Merge branch 'MDL-75105_401_STABLE' of https://github.com/marxjohnson/moodle into...
[moodle.git] / lib / moodlelib.php
blobd22c8dad008322aef187132b1e899f4627e5f0a1
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * moodlelib.php - Moodle main library
20 * Main library file of miscellaneous general-purpose Moodle functions.
21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - datalib.php - functions that access the database
25 * @package core
26 * @subpackage lib
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') || die();
33 // CONSTANTS (Encased in phpdoc proper comments).
35 // Date and time constants.
36 /**
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
41 /**
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
46 /**
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
51 /**
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
56 /**
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
61 /**
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
66 /**
67 * Time constant - the number of minutes in an hour
69 define('HOURMINS', 60);
71 // Parameter constants - every call to optional_param(), required_param()
72 // or clean_param() should have a specified type of parameter.
74 /**
75 * PARAM_ALPHA - contains only English ascii letters [a-zA-Z].
77 define('PARAM_ALPHA', 'alpha');
79 /**
80 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA (English ascii letters [a-zA-Z]) plus the chars in quotes: "_-" allowed
81 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
83 define('PARAM_ALPHAEXT', 'alphaext');
85 /**
86 * PARAM_ALPHANUM - expected numbers 0-9 and English ascii letters [a-zA-Z] only.
88 define('PARAM_ALPHANUM', 'alphanum');
90 /**
91 * PARAM_ALPHANUMEXT - expected numbers 0-9, letters (English ascii letters [a-zA-Z]) and _- only.
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
95 /**
96 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
98 define('PARAM_AUTH', 'auth');
101 * PARAM_BASE64 - Base 64 encoded format
103 define('PARAM_BASE64', 'base64');
106 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
108 define('PARAM_BOOL', 'bool');
111 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
112 * checked against the list of capabilities in the database.
114 define('PARAM_CAPABILITY', 'capability');
117 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118 * to use this. The normal mode of operation is to use PARAM_RAW when receiving
119 * the input (required/optional_param or formslib) and then sanitise the HTML
120 * using format_text on output. This is for the rare cases when you want to
121 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
123 define('PARAM_CLEANHTML', 'cleanhtml');
126 * PARAM_EMAIL - an email address following the RFC
128 define('PARAM_EMAIL', 'email');
131 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
133 define('PARAM_FILE', 'file');
136 * PARAM_FLOAT - a real/floating point number.
138 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
139 * It does not work for languages that use , as a decimal separator.
140 * Use PARAM_LOCALISEDFLOAT instead.
142 define('PARAM_FLOAT', 'float');
145 * PARAM_LOCALISEDFLOAT - a localised real/floating point number.
146 * This is preferred over PARAM_FLOAT for numbers typed in by the user.
147 * Cleans localised numbers to computer readable numbers; false for invalid numbers.
149 define('PARAM_LOCALISEDFLOAT', 'localisedfloat');
152 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
154 define('PARAM_HOST', 'host');
157 * PARAM_INT - integers only, use when expecting only numbers.
159 define('PARAM_INT', 'int');
162 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
164 define('PARAM_LANG', 'lang');
167 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
168 * others! Implies PARAM_URL!)
170 define('PARAM_LOCALURL', 'localurl');
173 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
175 define('PARAM_NOTAGS', 'notags');
178 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
179 * traversals note: the leading slash is not removed, window drive letter is not allowed
181 define('PARAM_PATH', 'path');
184 * PARAM_PEM - Privacy Enhanced Mail format
186 define('PARAM_PEM', 'pem');
189 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
191 define('PARAM_PERMISSION', 'permission');
194 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
196 define('PARAM_RAW', 'raw');
199 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
201 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
204 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
206 define('PARAM_SAFEDIR', 'safedir');
209 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths
210 * and other references to Moodle code files.
212 * This is NOT intended to be used for absolute paths or any user uploaded files.
214 define('PARAM_SAFEPATH', 'safepath');
217 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
219 define('PARAM_SEQUENCE', 'sequence');
222 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
224 define('PARAM_TAG', 'tag');
227 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
229 define('PARAM_TAGLIST', 'taglist');
232 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
234 define('PARAM_TEXT', 'text');
237 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
239 define('PARAM_THEME', 'theme');
242 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
243 * http://localhost.localdomain/ is ok.
245 define('PARAM_URL', 'url');
248 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
249 * accounts, do NOT use when syncing with external systems!!
251 define('PARAM_USERNAME', 'username');
254 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
256 define('PARAM_STRINGID', 'stringid');
258 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
260 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
261 * It was one of the first types, that is why it is abused so much ;-)
262 * @deprecated since 2.0
264 define('PARAM_CLEAN', 'clean');
267 * PARAM_INTEGER - deprecated alias for PARAM_INT
268 * @deprecated since 2.0
270 define('PARAM_INTEGER', 'int');
273 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
274 * @deprecated since 2.0
276 define('PARAM_NUMBER', 'float');
279 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
280 * NOTE: originally alias for PARAM_APLHA
281 * @deprecated since 2.0
283 define('PARAM_ACTION', 'alphanumext');
286 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
287 * NOTE: originally alias for PARAM_APLHA
288 * @deprecated since 2.0
290 define('PARAM_FORMAT', 'alphanumext');
293 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
294 * @deprecated since 2.0
296 define('PARAM_MULTILANG', 'text');
299 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
300 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
301 * America/Port-au-Prince)
303 define('PARAM_TIMEZONE', 'timezone');
306 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
308 define('PARAM_CLEANFILE', 'file');
311 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
312 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
313 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
314 * NOTE: numbers and underscores are strongly discouraged in plugin names!
316 define('PARAM_COMPONENT', 'component');
319 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
320 * It is usually used together with context id and component.
321 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
323 define('PARAM_AREA', 'area');
326 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
327 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
328 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
330 define('PARAM_PLUGIN', 'plugin');
333 // Web Services.
336 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
338 define('VALUE_REQUIRED', 1);
341 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
343 define('VALUE_OPTIONAL', 2);
346 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
348 define('VALUE_DEFAULT', 0);
351 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
353 define('NULL_NOT_ALLOWED', false);
356 * NULL_ALLOWED - the parameter can be set to null in the database
358 define('NULL_ALLOWED', true);
360 // Page types.
363 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
365 define('PAGE_COURSE_VIEW', 'course-view');
367 /** Get remote addr constant */
368 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
369 /** Get remote addr constant */
370 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
372 * GETREMOTEADDR_SKIP_DEFAULT defines the default behavior remote IP address validation.
374 define('GETREMOTEADDR_SKIP_DEFAULT', GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR|GETREMOTEADDR_SKIP_HTTP_CLIENT_IP);
376 // Blog access level constant declaration.
377 define ('BLOG_USER_LEVEL', 1);
378 define ('BLOG_GROUP_LEVEL', 2);
379 define ('BLOG_COURSE_LEVEL', 3);
380 define ('BLOG_SITE_LEVEL', 4);
381 define ('BLOG_GLOBAL_LEVEL', 5);
384 // Tag constants.
386 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
387 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
388 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
390 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
392 define('TAG_MAX_LENGTH', 50);
394 // Password policy constants.
395 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
396 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
397 define ('PASSWORD_DIGITS', '0123456789');
398 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
400 // Feature constants.
401 // Used for plugin_supports() to report features that are, or are not, supported by a module.
403 /** True if module can provide a grade */
404 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
405 /** True if module supports outcomes */
406 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
407 /** True if module supports advanced grading methods */
408 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
409 /** True if module controls the grade visibility over the gradebook */
410 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
411 /** True if module supports plagiarism plugins */
412 define('FEATURE_PLAGIARISM', 'plagiarism');
414 /** True if module has code to track whether somebody viewed it */
415 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
416 /** True if module has custom completion rules */
417 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
419 /** True if module has no 'view' page (like label) */
420 define('FEATURE_NO_VIEW_LINK', 'viewlink');
421 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
422 define('FEATURE_IDNUMBER', 'idnumber');
423 /** True if module supports groups */
424 define('FEATURE_GROUPS', 'groups');
425 /** True if module supports groupings */
426 define('FEATURE_GROUPINGS', 'groupings');
428 * True if module supports groupmembersonly (which no longer exists)
429 * @deprecated Since Moodle 2.8
431 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
433 /** Type of module */
434 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
435 /** True if module supports intro editor */
436 define('FEATURE_MOD_INTRO', 'mod_intro');
437 /** True if module has default completion */
438 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
440 define('FEATURE_COMMENT', 'comment');
442 define('FEATURE_RATE', 'rate');
443 /** True if module supports backup/restore of moodle2 format */
444 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
446 /** True if module can show description on course main page */
447 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
449 /** True if module uses the question bank */
450 define('FEATURE_USES_QUESTIONS', 'usesquestions');
453 * Maximum filename char size
455 define('MAX_FILENAME_SIZE', 100);
457 /** Unspecified module archetype */
458 define('MOD_ARCHETYPE_OTHER', 0);
459 /** Resource-like type module */
460 define('MOD_ARCHETYPE_RESOURCE', 1);
461 /** Assignment module archetype */
462 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
463 /** System (not user-addable) module archetype */
464 define('MOD_ARCHETYPE_SYSTEM', 3);
466 /** Type of module */
467 define('FEATURE_MOD_PURPOSE', 'mod_purpose');
468 /** Module purpose administration */
469 define('MOD_PURPOSE_ADMINISTRATION', 'administration');
470 /** Module purpose assessment */
471 define('MOD_PURPOSE_ASSESSMENT', 'assessment');
472 /** Module purpose communication */
473 define('MOD_PURPOSE_COLLABORATION', 'collaboration');
474 /** Module purpose communication */
475 define('MOD_PURPOSE_COMMUNICATION', 'communication');
476 /** Module purpose content */
477 define('MOD_PURPOSE_CONTENT', 'content');
478 /** Module purpose interface */
479 define('MOD_PURPOSE_INTERFACE', 'interface');
480 /** Module purpose other */
481 define('MOD_PURPOSE_OTHER', 'other');
484 * Security token used for allowing access
485 * from external application such as web services.
486 * Scripts do not use any session, performance is relatively
487 * low because we need to load access info in each request.
488 * Scripts are executed in parallel.
490 define('EXTERNAL_TOKEN_PERMANENT', 0);
493 * Security token used for allowing access
494 * of embedded applications, the code is executed in the
495 * active user session. Token is invalidated after user logs out.
496 * Scripts are executed serially - normal session locking is used.
498 define('EXTERNAL_TOKEN_EMBEDDED', 1);
501 * The home page should be the site home
503 define('HOMEPAGE_SITE', 0);
505 * The home page should be the users my page
507 define('HOMEPAGE_MY', 1);
509 * The home page can be chosen by the user
511 define('HOMEPAGE_USER', 2);
513 * The home page should be the users my courses page
515 define('HOMEPAGE_MYCOURSES', 3);
518 * URL of the Moodle sites registration portal.
520 defined('HUB_MOODLEORGHUBURL') || define('HUB_MOODLEORGHUBURL', 'https://stats.moodle.org');
523 * URL of the statistic server public key.
525 defined('HUB_STATSPUBLICKEY') || define('HUB_STATSPUBLICKEY', 'https://moodle.org/static/statspubkey.pem');
528 * Moodle mobile app service name
530 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
533 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
535 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
538 * Course display settings: display all sections on one page.
540 define('COURSE_DISPLAY_SINGLEPAGE', 0);
542 * Course display settings: split pages into a page per section.
544 define('COURSE_DISPLAY_MULTIPAGE', 1);
547 * Authentication constant: String used in password field when password is not stored.
549 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
552 * Email from header to never include via information.
554 define('EMAIL_VIA_NEVER', 0);
557 * Email from header to always include via information.
559 define('EMAIL_VIA_ALWAYS', 1);
562 * Email from header to only include via information if the address is no-reply.
564 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
567 * Contact site support form/link disabled.
569 define('CONTACT_SUPPORT_DISABLED', 0);
572 * Contact site support form/link only available to authenticated users.
574 define('CONTACT_SUPPORT_AUTHENTICATED', 1);
577 * Contact site support form/link available to anyone visiting the site.
579 define('CONTACT_SUPPORT_ANYONE', 2);
581 // PARAMETER HANDLING.
584 * Returns a particular value for the named variable, taken from
585 * POST or GET. If the parameter doesn't exist then an error is
586 * thrown because we require this variable.
588 * This function should be used to initialise all required values
589 * in a script that are based on parameters. Usually it will be
590 * used like this:
591 * $id = required_param('id', PARAM_INT);
593 * Please note the $type parameter is now required and the value can not be array.
595 * @param string $parname the name of the page parameter we want
596 * @param string $type expected type of parameter
597 * @return mixed
598 * @throws coding_exception
600 function required_param($parname, $type) {
601 if (func_num_args() != 2 or empty($parname) or empty($type)) {
602 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
604 // POST has precedence.
605 if (isset($_POST[$parname])) {
606 $param = $_POST[$parname];
607 } else if (isset($_GET[$parname])) {
608 $param = $_GET[$parname];
609 } else {
610 throw new \moodle_exception('missingparam', '', '', $parname);
613 if (is_array($param)) {
614 debugging('Invalid array parameter detected in required_param(): '.$parname);
615 // TODO: switch to fatal error in Moodle 2.3.
616 return required_param_array($parname, $type);
619 return clean_param($param, $type);
623 * Returns a particular array value for the named variable, taken from
624 * POST or GET. If the parameter doesn't exist then an error is
625 * thrown because we require this variable.
627 * This function should be used to initialise all required values
628 * in a script that are based on parameters. Usually it will be
629 * used like this:
630 * $ids = required_param_array('ids', PARAM_INT);
632 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
634 * @param string $parname the name of the page parameter we want
635 * @param string $type expected type of parameter
636 * @return array
637 * @throws coding_exception
639 function required_param_array($parname, $type) {
640 if (func_num_args() != 2 or empty($parname) or empty($type)) {
641 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
643 // POST has precedence.
644 if (isset($_POST[$parname])) {
645 $param = $_POST[$parname];
646 } else if (isset($_GET[$parname])) {
647 $param = $_GET[$parname];
648 } else {
649 throw new \moodle_exception('missingparam', '', '', $parname);
651 if (!is_array($param)) {
652 throw new \moodle_exception('missingparam', '', '', $parname);
655 $result = array();
656 foreach ($param as $key => $value) {
657 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
658 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
659 continue;
661 $result[$key] = clean_param($value, $type);
664 return $result;
668 * Returns a particular value for the named variable, taken from
669 * POST or GET, otherwise returning a given default.
671 * This function should be used to initialise all optional values
672 * in a script that are based on parameters. Usually it will be
673 * used like this:
674 * $name = optional_param('name', 'Fred', PARAM_TEXT);
676 * Please note the $type parameter is now required and the value can not be array.
678 * @param string $parname the name of the page parameter we want
679 * @param mixed $default the default value to return if nothing is found
680 * @param string $type expected type of parameter
681 * @return mixed
682 * @throws coding_exception
684 function optional_param($parname, $default, $type) {
685 if (func_num_args() != 3 or empty($parname) or empty($type)) {
686 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
689 // POST has precedence.
690 if (isset($_POST[$parname])) {
691 $param = $_POST[$parname];
692 } else if (isset($_GET[$parname])) {
693 $param = $_GET[$parname];
694 } else {
695 return $default;
698 if (is_array($param)) {
699 debugging('Invalid array parameter detected in required_param(): '.$parname);
700 // TODO: switch to $default in Moodle 2.3.
701 return optional_param_array($parname, $default, $type);
704 return clean_param($param, $type);
708 * Returns a particular array value for the named variable, taken from
709 * POST or GET, otherwise returning a given default.
711 * This function should be used to initialise all optional values
712 * in a script that are based on parameters. Usually it will be
713 * used like this:
714 * $ids = optional_param('id', array(), PARAM_INT);
716 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
718 * @param string $parname the name of the page parameter we want
719 * @param mixed $default the default value to return if nothing is found
720 * @param string $type expected type of parameter
721 * @return array
722 * @throws coding_exception
724 function optional_param_array($parname, $default, $type) {
725 if (func_num_args() != 3 or empty($parname) or empty($type)) {
726 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
729 // POST has precedence.
730 if (isset($_POST[$parname])) {
731 $param = $_POST[$parname];
732 } else if (isset($_GET[$parname])) {
733 $param = $_GET[$parname];
734 } else {
735 return $default;
737 if (!is_array($param)) {
738 debugging('optional_param_array() expects array parameters only: '.$parname);
739 return $default;
742 $result = array();
743 foreach ($param as $key => $value) {
744 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
745 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
746 continue;
748 $result[$key] = clean_param($value, $type);
751 return $result;
755 * Strict validation of parameter values, the values are only converted
756 * to requested PHP type. Internally it is using clean_param, the values
757 * before and after cleaning must be equal - otherwise
758 * an invalid_parameter_exception is thrown.
759 * Objects and classes are not accepted.
761 * @param mixed $param
762 * @param string $type PARAM_ constant
763 * @param bool $allownull are nulls valid value?
764 * @param string $debuginfo optional debug information
765 * @return mixed the $param value converted to PHP type
766 * @throws invalid_parameter_exception if $param is not of given type
768 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
769 if (is_null($param)) {
770 if ($allownull == NULL_ALLOWED) {
771 return null;
772 } else {
773 throw new invalid_parameter_exception($debuginfo);
776 if (is_array($param) or is_object($param)) {
777 throw new invalid_parameter_exception($debuginfo);
780 $cleaned = clean_param($param, $type);
782 if ($type == PARAM_FLOAT) {
783 // Do not detect precision loss here.
784 if (is_float($param) or is_int($param)) {
785 // These always fit.
786 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
787 throw new invalid_parameter_exception($debuginfo);
789 } else if ((string)$param !== (string)$cleaned) {
790 // Conversion to string is usually lossless.
791 throw new invalid_parameter_exception($debuginfo);
794 return $cleaned;
798 * Makes sure array contains only the allowed types, this function does not validate array key names!
800 * <code>
801 * $options = clean_param($options, PARAM_INT);
802 * </code>
804 * @param array|null $param the variable array we are cleaning
805 * @param string $type expected format of param after cleaning.
806 * @param bool $recursive clean recursive arrays
807 * @return array
808 * @throws coding_exception
810 function clean_param_array(?array $param, $type, $recursive = false) {
811 // Convert null to empty array.
812 $param = (array)$param;
813 foreach ($param as $key => $value) {
814 if (is_array($value)) {
815 if ($recursive) {
816 $param[$key] = clean_param_array($value, $type, true);
817 } else {
818 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
820 } else {
821 $param[$key] = clean_param($value, $type);
824 return $param;
828 * Used by {@link optional_param()} and {@link required_param()} to
829 * clean the variables and/or cast to specific types, based on
830 * an options field.
831 * <code>
832 * $course->format = clean_param($course->format, PARAM_ALPHA);
833 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
834 * </code>
836 * @param mixed $param the variable we are cleaning
837 * @param string $type expected format of param after cleaning.
838 * @return mixed
839 * @throws coding_exception
841 function clean_param($param, $type) {
842 global $CFG;
844 if (is_array($param)) {
845 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
846 } else if (is_object($param)) {
847 if (method_exists($param, '__toString')) {
848 $param = $param->__toString();
849 } else {
850 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
854 switch ($type) {
855 case PARAM_RAW:
856 // No cleaning at all.
857 $param = fix_utf8($param);
858 return $param;
860 case PARAM_RAW_TRIMMED:
861 // No cleaning, but strip leading and trailing whitespace.
862 $param = (string)fix_utf8($param);
863 return trim($param);
865 case PARAM_CLEAN:
866 // General HTML cleaning, try to use more specific type if possible this is deprecated!
867 // Please use more specific type instead.
868 if (is_numeric($param)) {
869 return $param;
871 $param = fix_utf8($param);
872 // Sweep for scripts, etc.
873 return clean_text($param);
875 case PARAM_CLEANHTML:
876 // Clean html fragment.
877 $param = (string)fix_utf8($param);
878 // Sweep for scripts, etc.
879 $param = clean_text($param, FORMAT_HTML);
880 return trim($param);
882 case PARAM_INT:
883 // Convert to integer.
884 return (int)$param;
886 case PARAM_FLOAT:
887 // Convert to float.
888 return (float)$param;
890 case PARAM_LOCALISEDFLOAT:
891 // Convert to float.
892 return unformat_float($param, true);
894 case PARAM_ALPHA:
895 // Remove everything not `a-z`.
896 return preg_replace('/[^a-zA-Z]/i', '', (string)$param);
898 case PARAM_ALPHAEXT:
899 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
900 return preg_replace('/[^a-zA-Z_-]/i', '', (string)$param);
902 case PARAM_ALPHANUM:
903 // Remove everything not `a-zA-Z0-9`.
904 return preg_replace('/[^A-Za-z0-9]/i', '', (string)$param);
906 case PARAM_ALPHANUMEXT:
907 // Remove everything not `a-zA-Z0-9_-`.
908 return preg_replace('/[^A-Za-z0-9_-]/i', '', (string)$param);
910 case PARAM_SEQUENCE:
911 // Remove everything not `0-9,`.
912 return preg_replace('/[^0-9,]/i', '', (string)$param);
914 case PARAM_BOOL:
915 // Convert to 1 or 0.
916 $tempstr = strtolower((string)$param);
917 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
918 $param = 1;
919 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
920 $param = 0;
921 } else {
922 $param = empty($param) ? 0 : 1;
924 return $param;
926 case PARAM_NOTAGS:
927 // Strip all tags.
928 $param = fix_utf8($param);
929 return strip_tags((string)$param);
931 case PARAM_TEXT:
932 // Leave only tags needed for multilang.
933 $param = fix_utf8($param);
934 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
935 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
936 do {
937 if (strpos((string)$param, '</lang>') !== false) {
938 // Old and future mutilang syntax.
939 $param = strip_tags($param, '<lang>');
940 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
941 break;
943 $open = false;
944 foreach ($matches[0] as $match) {
945 if ($match === '</lang>') {
946 if ($open) {
947 $open = false;
948 continue;
949 } else {
950 break 2;
953 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
954 break 2;
955 } else {
956 $open = true;
959 if ($open) {
960 break;
962 return $param;
964 } else if (strpos((string)$param, '</span>') !== false) {
965 // Current problematic multilang syntax.
966 $param = strip_tags($param, '<span>');
967 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
968 break;
970 $open = false;
971 foreach ($matches[0] as $match) {
972 if ($match === '</span>') {
973 if ($open) {
974 $open = false;
975 continue;
976 } else {
977 break 2;
980 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
981 break 2;
982 } else {
983 $open = true;
986 if ($open) {
987 break;
989 return $param;
991 } while (false);
992 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
993 return strip_tags((string)$param);
995 case PARAM_COMPONENT:
996 // We do not want any guessing here, either the name is correct or not
997 // please note only normalised component names are accepted.
998 $param = (string)$param;
999 if (!preg_match('/^[a-z][a-z0-9]*(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
1000 return '';
1002 if (strpos($param, '__') !== false) {
1003 return '';
1005 if (strpos($param, 'mod_') === 0) {
1006 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
1007 if (substr_count($param, '_') != 1) {
1008 return '';
1011 return $param;
1013 case PARAM_PLUGIN:
1014 case PARAM_AREA:
1015 // We do not want any guessing here, either the name is correct or not.
1016 if (!is_valid_plugin_name($param)) {
1017 return '';
1019 return $param;
1021 case PARAM_SAFEDIR:
1022 // Remove everything not a-zA-Z0-9_- .
1023 return preg_replace('/[^a-zA-Z0-9_-]/i', '', (string)$param);
1025 case PARAM_SAFEPATH:
1026 // Remove everything not a-zA-Z0-9/_- .
1027 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', (string)$param);
1029 case PARAM_FILE:
1030 // Strip all suspicious characters from filename.
1031 $param = (string)fix_utf8($param);
1032 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
1033 if ($param === '.' || $param === '..') {
1034 $param = '';
1036 return $param;
1038 case PARAM_PATH:
1039 // Strip all suspicious characters from file path.
1040 $param = (string)fix_utf8($param);
1041 $param = str_replace('\\', '/', $param);
1043 // Explode the path and clean each element using the PARAM_FILE rules.
1044 $breadcrumb = explode('/', $param);
1045 foreach ($breadcrumb as $key => $crumb) {
1046 if ($crumb === '.' && $key === 0) {
1047 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1048 } else {
1049 $crumb = clean_param($crumb, PARAM_FILE);
1051 $breadcrumb[$key] = $crumb;
1053 $param = implode('/', $breadcrumb);
1055 // Remove multiple current path (./././) and multiple slashes (///).
1056 $param = preg_replace('~//+~', '/', $param);
1057 $param = preg_replace('~/(\./)+~', '/', $param);
1058 return $param;
1060 case PARAM_HOST:
1061 // Allow FQDN or IPv4 dotted quad.
1062 $param = preg_replace('/[^\.\d\w-]/', '', (string)$param );
1063 // Match ipv4 dotted quad.
1064 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1065 // Confirm values are ok.
1066 if ( $match[0] > 255
1067 || $match[1] > 255
1068 || $match[3] > 255
1069 || $match[4] > 255 ) {
1070 // Hmmm, what kind of dotted quad is this?
1071 $param = '';
1073 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1074 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1075 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1077 // All is ok - $param is respected.
1078 } else {
1079 // All is not ok...
1080 $param='';
1082 return $param;
1084 case PARAM_URL:
1085 // Allow safe urls.
1086 $param = (string)fix_utf8($param);
1087 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1088 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1089 // All is ok, param is respected.
1090 } else {
1091 // Not really ok.
1092 $param ='';
1094 return $param;
1096 case PARAM_LOCALURL:
1097 // Allow http absolute, root relative and relative URLs within wwwroot.
1098 $param = clean_param($param, PARAM_URL);
1099 if (!empty($param)) {
1101 if ($param === $CFG->wwwroot) {
1102 // Exact match;
1103 } else if (preg_match(':^/:', $param)) {
1104 // Root-relative, ok!
1105 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1106 // Absolute, and matches our wwwroot.
1107 } else {
1109 // Relative - let's make sure there are no tricks.
1110 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?') && !preg_match('/javascript:/i', $param)) {
1111 // Looks ok.
1112 } else {
1113 $param = '';
1117 return $param;
1119 case PARAM_PEM:
1120 $param = trim((string)$param);
1121 // PEM formatted strings may contain letters/numbers and the symbols:
1122 // forward slash: /
1123 // plus sign: +
1124 // equal sign: =
1125 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1126 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1127 list($wholething, $body) = $matches;
1128 unset($wholething, $matches);
1129 $b64 = clean_param($body, PARAM_BASE64);
1130 if (!empty($b64)) {
1131 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1132 } else {
1133 return '';
1136 return '';
1138 case PARAM_BASE64:
1139 if (!empty($param)) {
1140 // PEM formatted strings may contain letters/numbers and the symbols
1141 // forward slash: /
1142 // plus sign: +
1143 // equal sign: =.
1144 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1145 return '';
1147 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1148 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1149 // than (or equal to) 64 characters long.
1150 for ($i=0, $j=count($lines); $i < $j; $i++) {
1151 if ($i + 1 == $j) {
1152 if (64 < strlen($lines[$i])) {
1153 return '';
1155 continue;
1158 if (64 != strlen($lines[$i])) {
1159 return '';
1162 return implode("\n", $lines);
1163 } else {
1164 return '';
1167 case PARAM_TAG:
1168 $param = (string)fix_utf8($param);
1169 // Please note it is not safe to use the tag name directly anywhere,
1170 // it must be processed with s(), urlencode() before embedding anywhere.
1171 // Remove some nasties.
1172 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1173 // Convert many whitespace chars into one.
1174 $param = preg_replace('/\s+/u', ' ', $param);
1175 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1176 return $param;
1178 case PARAM_TAGLIST:
1179 $param = (string)fix_utf8($param);
1180 $tags = explode(',', $param);
1181 $result = array();
1182 foreach ($tags as $tag) {
1183 $res = clean_param($tag, PARAM_TAG);
1184 if ($res !== '') {
1185 $result[] = $res;
1188 if ($result) {
1189 return implode(',', $result);
1190 } else {
1191 return '';
1194 case PARAM_CAPABILITY:
1195 if (get_capability_info($param)) {
1196 return $param;
1197 } else {
1198 return '';
1201 case PARAM_PERMISSION:
1202 $param = (int)$param;
1203 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1204 return $param;
1205 } else {
1206 return CAP_INHERIT;
1209 case PARAM_AUTH:
1210 $param = clean_param($param, PARAM_PLUGIN);
1211 if (empty($param)) {
1212 return '';
1213 } else if (exists_auth_plugin($param)) {
1214 return $param;
1215 } else {
1216 return '';
1219 case PARAM_LANG:
1220 $param = clean_param($param, PARAM_SAFEDIR);
1221 if (get_string_manager()->translation_exists($param)) {
1222 return $param;
1223 } else {
1224 // Specified language is not installed or param malformed.
1225 return '';
1228 case PARAM_THEME:
1229 $param = clean_param($param, PARAM_PLUGIN);
1230 if (empty($param)) {
1231 return '';
1232 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1233 return $param;
1234 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1235 return $param;
1236 } else {
1237 // Specified theme is not installed.
1238 return '';
1241 case PARAM_USERNAME:
1242 $param = (string)fix_utf8($param);
1243 $param = trim($param);
1244 // Convert uppercase to lowercase MDL-16919.
1245 $param = core_text::strtolower($param);
1246 if (empty($CFG->extendedusernamechars)) {
1247 $param = str_replace(" " , "", $param);
1248 // Regular expression, eliminate all chars EXCEPT:
1249 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1250 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1252 return $param;
1254 case PARAM_EMAIL:
1255 $param = fix_utf8($param);
1256 if (validate_email($param ?? '')) {
1257 return $param;
1258 } else {
1259 return '';
1262 case PARAM_STRINGID:
1263 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', (string)$param)) {
1264 return $param;
1265 } else {
1266 return '';
1269 case PARAM_TIMEZONE:
1270 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1271 $param = (string)fix_utf8($param);
1272 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1273 if (preg_match($timezonepattern, $param)) {
1274 return $param;
1275 } else {
1276 return '';
1279 default:
1280 // Doh! throw error, switched parameters in optional_param or another serious problem.
1281 throw new \moodle_exception("unknownparamtype", '', '', $type);
1286 * Whether the PARAM_* type is compatible in RTL.
1288 * Being compatible with RTL means that the data they contain can flow
1289 * from right-to-left or left-to-right without compromising the user experience.
1291 * Take URLs for example, they are not RTL compatible as they should always
1292 * flow from the left to the right. This also applies to numbers, email addresses,
1293 * configuration snippets, base64 strings, etc...
1295 * This function tries to best guess which parameters can contain localised strings.
1297 * @param string $paramtype Constant PARAM_*.
1298 * @return bool
1300 function is_rtl_compatible($paramtype) {
1301 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1305 * Makes sure the data is using valid utf8, invalid characters are discarded.
1307 * Note: this function is not intended for full objects with methods and private properties.
1309 * @param mixed $value
1310 * @return mixed with proper utf-8 encoding
1312 function fix_utf8($value) {
1313 if (is_null($value) or $value === '') {
1314 return $value;
1316 } else if (is_string($value)) {
1317 if ((string)(int)$value === $value) {
1318 // Shortcut.
1319 return $value;
1321 // No null bytes expected in our data, so let's remove it.
1322 $value = str_replace("\0", '', $value);
1324 // Note: this duplicates min_fix_utf8() intentionally.
1325 static $buggyiconv = null;
1326 if ($buggyiconv === null) {
1327 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1330 if ($buggyiconv) {
1331 if (function_exists('mb_convert_encoding')) {
1332 $subst = mb_substitute_character();
1333 mb_substitute_character('none');
1334 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1335 mb_substitute_character($subst);
1337 } else {
1338 // Warn admins on admin/index.php page.
1339 $result = $value;
1342 } else {
1343 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1346 return $result;
1348 } else if (is_array($value)) {
1349 foreach ($value as $k => $v) {
1350 $value[$k] = fix_utf8($v);
1352 return $value;
1354 } else if (is_object($value)) {
1355 // Do not modify original.
1356 $value = clone($value);
1357 foreach ($value as $k => $v) {
1358 $value->$k = fix_utf8($v);
1360 return $value;
1362 } else {
1363 // This is some other type, no utf-8 here.
1364 return $value;
1369 * Return true if given value is integer or string with integer value
1371 * @param mixed $value String or Int
1372 * @return bool true if number, false if not
1374 function is_number($value) {
1375 if (is_int($value)) {
1376 return true;
1377 } else if (is_string($value)) {
1378 return ((string)(int)$value) === $value;
1379 } else {
1380 return false;
1385 * Returns host part from url.
1387 * @param string $url full url
1388 * @return string host, null if not found
1390 function get_host_from_url($url) {
1391 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1392 if ($matches) {
1393 return $matches[1];
1395 return null;
1399 * Tests whether anything was returned by text editor
1401 * This function is useful for testing whether something you got back from
1402 * the HTML editor actually contains anything. Sometimes the HTML editor
1403 * appear to be empty, but actually you get back a <br> tag or something.
1405 * @param string $string a string containing HTML.
1406 * @return boolean does the string contain any actual content - that is text,
1407 * images, objects, etc.
1409 function html_is_blank($string) {
1410 return trim(strip_tags((string)$string, '<img><object><applet><input><select><textarea><hr>')) == '';
1414 * Set a key in global configuration
1416 * Set a key/value pair in both this session's {@link $CFG} global variable
1417 * and in the 'config' database table for future sessions.
1419 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1420 * In that case it doesn't affect $CFG.
1422 * A NULL value will delete the entry.
1424 * NOTE: this function is called from lib/db/upgrade.php
1426 * @param string $name the key to set
1427 * @param string $value the value to set (without magic quotes)
1428 * @param string $plugin (optional) the plugin scope, default null
1429 * @return bool true or exception
1431 function set_config($name, $value, $plugin = null) {
1432 global $CFG, $DB;
1434 // Redirect to appropriate handler when value is null.
1435 if ($value === null) {
1436 return unset_config($name, $plugin);
1439 // Set variables determining conditions and where to store the new config.
1440 // Plugin config goes to {config_plugins}, core config goes to {config}.
1441 $iscore = empty($plugin);
1442 if ($iscore) {
1443 // If it's for core config.
1444 $table = 'config';
1445 $conditions = ['name' => $name];
1446 $invalidatecachekey = 'core';
1447 } else {
1448 // If it's a plugin.
1449 $table = 'config_plugins';
1450 $conditions = ['name' => $name, 'plugin' => $plugin];
1451 $invalidatecachekey = $plugin;
1454 // DB handling - checks for existing config, updating or inserting only if necessary.
1455 $invalidatecache = true;
1456 $inserted = false;
1457 $record = $DB->get_record($table, $conditions, 'id, value');
1458 if ($record === false) {
1459 // Inserts a new config record.
1460 $config = new stdClass();
1461 $config->name = $name;
1462 $config->value = $value;
1463 if (!$iscore) {
1464 $config->plugin = $plugin;
1466 $inserted = $DB->insert_record($table, $config, false);
1467 } else if ($invalidatecache = ($record->value !== $value)) {
1468 // Record exists - Check and only set new value if it has changed.
1469 $DB->set_field($table, 'value', $value, ['id' => $record->id]);
1472 if ($iscore && !isset($CFG->config_php_settings[$name])) {
1473 // So it's defined for this invocation at least.
1474 // Settings from db are always strings.
1475 $CFG->$name = (string) $value;
1478 // When setting config during a Behat test (in the CLI script, not in the web browser
1479 // requests), remember which ones are set so that we can clear them later.
1480 if ($iscore && $inserted && defined('BEHAT_TEST')) {
1481 $CFG->behat_cli_added_config[$name] = true;
1484 // Update siteidentifier cache, if required.
1485 if ($iscore && $name === 'siteidentifier') {
1486 cache_helper::update_site_identifier($value);
1489 // Invalidate cache, if required.
1490 if ($invalidatecache) {
1491 cache_helper::invalidate_by_definition('core', 'config', [], $invalidatecachekey);
1494 return true;
1498 * Get configuration values from the global config table
1499 * or the config_plugins table.
1501 * If called with one parameter, it will load all the config
1502 * variables for one plugin, and return them as an object.
1504 * If called with 2 parameters it will return a string single
1505 * value or false if the value is not found.
1507 * NOTE: this function is called from lib/db/upgrade.php
1509 * @param string $plugin full component name
1510 * @param string $name default null
1511 * @return mixed hash-like object or single value, return false no config found
1512 * @throws dml_exception
1514 function get_config($plugin, $name = null) {
1515 global $CFG, $DB;
1517 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1518 $forced =& $CFG->config_php_settings;
1519 $iscore = true;
1520 $plugin = 'core';
1521 } else {
1522 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1523 $forced =& $CFG->forced_plugin_settings[$plugin];
1524 } else {
1525 $forced = array();
1527 $iscore = false;
1530 if (!isset($CFG->siteidentifier)) {
1531 try {
1532 // This may throw an exception during installation, which is how we detect the
1533 // need to install the database. For more details see {@see initialise_cfg()}.
1534 $CFG->siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1535 } catch (dml_exception $ex) {
1536 // Set siteidentifier to false. We don't want to trip this continually.
1537 $siteidentifier = false;
1538 throw $ex;
1542 if (!empty($name)) {
1543 if (array_key_exists($name, $forced)) {
1544 return (string)$forced[$name];
1545 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1546 return $CFG->siteidentifier;
1550 $cache = cache::make('core', 'config');
1551 $result = $cache->get($plugin);
1552 if ($result === false) {
1553 // The user is after a recordset.
1554 if (!$iscore) {
1555 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1556 } else {
1557 // This part is not really used any more, but anyway...
1558 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1560 $cache->set($plugin, $result);
1563 if (!empty($name)) {
1564 if (array_key_exists($name, $result)) {
1565 return $result[$name];
1567 return false;
1570 if ($plugin === 'core') {
1571 $result['siteidentifier'] = $CFG->siteidentifier;
1574 foreach ($forced as $key => $value) {
1575 if (is_null($value) or is_array($value) or is_object($value)) {
1576 // We do not want any extra mess here, just real settings that could be saved in db.
1577 unset($result[$key]);
1578 } else {
1579 // Convert to string as if it went through the DB.
1580 $result[$key] = (string)$value;
1584 return (object)$result;
1588 * Removes a key from global configuration.
1590 * NOTE: this function is called from lib/db/upgrade.php
1592 * @param string $name the key to set
1593 * @param string $plugin (optional) the plugin scope
1594 * @return boolean whether the operation succeeded.
1596 function unset_config($name, $plugin=null) {
1597 global $CFG, $DB;
1599 if (empty($plugin)) {
1600 unset($CFG->$name);
1601 $DB->delete_records('config', array('name' => $name));
1602 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1603 } else {
1604 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1605 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1608 return true;
1612 * Remove all the config variables for a given plugin.
1614 * NOTE: this function is called from lib/db/upgrade.php
1616 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1617 * @return boolean whether the operation succeeded.
1619 function unset_all_config_for_plugin($plugin) {
1620 global $DB;
1621 // Delete from the obvious config_plugins first.
1622 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1623 // Next delete any suspect settings from config.
1624 $like = $DB->sql_like('name', '?', true, true, false, '|');
1625 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1626 $DB->delete_records_select('config', $like, $params);
1627 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1628 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1630 return true;
1634 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1636 * All users are verified if they still have the necessary capability.
1638 * @param string $value the value of the config setting.
1639 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1640 * @param bool $includeadmins include administrators.
1641 * @return array of user objects.
1643 function get_users_from_config($value, $capability, $includeadmins = true) {
1644 if (empty($value) or $value === '$@NONE@$') {
1645 return array();
1648 // We have to make sure that users still have the necessary capability,
1649 // it should be faster to fetch them all first and then test if they are present
1650 // instead of validating them one-by-one.
1651 $users = get_users_by_capability(context_system::instance(), $capability);
1652 if ($includeadmins) {
1653 $admins = get_admins();
1654 foreach ($admins as $admin) {
1655 $users[$admin->id] = $admin;
1659 if ($value === '$@ALL@$') {
1660 return $users;
1663 $result = array(); // Result in correct order.
1664 $allowed = explode(',', $value);
1665 foreach ($allowed as $uid) {
1666 if (isset($users[$uid])) {
1667 $user = $users[$uid];
1668 $result[$user->id] = $user;
1672 return $result;
1677 * Invalidates browser caches and cached data in temp.
1679 * @return void
1681 function purge_all_caches() {
1682 purge_caches();
1686 * Selectively invalidate different types of cache.
1688 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1689 * areas alone or in combination.
1691 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1692 * 'muc' Purge MUC caches?
1693 * 'theme' Purge theme cache?
1694 * 'lang' Purge language string cache?
1695 * 'js' Purge javascript cache?
1696 * 'filter' Purge text filter cache?
1697 * 'other' Purge all other caches?
1699 function purge_caches($options = []) {
1700 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1701 if (empty(array_filter($options))) {
1702 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1703 } else {
1704 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1706 if ($options['muc']) {
1707 cache_helper::purge_all();
1709 if ($options['theme']) {
1710 theme_reset_all_caches();
1712 if ($options['lang']) {
1713 get_string_manager()->reset_caches();
1715 if ($options['js']) {
1716 js_reset_all_caches();
1718 if ($options['template']) {
1719 template_reset_all_caches();
1721 if ($options['filter']) {
1722 reset_text_filters_cache();
1724 if ($options['other']) {
1725 purge_other_caches();
1730 * Purge all non-MUC caches not otherwise purged in purge_caches.
1732 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1733 * {@link phpunit_util::reset_dataroot()}
1735 function purge_other_caches() {
1736 global $DB, $CFG;
1737 if (class_exists('core_plugin_manager')) {
1738 core_plugin_manager::reset_caches();
1741 // Bump up cacherev field for all courses.
1742 try {
1743 increment_revision_number('course', 'cacherev', '');
1744 } catch (moodle_exception $e) {
1745 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1748 $DB->reset_caches();
1750 // Purge all other caches: rss, simplepie, etc.
1751 clearstatcache();
1752 remove_dir($CFG->cachedir.'', true);
1754 // Make sure cache dir is writable, throws exception if not.
1755 make_cache_directory('');
1757 // This is the only place where we purge local caches, we are only adding files there.
1758 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1759 remove_dir($CFG->localcachedir, true);
1760 set_config('localcachedirpurged', time());
1761 make_localcache_directory('', true);
1762 \core\task\manager::clear_static_caches();
1766 * Get volatile flags
1768 * @param string $type
1769 * @param int $changedsince default null
1770 * @return array records array
1772 function get_cache_flags($type, $changedsince = null) {
1773 global $DB;
1775 $params = array('type' => $type, 'expiry' => time());
1776 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1777 if ($changedsince !== null) {
1778 $params['changedsince'] = $changedsince;
1779 $sqlwhere .= " AND timemodified > :changedsince";
1781 $cf = array();
1782 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1783 foreach ($flags as $flag) {
1784 $cf[$flag->name] = $flag->value;
1787 return $cf;
1791 * Get volatile flags
1793 * @param string $type
1794 * @param string $name
1795 * @param int $changedsince default null
1796 * @return string|false The cache flag value or false
1798 function get_cache_flag($type, $name, $changedsince=null) {
1799 global $DB;
1801 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1803 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1804 if ($changedsince !== null) {
1805 $params['changedsince'] = $changedsince;
1806 $sqlwhere .= " AND timemodified > :changedsince";
1809 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1813 * Set a volatile flag
1815 * @param string $type the "type" namespace for the key
1816 * @param string $name the key to set
1817 * @param string $value the value to set (without magic quotes) - null will remove the flag
1818 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1819 * @return bool Always returns true
1821 function set_cache_flag($type, $name, $value, $expiry = null) {
1822 global $DB;
1824 $timemodified = time();
1825 if ($expiry === null || $expiry < $timemodified) {
1826 $expiry = $timemodified + 24 * 60 * 60;
1827 } else {
1828 $expiry = (int)$expiry;
1831 if ($value === null) {
1832 unset_cache_flag($type, $name);
1833 return true;
1836 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1837 // This is a potential problem in DEBUG_DEVELOPER.
1838 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1839 return true; // No need to update.
1841 $f->value = $value;
1842 $f->expiry = $expiry;
1843 $f->timemodified = $timemodified;
1844 $DB->update_record('cache_flags', $f);
1845 } else {
1846 $f = new stdClass();
1847 $f->flagtype = $type;
1848 $f->name = $name;
1849 $f->value = $value;
1850 $f->expiry = $expiry;
1851 $f->timemodified = $timemodified;
1852 $DB->insert_record('cache_flags', $f);
1854 return true;
1858 * Removes a single volatile flag
1860 * @param string $type the "type" namespace for the key
1861 * @param string $name the key to set
1862 * @return bool
1864 function unset_cache_flag($type, $name) {
1865 global $DB;
1866 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1867 return true;
1871 * Garbage-collect volatile flags
1873 * @return bool Always returns true
1875 function gc_cache_flags() {
1876 global $DB;
1877 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1878 return true;
1881 // USER PREFERENCE API.
1884 * Refresh user preference cache. This is used most often for $USER
1885 * object that is stored in session, but it also helps with performance in cron script.
1887 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1889 * @package core
1890 * @category preference
1891 * @access public
1892 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1893 * @param int $cachelifetime Cache life time on the current page (in seconds)
1894 * @throws coding_exception
1895 * @return null
1897 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1898 global $DB;
1899 // Static cache, we need to check on each page load, not only every 2 minutes.
1900 static $loadedusers = array();
1902 if (!isset($user->id)) {
1903 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1906 if (empty($user->id) or isguestuser($user->id)) {
1907 // No permanent storage for not-logged-in users and guest.
1908 if (!isset($user->preference)) {
1909 $user->preference = array();
1911 return;
1914 $timenow = time();
1916 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1917 // Already loaded at least once on this page. Are we up to date?
1918 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1919 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1920 return;
1922 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1923 // No change since the lastcheck on this page.
1924 $user->preference['_lastloaded'] = $timenow;
1925 return;
1929 // OK, so we have to reload all preferences.
1930 $loadedusers[$user->id] = true;
1931 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1932 $user->preference['_lastloaded'] = $timenow;
1936 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1938 * NOTE: internal function, do not call from other code.
1940 * @package core
1941 * @access private
1942 * @param integer $userid the user whose prefs were changed.
1944 function mark_user_preferences_changed($userid) {
1945 global $CFG;
1947 if (empty($userid) or isguestuser($userid)) {
1948 // No cache flags for guest and not-logged-in users.
1949 return;
1952 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1956 * Sets a preference for the specified user.
1958 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1960 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1962 * @package core
1963 * @category preference
1964 * @access public
1965 * @param string $name The key to set as preference for the specified user
1966 * @param string $value The value to set for the $name key in the specified user's
1967 * record, null means delete current value.
1968 * @param stdClass|int|null $user A moodle user object or id, null means current user
1969 * @throws coding_exception
1970 * @return bool Always true or exception
1972 function set_user_preference($name, $value, $user = null) {
1973 global $USER, $DB;
1975 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1976 throw new coding_exception('Invalid preference name in set_user_preference() call');
1979 if (is_null($value)) {
1980 // Null means delete current.
1981 return unset_user_preference($name, $user);
1982 } else if (is_object($value)) {
1983 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1984 } else if (is_array($value)) {
1985 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1987 // Value column maximum length is 1333 characters.
1988 $value = (string)$value;
1989 if (core_text::strlen($value) > 1333) {
1990 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1993 if (is_null($user)) {
1994 $user = $USER;
1995 } else if (isset($user->id)) {
1996 // It is a valid object.
1997 } else if (is_numeric($user)) {
1998 $user = (object)array('id' => (int)$user);
1999 } else {
2000 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
2003 check_user_preferences_loaded($user);
2005 if (empty($user->id) or isguestuser($user->id)) {
2006 // No permanent storage for not-logged-in users and guest.
2007 $user->preference[$name] = $value;
2008 return true;
2011 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
2012 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
2013 // Preference already set to this value.
2014 return true;
2016 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
2018 } else {
2019 $preference = new stdClass();
2020 $preference->userid = $user->id;
2021 $preference->name = $name;
2022 $preference->value = $value;
2023 $DB->insert_record('user_preferences', $preference);
2026 // Update value in cache.
2027 $user->preference[$name] = $value;
2028 // Update the $USER in case where we've not a direct reference to $USER.
2029 if ($user !== $USER && $user->id == $USER->id) {
2030 $USER->preference[$name] = $value;
2033 // Set reload flag for other sessions.
2034 mark_user_preferences_changed($user->id);
2036 return true;
2040 * Sets a whole array of preferences for the current user
2042 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2044 * @package core
2045 * @category preference
2046 * @access public
2047 * @param array $prefarray An array of key/value pairs to be set
2048 * @param stdClass|int|null $user A moodle user object or id, null means current user
2049 * @return bool Always true or exception
2051 function set_user_preferences(array $prefarray, $user = null) {
2052 foreach ($prefarray as $name => $value) {
2053 set_user_preference($name, $value, $user);
2055 return true;
2059 * Unsets a preference completely by deleting it from the database
2061 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2063 * @package core
2064 * @category preference
2065 * @access public
2066 * @param string $name The key to unset as preference for the specified user
2067 * @param stdClass|int|null $user A moodle user object or id, null means current user
2068 * @throws coding_exception
2069 * @return bool Always true or exception
2071 function unset_user_preference($name, $user = null) {
2072 global $USER, $DB;
2074 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2075 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2078 if (is_null($user)) {
2079 $user = $USER;
2080 } else if (isset($user->id)) {
2081 // It is a valid object.
2082 } else if (is_numeric($user)) {
2083 $user = (object)array('id' => (int)$user);
2084 } else {
2085 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2088 check_user_preferences_loaded($user);
2090 if (empty($user->id) or isguestuser($user->id)) {
2091 // No permanent storage for not-logged-in user and guest.
2092 unset($user->preference[$name]);
2093 return true;
2096 // Delete from DB.
2097 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2099 // Delete the preference from cache.
2100 unset($user->preference[$name]);
2101 // Update the $USER in case where we've not a direct reference to $USER.
2102 if ($user !== $USER && $user->id == $USER->id) {
2103 unset($USER->preference[$name]);
2106 // Set reload flag for other sessions.
2107 mark_user_preferences_changed($user->id);
2109 return true;
2113 * Used to fetch user preference(s)
2115 * If no arguments are supplied this function will return
2116 * all of the current user preferences as an array.
2118 * If a name is specified then this function
2119 * attempts to return that particular preference value. If
2120 * none is found, then the optional value $default is returned,
2121 * otherwise null.
2123 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2125 * @package core
2126 * @category preference
2127 * @access public
2128 * @param string $name Name of the key to use in finding a preference value
2129 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2130 * @param stdClass|int|null $user A moodle user object or id, null means current user
2131 * @throws coding_exception
2132 * @return string|mixed|null A string containing the value of a single preference. An
2133 * array with all of the preferences or null
2135 function get_user_preferences($name = null, $default = null, $user = null) {
2136 global $USER;
2138 if (is_null($name)) {
2139 // All prefs.
2140 } else if (is_numeric($name) or $name === '_lastloaded') {
2141 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2144 if (is_null($user)) {
2145 $user = $USER;
2146 } else if (isset($user->id)) {
2147 // Is a valid object.
2148 } else if (is_numeric($user)) {
2149 if ($USER->id == $user) {
2150 $user = $USER;
2151 } else {
2152 $user = (object)array('id' => (int)$user);
2154 } else {
2155 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2158 check_user_preferences_loaded($user);
2160 if (empty($name)) {
2161 // All values.
2162 return $user->preference;
2163 } else if (isset($user->preference[$name])) {
2164 // The single string value.
2165 return $user->preference[$name];
2166 } else {
2167 // Default value (null if not specified).
2168 return $default;
2172 // FUNCTIONS FOR HANDLING TIME.
2175 * Given Gregorian date parts in user time produce a GMT timestamp.
2177 * @package core
2178 * @category time
2179 * @param int $year The year part to create timestamp of
2180 * @param int $month The month part to create timestamp of
2181 * @param int $day The day part to create timestamp of
2182 * @param int $hour The hour part to create timestamp of
2183 * @param int $minute The minute part to create timestamp of
2184 * @param int $second The second part to create timestamp of
2185 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2186 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2187 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2188 * applied only if timezone is 99 or string.
2189 * @return int GMT timestamp
2191 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2192 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2193 $date->setDate((int)$year, (int)$month, (int)$day);
2194 $date->setTime((int)$hour, (int)$minute, (int)$second);
2196 $time = $date->getTimestamp();
2198 if ($time === false) {
2199 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2200 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2203 // Moodle BC DST stuff.
2204 if (!$applydst) {
2205 $time += dst_offset_on($time, $timezone);
2208 return $time;
2213 * Format a date/time (seconds) as weeks, days, hours etc as needed
2215 * Given an amount of time in seconds, returns string
2216 * formatted nicely as years, days, hours etc as needed
2218 * @package core
2219 * @category time
2220 * @uses MINSECS
2221 * @uses HOURSECS
2222 * @uses DAYSECS
2223 * @uses YEARSECS
2224 * @param int $totalsecs Time in seconds
2225 * @param stdClass $str Should be a time object
2226 * @return string A nicely formatted date/time string
2228 function format_time($totalsecs, $str = null) {
2230 $totalsecs = abs($totalsecs);
2232 if (!$str) {
2233 // Create the str structure the slow way.
2234 $str = new stdClass();
2235 $str->day = get_string('day');
2236 $str->days = get_string('days');
2237 $str->hour = get_string('hour');
2238 $str->hours = get_string('hours');
2239 $str->min = get_string('min');
2240 $str->mins = get_string('mins');
2241 $str->sec = get_string('sec');
2242 $str->secs = get_string('secs');
2243 $str->year = get_string('year');
2244 $str->years = get_string('years');
2247 $years = floor($totalsecs/YEARSECS);
2248 $remainder = $totalsecs - ($years*YEARSECS);
2249 $days = floor($remainder/DAYSECS);
2250 $remainder = $totalsecs - ($days*DAYSECS);
2251 $hours = floor($remainder/HOURSECS);
2252 $remainder = $remainder - ($hours*HOURSECS);
2253 $mins = floor($remainder/MINSECS);
2254 $secs = $remainder - ($mins*MINSECS);
2256 $ss = ($secs == 1) ? $str->sec : $str->secs;
2257 $sm = ($mins == 1) ? $str->min : $str->mins;
2258 $sh = ($hours == 1) ? $str->hour : $str->hours;
2259 $sd = ($days == 1) ? $str->day : $str->days;
2260 $sy = ($years == 1) ? $str->year : $str->years;
2262 $oyears = '';
2263 $odays = '';
2264 $ohours = '';
2265 $omins = '';
2266 $osecs = '';
2268 if ($years) {
2269 $oyears = $years .' '. $sy;
2271 if ($days) {
2272 $odays = $days .' '. $sd;
2274 if ($hours) {
2275 $ohours = $hours .' '. $sh;
2277 if ($mins) {
2278 $omins = $mins .' '. $sm;
2280 if ($secs) {
2281 $osecs = $secs .' '. $ss;
2284 if ($years) {
2285 return trim($oyears .' '. $odays);
2287 if ($days) {
2288 return trim($odays .' '. $ohours);
2290 if ($hours) {
2291 return trim($ohours .' '. $omins);
2293 if ($mins) {
2294 return trim($omins .' '. $osecs);
2296 if ($secs) {
2297 return $osecs;
2299 return get_string('now');
2303 * Returns a formatted string that represents a date in user time.
2305 * @package core
2306 * @category time
2307 * @param int $date the timestamp in UTC, as obtained from the database.
2308 * @param string $format strftime format. You should probably get this using
2309 * get_string('strftime...', 'langconfig');
2310 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2311 * not 99 then daylight saving will not be added.
2312 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2313 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2314 * If false then the leading zero is maintained.
2315 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2316 * @return string the formatted date/time.
2318 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2319 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2320 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2324 * Returns a html "time" tag with both the exact user date with timezone information
2325 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2327 * @package core
2328 * @category time
2329 * @param int $date the timestamp in UTC, as obtained from the database.
2330 * @param string $format strftime format. You should probably get this using
2331 * get_string('strftime...', 'langconfig');
2332 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2333 * not 99 then daylight saving will not be added.
2334 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2335 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2336 * If false then the leading zero is maintained.
2337 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2338 * @return string the formatted date/time.
2340 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2341 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2342 if (CLI_SCRIPT && !PHPUNIT_TEST) {
2343 return $userdatestr;
2345 $machinedate = new DateTime();
2346 $machinedate->setTimestamp(intval($date));
2347 $machinedate->setTimezone(core_date::get_user_timezone_object());
2349 return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2353 * Returns a formatted date ensuring it is UTF-8.
2355 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2356 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2358 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2359 * @param string $format strftime format.
2360 * @param int|float|string $tz the user timezone
2361 * @return string the formatted date/time.
2362 * @since Moodle 2.3.3
2364 function date_format_string($date, $format, $tz = 99) {
2365 global $CFG;
2367 $localewincharset = null;
2368 // Get the calendar type user is using.
2369 if ($CFG->ostype == 'WINDOWS') {
2370 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2371 $localewincharset = $calendartype->locale_win_charset();
2374 if ($localewincharset) {
2375 $format = core_text::convert($format, 'utf-8', $localewincharset);
2378 date_default_timezone_set(core_date::get_user_timezone($tz));
2380 if (date('A', 0) === date('A', HOURSECS * 18)) {
2381 $datearray = getdate($date);
2382 $format = str_replace([
2383 '%P',
2384 '%p',
2385 ], [
2386 $datearray['hours'] < 12 ? get_string('am', 'langconfig') : get_string('pm', 'langconfig'),
2387 $datearray['hours'] < 12 ? get_string('amcaps', 'langconfig') : get_string('pmcaps', 'langconfig'),
2388 ], $format);
2391 $datestring = core_date::strftime($format, $date);
2392 core_date::set_default_server_timezone();
2394 if ($localewincharset) {
2395 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2398 return $datestring;
2402 * Given a $time timestamp in GMT (seconds since epoch),
2403 * returns an array that represents the Gregorian date in user time
2405 * @package core
2406 * @category time
2407 * @param int $time Timestamp in GMT
2408 * @param float|int|string $timezone user timezone
2409 * @return array An array that represents the date in user time
2411 function usergetdate($time, $timezone=99) {
2412 if ($time === null) {
2413 // PHP8 and PHP7 return different results when getdate(null) is called.
2414 // Display warning and cast to 0 to make sure the usergetdate() behaves consistently on all versions of PHP.
2415 // In the future versions of Moodle we may consider adding a strict typehint.
2416 debugging('usergetdate() expects parameter $time to be int, null given', DEBUG_DEVELOPER);
2417 $time = 0;
2420 date_default_timezone_set(core_date::get_user_timezone($timezone));
2421 $result = getdate($time);
2422 core_date::set_default_server_timezone();
2424 return $result;
2428 * Given a GMT timestamp (seconds since epoch), offsets it by
2429 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2431 * NOTE: this function does not include DST properly,
2432 * you should use the PHP date stuff instead!
2434 * @package core
2435 * @category time
2436 * @param int $date Timestamp in GMT
2437 * @param float|int|string $timezone user timezone
2438 * @return int
2440 function usertime($date, $timezone=99) {
2441 $userdate = new DateTime('@' . $date);
2442 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2443 $dst = dst_offset_on($date, $timezone);
2445 return $date - $userdate->getOffset() + $dst;
2449 * Get a formatted string representation of an interval between two unix timestamps.
2451 * E.g.
2452 * $intervalstring = get_time_interval_string(12345600, 12345660);
2453 * Will produce the string:
2454 * '0d 0h 1m'
2456 * @param int $time1 unix timestamp
2457 * @param int $time2 unix timestamp
2458 * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2459 * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2461 function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
2462 $dtdate = new DateTime();
2463 $dtdate->setTimeStamp($time1);
2464 $dtdate2 = new DateTime();
2465 $dtdate2->setTimeStamp($time2);
2466 $interval = $dtdate2->diff($dtdate);
2467 $format = empty($format) ? get_string('dateintervaldayshoursmins', 'langconfig') : $format;
2468 return $interval->format($format);
2472 * Given a time, return the GMT timestamp of the most recent midnight
2473 * for the current user.
2475 * @package core
2476 * @category time
2477 * @param int $date Timestamp in GMT
2478 * @param float|int|string $timezone user timezone
2479 * @return int Returns a GMT timestamp
2481 function usergetmidnight($date, $timezone=99) {
2483 $userdate = usergetdate($date, $timezone);
2485 // Time of midnight of this user's day, in GMT.
2486 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2491 * Returns a string that prints the user's timezone
2493 * @package core
2494 * @category time
2495 * @param float|int|string $timezone user timezone
2496 * @return string
2498 function usertimezone($timezone=99) {
2499 $tz = core_date::get_user_timezone($timezone);
2500 return core_date::get_localised_timezone($tz);
2504 * Returns a float or a string which denotes the user's timezone
2505 * 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)
2506 * means that for this timezone there are also DST rules to be taken into account
2507 * Checks various settings and picks the most dominant of those which have a value
2509 * @package core
2510 * @category time
2511 * @param float|int|string $tz timezone to calculate GMT time offset before
2512 * calculating user timezone, 99 is default user timezone
2513 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2514 * @return float|string
2516 function get_user_timezone($tz = 99) {
2517 global $USER, $CFG;
2519 $timezones = array(
2520 $tz,
2521 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2522 isset($USER->timezone) ? $USER->timezone : 99,
2523 isset($CFG->timezone) ? $CFG->timezone : 99,
2526 $tz = 99;
2528 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2529 foreach ($timezones as $nextvalue) {
2530 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2531 $tz = $nextvalue;
2534 return is_numeric($tz) ? (float) $tz : $tz;
2538 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2539 * - Note: Daylight saving only works for string timezones and not for float.
2541 * @package core
2542 * @category time
2543 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2544 * @param int|float|string $strtimezone user timezone
2545 * @return int
2547 function dst_offset_on($time, $strtimezone = null) {
2548 $tz = core_date::get_user_timezone($strtimezone);
2549 $date = new DateTime('@' . $time);
2550 $date->setTimezone(new DateTimeZone($tz));
2551 if ($date->format('I') == '1') {
2552 if ($tz === 'Australia/Lord_Howe') {
2553 return 1800;
2555 return 3600;
2557 return 0;
2561 * Calculates when the day appears in specific month
2563 * @package core
2564 * @category time
2565 * @param int $startday starting day of the month
2566 * @param int $weekday The day when week starts (normally taken from user preferences)
2567 * @param int $month The month whose day is sought
2568 * @param int $year The year of the month whose day is sought
2569 * @return int
2571 function find_day_in_month($startday, $weekday, $month, $year) {
2572 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2574 $daysinmonth = days_in_month($month, $year);
2575 $daysinweek = count($calendartype->get_weekdays());
2577 if ($weekday == -1) {
2578 // Don't care about weekday, so return:
2579 // abs($startday) if $startday != -1
2580 // $daysinmonth otherwise.
2581 return ($startday == -1) ? $daysinmonth : abs($startday);
2584 // From now on we 're looking for a specific weekday.
2585 // Give "end of month" its actual value, since we know it.
2586 if ($startday == -1) {
2587 $startday = -1 * $daysinmonth;
2590 // Starting from day $startday, the sign is the direction.
2591 if ($startday < 1) {
2592 $startday = abs($startday);
2593 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2595 // This is the last such weekday of the month.
2596 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2597 if ($lastinmonth > $daysinmonth) {
2598 $lastinmonth -= $daysinweek;
2601 // Find the first such weekday <= $startday.
2602 while ($lastinmonth > $startday) {
2603 $lastinmonth -= $daysinweek;
2606 return $lastinmonth;
2607 } else {
2608 $indexweekday = dayofweek($startday, $month, $year);
2610 $diff = $weekday - $indexweekday;
2611 if ($diff < 0) {
2612 $diff += $daysinweek;
2615 // This is the first such weekday of the month equal to or after $startday.
2616 $firstfromindex = $startday + $diff;
2618 return $firstfromindex;
2623 * Calculate the number of days in a given month
2625 * @package core
2626 * @category time
2627 * @param int $month The month whose day count is sought
2628 * @param int $year The year of the month whose day count is sought
2629 * @return int
2631 function days_in_month($month, $year) {
2632 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2633 return $calendartype->get_num_days_in_month($year, $month);
2637 * Calculate the position in the week of a specific calendar day
2639 * @package core
2640 * @category time
2641 * @param int $day The day of the date whose position in the week is sought
2642 * @param int $month The month of the date whose position in the week is sought
2643 * @param int $year The year of the date whose position in the week is sought
2644 * @return int
2646 function dayofweek($day, $month, $year) {
2647 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2648 return $calendartype->get_weekday($year, $month, $day);
2651 // USER AUTHENTICATION AND LOGIN.
2654 * Returns full login url.
2656 * Any form submissions for authentication to this URL must include username,
2657 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2659 * @return string login url
2661 function get_login_url() {
2662 global $CFG;
2664 return "$CFG->wwwroot/login/index.php";
2668 * This function checks that the current user is logged in and has the
2669 * required privileges
2671 * This function checks that the current user is logged in, and optionally
2672 * whether they are allowed to be in a particular course and view a particular
2673 * course module.
2674 * If they are not logged in, then it redirects them to the site login unless
2675 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2676 * case they are automatically logged in as guests.
2677 * If $courseid is given and the user is not enrolled in that course then the
2678 * user is redirected to the course enrolment page.
2679 * If $cm is given and the course module is hidden and the user is not a teacher
2680 * in the course then the user is redirected to the course home page.
2682 * When $cm parameter specified, this function sets page layout to 'module'.
2683 * You need to change it manually later if some other layout needed.
2685 * @package core_access
2686 * @category access
2688 * @param mixed $courseorid id of the course or course object
2689 * @param bool $autologinguest default true
2690 * @param object $cm course module object
2691 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2692 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2693 * in order to keep redirects working properly. MDL-14495
2694 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2695 * @return mixed Void, exit, and die depending on path
2696 * @throws coding_exception
2697 * @throws require_login_exception
2698 * @throws moodle_exception
2700 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2701 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2703 // Must not redirect when byteserving already started.
2704 if (!empty($_SERVER['HTTP_RANGE'])) {
2705 $preventredirect = true;
2708 if (AJAX_SCRIPT) {
2709 // We cannot redirect for AJAX scripts either.
2710 $preventredirect = true;
2713 // Setup global $COURSE, themes, language and locale.
2714 if (!empty($courseorid)) {
2715 if (is_object($courseorid)) {
2716 $course = $courseorid;
2717 } else if ($courseorid == SITEID) {
2718 $course = clone($SITE);
2719 } else {
2720 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2722 if ($cm) {
2723 if ($cm->course != $course->id) {
2724 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2726 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2727 if (!($cm instanceof cm_info)) {
2728 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2729 // db queries so this is not really a performance concern, however it is obviously
2730 // better if you use get_fast_modinfo to get the cm before calling this.
2731 $modinfo = get_fast_modinfo($course);
2732 $cm = $modinfo->get_cm($cm->id);
2735 } else {
2736 // Do not touch global $COURSE via $PAGE->set_course(),
2737 // the reasons is we need to be able to call require_login() at any time!!
2738 $course = $SITE;
2739 if ($cm) {
2740 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2744 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2745 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2746 // risk leading the user back to the AJAX request URL.
2747 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2748 $setwantsurltome = false;
2751 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2752 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2753 if ($preventredirect) {
2754 throw new require_login_session_timeout_exception();
2755 } else {
2756 if ($setwantsurltome) {
2757 $SESSION->wantsurl = qualified_me();
2759 redirect(get_login_url());
2763 // If the user is not even logged in yet then make sure they are.
2764 if (!isloggedin()) {
2765 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2766 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2767 // Misconfigured site guest, just redirect to login page.
2768 redirect(get_login_url());
2769 exit; // Never reached.
2771 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2772 complete_user_login($guest);
2773 $USER->autologinguest = true;
2774 $SESSION->lang = $lang;
2775 } else {
2776 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2777 if ($preventredirect) {
2778 throw new require_login_exception('You are not logged in');
2781 if ($setwantsurltome) {
2782 $SESSION->wantsurl = qualified_me();
2785 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2786 $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
2787 foreach($authsequence as $authname) {
2788 $authplugin = get_auth_plugin($authname);
2789 $authplugin->pre_loginpage_hook();
2790 if (isloggedin()) {
2791 if ($cm) {
2792 $modinfo = get_fast_modinfo($course);
2793 $cm = $modinfo->get_cm($cm->id);
2795 set_access_log_user();
2796 break;
2800 // If we're still not logged in then go to the login page
2801 if (!isloggedin()) {
2802 redirect(get_login_url());
2803 exit; // Never reached.
2808 // Loginas as redirection if needed.
2809 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2810 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2811 if ($USER->loginascontext->instanceid != $course->id) {
2812 throw new \moodle_exception('loginasonecourse', '',
2813 $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2818 // Check whether the user should be changing password (but only if it is REALLY them).
2819 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2820 $userauth = get_auth_plugin($USER->auth);
2821 if ($userauth->can_change_password() and !$preventredirect) {
2822 if ($setwantsurltome) {
2823 $SESSION->wantsurl = qualified_me();
2825 if ($changeurl = $userauth->change_password_url()) {
2826 // Use plugin custom url.
2827 redirect($changeurl);
2828 } else {
2829 // Use moodle internal method.
2830 redirect($CFG->wwwroot .'/login/change_password.php');
2832 } else if ($userauth->can_change_password()) {
2833 throw new moodle_exception('forcepasswordchangenotice');
2834 } else {
2835 throw new moodle_exception('nopasswordchangeforced', 'auth');
2839 // Check that the user account is properly set up. If we can't redirect to
2840 // edit their profile and this is not a WS request, perform just the lax check.
2841 // It will allow them to use filepicker on the profile edit page.
2843 if ($preventredirect && !WS_SERVER) {
2844 $usernotfullysetup = user_not_fully_set_up($USER, false);
2845 } else {
2846 $usernotfullysetup = user_not_fully_set_up($USER, true);
2849 if ($usernotfullysetup) {
2850 if ($preventredirect) {
2851 throw new moodle_exception('usernotfullysetup');
2853 if ($setwantsurltome) {
2854 $SESSION->wantsurl = qualified_me();
2856 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2859 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2860 sesskey();
2862 if (\core\session\manager::is_loggedinas()) {
2863 // During a "logged in as" session we should force all content to be cleaned because the
2864 // logged in user will be viewing potentially malicious user generated content.
2865 // See MDL-63786 for more details.
2866 $CFG->forceclean = true;
2869 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2871 // Do not bother admins with any formalities, except for activities pending deletion.
2872 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2873 // Set the global $COURSE.
2874 if ($cm) {
2875 $PAGE->set_cm($cm, $course);
2876 $PAGE->set_pagelayout('incourse');
2877 } else if (!empty($courseorid)) {
2878 $PAGE->set_course($course);
2880 // Set accesstime or the user will appear offline which messes up messaging.
2881 // Do not update access time for webservice or ajax requests.
2882 if (!WS_SERVER && !AJAX_SCRIPT) {
2883 user_accesstime_log($course->id);
2886 foreach ($afterlogins as $plugintype => $plugins) {
2887 foreach ($plugins as $pluginfunction) {
2888 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2891 return;
2894 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2895 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2896 if (!defined('NO_SITEPOLICY_CHECK')) {
2897 define('NO_SITEPOLICY_CHECK', false);
2900 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2901 // Do not test if the script explicitly asked for skipping the site policies check.
2902 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2903 $manager = new \core_privacy\local\sitepolicy\manager();
2904 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2905 if ($preventredirect) {
2906 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2908 if ($setwantsurltome) {
2909 $SESSION->wantsurl = qualified_me();
2911 redirect($policyurl);
2915 // Fetch the system context, the course context, and prefetch its child contexts.
2916 $sysctx = context_system::instance();
2917 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2918 if ($cm) {
2919 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2920 } else {
2921 $cmcontext = null;
2924 // If the site is currently under maintenance, then print a message.
2925 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2926 if ($preventredirect) {
2927 throw new require_login_exception('Maintenance in progress');
2929 $PAGE->set_context(null);
2930 print_maintenance_message();
2933 // Make sure the course itself is not hidden.
2934 if ($course->id == SITEID) {
2935 // Frontpage can not be hidden.
2936 } else {
2937 if (is_role_switched($course->id)) {
2938 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2939 } else {
2940 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2941 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2942 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2943 if ($preventredirect) {
2944 throw new require_login_exception('Course is hidden');
2946 $PAGE->set_context(null);
2947 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2948 // the navigation will mess up when trying to find it.
2949 navigation_node::override_active_url(new moodle_url('/'));
2950 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2955 // Is the user enrolled?
2956 if ($course->id == SITEID) {
2957 // Everybody is enrolled on the frontpage.
2958 } else {
2959 if (\core\session\manager::is_loggedinas()) {
2960 // Make sure the REAL person can access this course first.
2961 $realuser = \core\session\manager::get_realuser();
2962 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2963 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2964 if ($preventredirect) {
2965 throw new require_login_exception('Invalid course login-as access');
2967 $PAGE->set_context(null);
2968 echo $OUTPUT->header();
2969 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2973 $access = false;
2975 if (is_role_switched($course->id)) {
2976 // Ok, user had to be inside this course before the switch.
2977 $access = true;
2979 } else if (is_viewing($coursecontext, $USER)) {
2980 // Ok, no need to mess with enrol.
2981 $access = true;
2983 } else {
2984 if (isset($USER->enrol['enrolled'][$course->id])) {
2985 if ($USER->enrol['enrolled'][$course->id] > time()) {
2986 $access = true;
2987 if (isset($USER->enrol['tempguest'][$course->id])) {
2988 unset($USER->enrol['tempguest'][$course->id]);
2989 remove_temp_course_roles($coursecontext);
2991 } else {
2992 // Expired.
2993 unset($USER->enrol['enrolled'][$course->id]);
2996 if (isset($USER->enrol['tempguest'][$course->id])) {
2997 if ($USER->enrol['tempguest'][$course->id] == 0) {
2998 $access = true;
2999 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3000 $access = true;
3001 } else {
3002 // Expired.
3003 unset($USER->enrol['tempguest'][$course->id]);
3004 remove_temp_course_roles($coursecontext);
3008 if (!$access) {
3009 // Cache not ok.
3010 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3011 if ($until !== false) {
3012 // Active participants may always access, a timestamp in the future, 0 (always) or false.
3013 if ($until == 0) {
3014 $until = ENROL_MAX_TIMESTAMP;
3016 $USER->enrol['enrolled'][$course->id] = $until;
3017 $access = true;
3019 } else if (core_course_category::can_view_course_info($course)) {
3020 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
3021 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3022 $enrols = enrol_get_plugins(true);
3023 // First ask all enabled enrol instances in course if they want to auto enrol user.
3024 foreach ($instances as $instance) {
3025 if (!isset($enrols[$instance->enrol])) {
3026 continue;
3028 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3029 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3030 if ($until !== false) {
3031 if ($until == 0) {
3032 $until = ENROL_MAX_TIMESTAMP;
3034 $USER->enrol['enrolled'][$course->id] = $until;
3035 $access = true;
3036 break;
3039 // If not enrolled yet try to gain temporary guest access.
3040 if (!$access) {
3041 foreach ($instances as $instance) {
3042 if (!isset($enrols[$instance->enrol])) {
3043 continue;
3045 // Get a duration for the guest access, a timestamp in the future or false.
3046 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3047 if ($until !== false and $until > time()) {
3048 $USER->enrol['tempguest'][$course->id] = $until;
3049 $access = true;
3050 break;
3054 } else {
3055 // User is not enrolled and is not allowed to browse courses here.
3056 if ($preventredirect) {
3057 throw new require_login_exception('Course is not available');
3059 $PAGE->set_context(null);
3060 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3061 // the navigation will mess up when trying to find it.
3062 navigation_node::override_active_url(new moodle_url('/'));
3063 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3068 if (!$access) {
3069 if ($preventredirect) {
3070 throw new require_login_exception('Not enrolled');
3072 if ($setwantsurltome) {
3073 $SESSION->wantsurl = qualified_me();
3075 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3079 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3080 if ($cm && $cm->deletioninprogress) {
3081 if ($preventredirect) {
3082 throw new moodle_exception('activityisscheduledfordeletion');
3084 require_once($CFG->dirroot . '/course/lib.php');
3085 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3088 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3089 if ($cm && !$cm->uservisible) {
3090 if ($preventredirect) {
3091 throw new require_login_exception('Activity is hidden');
3093 // Get the error message that activity is not available and why (if explanation can be shown to the user).
3094 $PAGE->set_course($course);
3095 $renderer = $PAGE->get_renderer('course');
3096 $message = $renderer->course_section_cm_unavailable_error_message($cm);
3097 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
3100 // Set the global $COURSE.
3101 if ($cm) {
3102 $PAGE->set_cm($cm, $course);
3103 $PAGE->set_pagelayout('incourse');
3104 } else if (!empty($courseorid)) {
3105 $PAGE->set_course($course);
3108 foreach ($afterlogins as $plugintype => $plugins) {
3109 foreach ($plugins as $pluginfunction) {
3110 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3114 // Finally access granted, update lastaccess times.
3115 // Do not update access time for webservice or ajax requests.
3116 if (!WS_SERVER && !AJAX_SCRIPT) {
3117 user_accesstime_log($course->id);
3122 * A convenience function for where we must be logged in as admin
3123 * @return void
3125 function require_admin() {
3126 require_login(null, false);
3127 require_capability('moodle/site:config', context_system::instance());
3131 * This function just makes sure a user is logged out.
3133 * @package core_access
3134 * @category access
3136 function require_logout() {
3137 global $USER, $DB;
3139 if (!isloggedin()) {
3140 // This should not happen often, no need for hooks or events here.
3141 \core\session\manager::terminate_current();
3142 return;
3145 // Execute hooks before action.
3146 $authplugins = array();
3147 $authsequence = get_enabled_auth_plugins();
3148 foreach ($authsequence as $authname) {
3149 $authplugins[$authname] = get_auth_plugin($authname);
3150 $authplugins[$authname]->prelogout_hook();
3153 // Store info that gets removed during logout.
3154 $sid = session_id();
3155 $event = \core\event\user_loggedout::create(
3156 array(
3157 'userid' => $USER->id,
3158 'objectid' => $USER->id,
3159 'other' => array('sessionid' => $sid),
3162 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3163 $event->add_record_snapshot('sessions', $session);
3166 // Clone of $USER object to be used by auth plugins.
3167 $user = fullclone($USER);
3169 // Delete session record and drop $_SESSION content.
3170 \core\session\manager::terminate_current();
3172 // Trigger event AFTER action.
3173 $event->trigger();
3175 // Hook to execute auth plugins redirection after event trigger.
3176 foreach ($authplugins as $authplugin) {
3177 $authplugin->postlogout_hook($user);
3182 * Weaker version of require_login()
3184 * This is a weaker version of {@link require_login()} which only requires login
3185 * when called from within a course rather than the site page, unless
3186 * the forcelogin option is turned on.
3187 * @see require_login()
3189 * @package core_access
3190 * @category access
3192 * @param mixed $courseorid The course object or id in question
3193 * @param bool $autologinguest Allow autologin guests if that is wanted
3194 * @param object $cm Course activity module if known
3195 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3196 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3197 * in order to keep redirects working properly. MDL-14495
3198 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3199 * @return void
3200 * @throws coding_exception
3202 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3203 global $CFG, $PAGE, $SITE;
3204 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3205 or (!is_object($courseorid) and $courseorid == SITEID));
3206 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3207 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3208 // db queries so this is not really a performance concern, however it is obviously
3209 // better if you use get_fast_modinfo to get the cm before calling this.
3210 if (is_object($courseorid)) {
3211 $course = $courseorid;
3212 } else {
3213 $course = clone($SITE);
3215 $modinfo = get_fast_modinfo($course);
3216 $cm = $modinfo->get_cm($cm->id);
3218 if (!empty($CFG->forcelogin)) {
3219 // Login required for both SITE and courses.
3220 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3222 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3223 // Always login for hidden activities.
3224 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3226 } else if (isloggedin() && !isguestuser()) {
3227 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3228 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3230 } else if ($issite) {
3231 // Login for SITE not required.
3232 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3233 if (!empty($courseorid)) {
3234 if (is_object($courseorid)) {
3235 $course = $courseorid;
3236 } else {
3237 $course = clone $SITE;
3239 if ($cm) {
3240 if ($cm->course != $course->id) {
3241 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3243 $PAGE->set_cm($cm, $course);
3244 $PAGE->set_pagelayout('incourse');
3245 } else {
3246 $PAGE->set_course($course);
3248 } else {
3249 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3250 $PAGE->set_course($PAGE->course);
3252 // Do not update access time for webservice or ajax requests.
3253 if (!WS_SERVER && !AJAX_SCRIPT) {
3254 user_accesstime_log(SITEID);
3256 return;
3258 } else {
3259 // Course login always required.
3260 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3265 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3267 * @param string $keyvalue the key value
3268 * @param string $script unique script identifier
3269 * @param int $instance instance id
3270 * @return stdClass the key entry in the user_private_key table
3271 * @since Moodle 3.2
3272 * @throws moodle_exception
3274 function validate_user_key($keyvalue, $script, $instance) {
3275 global $DB;
3277 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3278 throw new \moodle_exception('invalidkey');
3281 if (!empty($key->validuntil) and $key->validuntil < time()) {
3282 throw new \moodle_exception('expiredkey');
3285 if ($key->iprestriction) {
3286 $remoteaddr = getremoteaddr(null);
3287 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3288 throw new \moodle_exception('ipmismatch');
3291 return $key;
3295 * Require key login. Function terminates with error if key not found or incorrect.
3297 * @uses NO_MOODLE_COOKIES
3298 * @uses PARAM_ALPHANUM
3299 * @param string $script unique script identifier
3300 * @param int $instance optional instance id
3301 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3302 * @return int Instance ID
3304 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3305 global $DB;
3307 if (!NO_MOODLE_COOKIES) {
3308 throw new \moodle_exception('sessioncookiesdisable');
3311 // Extra safety.
3312 \core\session\manager::write_close();
3314 if (null === $keyvalue) {
3315 $keyvalue = required_param('key', PARAM_ALPHANUM);
3318 $key = validate_user_key($keyvalue, $script, $instance);
3320 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3321 throw new \moodle_exception('invaliduserid');
3324 core_user::require_active_user($user, true, true);
3326 // Emulate normal session.
3327 enrol_check_plugins($user, false);
3328 \core\session\manager::set_user($user);
3330 // Note we are not using normal login.
3331 if (!defined('USER_KEY_LOGIN')) {
3332 define('USER_KEY_LOGIN', true);
3335 // Return instance id - it might be empty.
3336 return $key->instance;
3340 * Creates a new private user access key.
3342 * @param string $script unique target identifier
3343 * @param int $userid
3344 * @param int $instance optional instance id
3345 * @param string $iprestriction optional ip restricted access
3346 * @param int $validuntil key valid only until given data
3347 * @return string access key value
3349 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3350 global $DB;
3352 $key = new stdClass();
3353 $key->script = $script;
3354 $key->userid = $userid;
3355 $key->instance = $instance;
3356 $key->iprestriction = $iprestriction;
3357 $key->validuntil = $validuntil;
3358 $key->timecreated = time();
3360 // Something long and unique.
3361 $key->value = md5($userid.'_'.time().random_string(40));
3362 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3363 // Must be unique.
3364 $key->value = md5($userid.'_'.time().random_string(40));
3366 $DB->insert_record('user_private_key', $key);
3367 return $key->value;
3371 * Delete the user's new private user access keys for a particular script.
3373 * @param string $script unique target identifier
3374 * @param int $userid
3375 * @return void
3377 function delete_user_key($script, $userid) {
3378 global $DB;
3379 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3383 * Gets a private user access key (and creates one if one doesn't exist).
3385 * @param string $script unique target identifier
3386 * @param int $userid
3387 * @param int $instance optional instance id
3388 * @param string $iprestriction optional ip restricted access
3389 * @param int $validuntil key valid only until given date
3390 * @return string access key value
3392 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3393 global $DB;
3395 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3396 'instance' => $instance, 'iprestriction' => $iprestriction,
3397 'validuntil' => $validuntil))) {
3398 return $key->value;
3399 } else {
3400 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3406 * Modify the user table by setting the currently logged in user's last login to now.
3408 * @return bool Always returns true
3410 function update_user_login_times() {
3411 global $USER, $DB, $SESSION;
3413 if (isguestuser()) {
3414 // Do not update guest access times/ips for performance.
3415 return true;
3418 if (defined('USER_KEY_LOGIN') && USER_KEY_LOGIN === true) {
3419 // Do not update user login time when using user key login.
3420 return true;
3423 $now = time();
3425 $user = new stdClass();
3426 $user->id = $USER->id;
3428 // Make sure all users that logged in have some firstaccess.
3429 if ($USER->firstaccess == 0) {
3430 $USER->firstaccess = $user->firstaccess = $now;
3433 // Store the previous current as lastlogin.
3434 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3436 $USER->currentlogin = $user->currentlogin = $now;
3438 // Function user_accesstime_log() may not update immediately, better do it here.
3439 $USER->lastaccess = $user->lastaccess = $now;
3440 $SESSION->userpreviousip = $USER->lastip;
3441 $USER->lastip = $user->lastip = getremoteaddr();
3443 // Note: do not call user_update_user() here because this is part of the login process,
3444 // the login event means that these fields were updated.
3445 $DB->update_record('user', $user);
3446 return true;
3450 * Determines if a user has completed setting up their account.
3452 * The lax mode (with $strict = false) has been introduced for special cases
3453 * only where we want to skip certain checks intentionally. This is valid in
3454 * certain mnet or ajax scenarios when the user cannot / should not be
3455 * redirected to edit their profile. In most cases, you should perform the
3456 * strict check.
3458 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3459 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3460 * @return bool
3462 function user_not_fully_set_up($user, $strict = true) {
3463 global $CFG, $SESSION, $USER;
3464 require_once($CFG->dirroot.'/user/profile/lib.php');
3466 // If the user is setup then store this in the session to avoid re-checking.
3467 // Some edge cases are when the users email starts to bounce or the
3468 // configuration for custom fields has changed while they are logged in so
3469 // we re-check this fully every hour for the rare cases it has changed.
3470 if (isset($USER->id) && isset($user->id) && $USER->id === $user->id &&
3471 isset($SESSION->fullysetupstrict) && (time() - $SESSION->fullysetupstrict) < HOURSECS) {
3472 return false;
3475 if (isguestuser($user)) {
3476 return false;
3479 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3480 return true;
3483 if ($strict) {
3484 if (empty($user->id)) {
3485 // Strict mode can be used with existing accounts only.
3486 return true;
3488 if (!profile_has_required_custom_fields_set($user->id)) {
3489 return true;
3491 if (isset($USER->id) && isset($user->id) && $USER->id === $user->id) {
3492 $SESSION->fullysetupstrict = time();
3496 return false;
3500 * Check whether the user has exceeded the bounce threshold
3502 * @param stdClass $user A {@link $USER} object
3503 * @return bool true => User has exceeded bounce threshold
3505 function over_bounce_threshold($user) {
3506 global $CFG, $DB;
3508 if (empty($CFG->handlebounces)) {
3509 return false;
3512 if (empty($user->id)) {
3513 // No real (DB) user, nothing to do here.
3514 return false;
3517 // Set sensible defaults.
3518 if (empty($CFG->minbounces)) {
3519 $CFG->minbounces = 10;
3521 if (empty($CFG->bounceratio)) {
3522 $CFG->bounceratio = .20;
3524 $bouncecount = 0;
3525 $sendcount = 0;
3526 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3527 $bouncecount = $bounce->value;
3529 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3530 $sendcount = $send->value;
3532 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3536 * Used to increment or reset email sent count
3538 * @param stdClass $user object containing an id
3539 * @param bool $reset will reset the count to 0
3540 * @return void
3542 function set_send_count($user, $reset=false) {
3543 global $DB;
3545 if (empty($user->id)) {
3546 // No real (DB) user, nothing to do here.
3547 return;
3550 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3551 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3552 $DB->update_record('user_preferences', $pref);
3553 } else if (!empty($reset)) {
3554 // If it's not there and we're resetting, don't bother. Make a new one.
3555 $pref = new stdClass();
3556 $pref->name = 'email_send_count';
3557 $pref->value = 1;
3558 $pref->userid = $user->id;
3559 $DB->insert_record('user_preferences', $pref, false);
3564 * Increment or reset user's email bounce count
3566 * @param stdClass $user object containing an id
3567 * @param bool $reset will reset the count to 0
3569 function set_bounce_count($user, $reset=false) {
3570 global $DB;
3572 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3573 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3574 $DB->update_record('user_preferences', $pref);
3575 } else if (!empty($reset)) {
3576 // If it's not there and we're resetting, don't bother. Make a new one.
3577 $pref = new stdClass();
3578 $pref->name = 'email_bounce_count';
3579 $pref->value = 1;
3580 $pref->userid = $user->id;
3581 $DB->insert_record('user_preferences', $pref, false);
3586 * Determines if the logged in user is currently moving an activity
3588 * @param int $courseid The id of the course being tested
3589 * @return bool
3591 function ismoving($courseid) {
3592 global $USER;
3594 if (!empty($USER->activitycopy)) {
3595 return ($USER->activitycopycourse == $courseid);
3597 return false;
3601 * Returns a persons full name
3603 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3604 * The result may depend on system settings or language. 'override' will force the alternativefullnameformat to be used. In
3605 * English, fullname as well as alternativefullnameformat is set to 'firstname lastname' by default. But you could have
3606 * fullname set to 'firstname lastname' and alternativefullnameformat set to 'firstname middlename alternatename lastname'.
3608 * @param stdClass $user A {@link $USER} object to get full name of.
3609 * @param bool $override If true then the alternativefullnameformat format rather than fullnamedisplay format will be used.
3610 * @return string
3612 function fullname($user, $override=false) {
3613 global $CFG, $SESSION;
3615 if (!isset($user->firstname) and !isset($user->lastname)) {
3616 return '';
3619 // Get all of the name fields.
3620 $allnames = \core_user\fields::get_name_fields();
3621 if ($CFG->debugdeveloper) {
3622 foreach ($allnames as $allname) {
3623 if (!property_exists($user, $allname)) {
3624 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3625 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3626 // Message has been sent, no point in sending the message multiple times.
3627 break;
3632 if (!$override) {
3633 if (!empty($CFG->forcefirstname)) {
3634 $user->firstname = $CFG->forcefirstname;
3636 if (!empty($CFG->forcelastname)) {
3637 $user->lastname = $CFG->forcelastname;
3641 if (!empty($SESSION->fullnamedisplay)) {
3642 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3645 $template = null;
3646 // If the fullnamedisplay setting is available, set the template to that.
3647 if (isset($CFG->fullnamedisplay)) {
3648 $template = $CFG->fullnamedisplay;
3650 // If the template is empty, or set to language, return the language string.
3651 if ((empty($template) || $template == 'language') && !$override) {
3652 return get_string('fullnamedisplay', null, $user);
3655 // Check to see if we are displaying according to the alternative full name format.
3656 if ($override) {
3657 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3658 // Default to show just the user names according to the fullnamedisplay string.
3659 return get_string('fullnamedisplay', null, $user);
3660 } else {
3661 // If the override is true, then change the template to use the complete name.
3662 $template = $CFG->alternativefullnameformat;
3666 $requirednames = array();
3667 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3668 foreach ($allnames as $allname) {
3669 if (strpos($template, $allname) !== false) {
3670 $requirednames[] = $allname;
3674 $displayname = $template;
3675 // Switch in the actual data into the template.
3676 foreach ($requirednames as $altname) {
3677 if (isset($user->$altname)) {
3678 // Using empty() on the below if statement causes breakages.
3679 if ((string)$user->$altname == '') {
3680 $displayname = str_replace($altname, 'EMPTY', $displayname);
3681 } else {
3682 $displayname = str_replace($altname, $user->$altname, $displayname);
3684 } else {
3685 $displayname = str_replace($altname, 'EMPTY', $displayname);
3688 // Tidy up any misc. characters (Not perfect, but gets most characters).
3689 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3690 // katakana and parenthesis.
3691 $patterns = array();
3692 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3693 // filled in by a user.
3694 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3695 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3696 // This regular expression is to remove any double spaces in the display name.
3697 $patterns[] = '/\s{2,}/u';
3698 foreach ($patterns as $pattern) {
3699 $displayname = preg_replace($pattern, ' ', $displayname);
3702 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3703 $displayname = trim($displayname);
3704 if (empty($displayname)) {
3705 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3706 // people in general feel is a good setting to fall back on.
3707 $displayname = $user->firstname;
3709 return $displayname;
3713 * Reduces lines of duplicated code for getting user name fields.
3715 * See also {@link user_picture::unalias()}
3717 * @param object $addtoobject Object to add user name fields to.
3718 * @param object $secondobject Object that contains user name field information.
3719 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3720 * @param array $additionalfields Additional fields to be matched with data in the second object.
3721 * The key can be set to the user table field name.
3722 * @return object User name fields.
3724 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3725 $fields = [];
3726 foreach (\core_user\fields::get_name_fields() as $field) {
3727 $fields[$field] = $prefix . $field;
3729 if ($additionalfields) {
3730 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3731 // the key is a number and then sets the key to the array value.
3732 foreach ($additionalfields as $key => $value) {
3733 if (is_numeric($key)) {
3734 $additionalfields[$value] = $prefix . $value;
3735 unset($additionalfields[$key]);
3736 } else {
3737 $additionalfields[$key] = $prefix . $value;
3740 $fields = array_merge($fields, $additionalfields);
3742 foreach ($fields as $key => $field) {
3743 // Important that we have all of the user name fields present in the object that we are sending back.
3744 $addtoobject->$key = '';
3745 if (isset($secondobject->$field)) {
3746 $addtoobject->$key = $secondobject->$field;
3749 return $addtoobject;
3753 * Returns an array of values in order of occurance in a provided string.
3754 * The key in the result is the character postion in the string.
3756 * @param array $values Values to be found in the string format
3757 * @param string $stringformat The string which may contain values being searched for.
3758 * @return array An array of values in order according to placement in the string format.
3760 function order_in_string($values, $stringformat) {
3761 $valuearray = array();
3762 foreach ($values as $value) {
3763 $pattern = "/$value\b/";
3764 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3765 if (preg_match($pattern, $stringformat)) {
3766 $replacement = "thing";
3767 // Replace the value with something more unique to ensure we get the right position when using strpos().
3768 $newformat = preg_replace($pattern, $replacement, $stringformat);
3769 $position = strpos($newformat, $replacement);
3770 $valuearray[$position] = $value;
3773 ksort($valuearray);
3774 return $valuearray;
3778 * Returns whether a given authentication plugin exists.
3780 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3781 * @return boolean Whether the plugin is available.
3783 function exists_auth_plugin($auth) {
3784 global $CFG;
3786 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3787 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3789 return false;
3793 * Checks if a given plugin is in the list of enabled authentication plugins.
3795 * @param string $auth Authentication plugin.
3796 * @return boolean Whether the plugin is enabled.
3798 function is_enabled_auth($auth) {
3799 if (empty($auth)) {
3800 return false;
3803 $enabled = get_enabled_auth_plugins();
3805 return in_array($auth, $enabled);
3809 * Returns an authentication plugin instance.
3811 * @param string $auth name of authentication plugin
3812 * @return auth_plugin_base An instance of the required authentication plugin.
3814 function get_auth_plugin($auth) {
3815 global $CFG;
3817 // Check the plugin exists first.
3818 if (! exists_auth_plugin($auth)) {
3819 throw new \moodle_exception('authpluginnotfound', 'debug', '', $auth);
3822 // Return auth plugin instance.
3823 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3824 $class = "auth_plugin_$auth";
3825 return new $class;
3829 * Returns array of active auth plugins.
3831 * @param bool $fix fix $CFG->auth if needed. Only set if logged in as admin.
3832 * @return array
3834 function get_enabled_auth_plugins($fix=false) {
3835 global $CFG;
3837 $default = array('manual', 'nologin');
3839 if (empty($CFG->auth)) {
3840 $auths = array();
3841 } else {
3842 $auths = explode(',', $CFG->auth);
3845 $auths = array_unique($auths);
3846 $oldauthconfig = implode(',', $auths);
3847 foreach ($auths as $k => $authname) {
3848 if (in_array($authname, $default)) {
3849 // The manual and nologin plugin never need to be stored.
3850 unset($auths[$k]);
3851 } else if (!exists_auth_plugin($authname)) {
3852 debugging(get_string('authpluginnotfound', 'debug', $authname));
3853 unset($auths[$k]);
3857 // Ideally only explicit interaction from a human admin should trigger a
3858 // change in auth config, see MDL-70424 for details.
3859 if ($fix) {
3860 $newconfig = implode(',', $auths);
3861 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3862 add_to_config_log('auth', $oldauthconfig, $newconfig, 'core');
3863 set_config('auth', $newconfig);
3867 return (array_merge($default, $auths));
3871 * Returns true if an internal authentication method is being used.
3872 * if method not specified then, global default is assumed
3874 * @param string $auth Form of authentication required
3875 * @return bool
3877 function is_internal_auth($auth) {
3878 // Throws error if bad $auth.
3879 $authplugin = get_auth_plugin($auth);
3880 return $authplugin->is_internal();
3884 * Returns true if the user is a 'restored' one.
3886 * Used in the login process to inform the user and allow him/her to reset the password
3888 * @param string $username username to be checked
3889 * @return bool
3891 function is_restored_user($username) {
3892 global $CFG, $DB;
3894 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3898 * Returns an array of user fields
3900 * @return array User field/column names
3902 function get_user_fieldnames() {
3903 global $DB;
3905 $fieldarray = $DB->get_columns('user');
3906 unset($fieldarray['id']);
3907 $fieldarray = array_keys($fieldarray);
3909 return $fieldarray;
3913 * Returns the string of the language for the new user.
3915 * @return string language for the new user
3917 function get_newuser_language() {
3918 global $CFG, $SESSION;
3919 return (!empty($CFG->autolangusercreation) && !empty($SESSION->lang)) ? $SESSION->lang : $CFG->lang;
3923 * Creates a bare-bones user record
3925 * @todo Outline auth types and provide code example
3927 * @param string $username New user's username to add to record
3928 * @param string $password New user's password to add to record
3929 * @param string $auth Form of authentication required
3930 * @return stdClass A complete user object
3932 function create_user_record($username, $password, $auth = 'manual') {
3933 global $CFG, $DB, $SESSION;
3934 require_once($CFG->dirroot.'/user/profile/lib.php');
3935 require_once($CFG->dirroot.'/user/lib.php');
3937 // Just in case check text case.
3938 $username = trim(core_text::strtolower($username));
3940 $authplugin = get_auth_plugin($auth);
3941 $customfields = $authplugin->get_custom_user_profile_fields();
3942 $newuser = new stdClass();
3943 if ($newinfo = $authplugin->get_userinfo($username)) {
3944 $newinfo = truncate_userinfo($newinfo);
3945 foreach ($newinfo as $key => $value) {
3946 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3947 $newuser->$key = $value;
3952 if (!empty($newuser->email)) {
3953 if (email_is_not_allowed($newuser->email)) {
3954 unset($newuser->email);
3958 $newuser->auth = $auth;
3959 $newuser->username = $username;
3961 // Fix for MDL-8480
3962 // user CFG lang for user if $newuser->lang is empty
3963 // or $user->lang is not an installed language.
3964 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3965 $newuser->lang = get_newuser_language();
3967 $newuser->confirmed = 1;
3968 $newuser->lastip = getremoteaddr();
3969 $newuser->timecreated = time();
3970 $newuser->timemodified = $newuser->timecreated;
3971 $newuser->mnethostid = $CFG->mnet_localhost_id;
3973 $newuser->id = user_create_user($newuser, false, false);
3975 // Save user profile data.
3976 profile_save_data($newuser);
3978 $user = get_complete_user_data('id', $newuser->id);
3979 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3980 set_user_preference('auth_forcepasswordchange', 1, $user);
3982 // Set the password.
3983 update_internal_user_password($user, $password);
3985 // Trigger event.
3986 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3988 return $user;
3992 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3994 * @param string $username user's username to update the record
3995 * @return stdClass A complete user object
3997 function update_user_record($username) {
3998 global $DB, $CFG;
3999 // Just in case check text case.
4000 $username = trim(core_text::strtolower($username));
4002 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
4003 return update_user_record_by_id($oldinfo->id);
4007 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4009 * @param int $id user id
4010 * @return stdClass A complete user object
4012 function update_user_record_by_id($id) {
4013 global $DB, $CFG;
4014 require_once($CFG->dirroot."/user/profile/lib.php");
4015 require_once($CFG->dirroot.'/user/lib.php');
4017 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
4018 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
4020 $newuser = array();
4021 $userauth = get_auth_plugin($oldinfo->auth);
4023 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
4024 $newinfo = truncate_userinfo($newinfo);
4025 $customfields = $userauth->get_custom_user_profile_fields();
4027 foreach ($newinfo as $key => $value) {
4028 $iscustom = in_array($key, $customfields);
4029 if (!$iscustom) {
4030 $key = strtolower($key);
4032 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4033 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4034 // Unknown or must not be changed.
4035 continue;
4037 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
4038 continue;
4040 $confval = $userauth->config->{'field_updatelocal_' . $key};
4041 $lockval = $userauth->config->{'field_lock_' . $key};
4042 if ($confval === 'onlogin') {
4043 // MDL-4207 Don't overwrite modified user profile values with
4044 // empty LDAP values when 'unlocked if empty' is set. The purpose
4045 // of the setting 'unlocked if empty' is to allow the user to fill
4046 // in a value for the selected field _if LDAP is giving
4047 // nothing_ for this field. Thus it makes sense to let this value
4048 // stand in until LDAP is giving a value for this field.
4049 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4050 if ($iscustom || (in_array($key, $userauth->userfields) &&
4051 ((string)$oldinfo->$key !== (string)$value))) {
4052 $newuser[$key] = (string)$value;
4057 if ($newuser) {
4058 $newuser['id'] = $oldinfo->id;
4059 $newuser['timemodified'] = time();
4060 user_update_user((object) $newuser, false, false);
4062 // Save user profile data.
4063 profile_save_data((object) $newuser);
4065 // Trigger event.
4066 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4070 return get_complete_user_data('id', $oldinfo->id);
4074 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4076 * @param array $info Array of user properties to truncate if needed
4077 * @return array The now truncated information that was passed in
4079 function truncate_userinfo(array $info) {
4080 // Define the limits.
4081 $limit = array(
4082 'username' => 100,
4083 'idnumber' => 255,
4084 'firstname' => 100,
4085 'lastname' => 100,
4086 'email' => 100,
4087 'phone1' => 20,
4088 'phone2' => 20,
4089 'institution' => 255,
4090 'department' => 255,
4091 'address' => 255,
4092 'city' => 120,
4093 'country' => 2,
4096 // Apply where needed.
4097 foreach (array_keys($info) as $key) {
4098 if (!empty($limit[$key])) {
4099 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4103 return $info;
4107 * Marks user deleted in internal user database and notifies the auth plugin.
4108 * Also unenrols user from all roles and does other cleanup.
4110 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4112 * @param stdClass $user full user object before delete
4113 * @return boolean success
4114 * @throws coding_exception if invalid $user parameter detected
4116 function delete_user(stdClass $user) {
4117 global $CFG, $DB, $SESSION;
4118 require_once($CFG->libdir.'/grouplib.php');
4119 require_once($CFG->libdir.'/gradelib.php');
4120 require_once($CFG->dirroot.'/message/lib.php');
4121 require_once($CFG->dirroot.'/user/lib.php');
4123 // Make sure nobody sends bogus record type as parameter.
4124 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4125 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4128 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4129 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4130 debugging('Attempt to delete unknown user account.');
4131 return false;
4134 // There must be always exactly one guest record, originally the guest account was identified by username only,
4135 // now we use $CFG->siteguest for performance reasons.
4136 if ($user->username === 'guest' or isguestuser($user)) {
4137 debugging('Guest user account can not be deleted.');
4138 return false;
4141 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4142 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4143 if ($user->auth === 'manual' and is_siteadmin($user)) {
4144 debugging('Local administrator accounts can not be deleted.');
4145 return false;
4148 // Allow plugins to use this user object before we completely delete it.
4149 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4150 foreach ($pluginsfunction as $plugintype => $plugins) {
4151 foreach ($plugins as $pluginfunction) {
4152 $pluginfunction($user);
4157 // Keep user record before updating it, as we have to pass this to user_deleted event.
4158 $olduser = clone $user;
4160 // Keep a copy of user context, we need it for event.
4161 $usercontext = context_user::instance($user->id);
4163 // Delete all grades - backup is kept in grade_grades_history table.
4164 grade_user_delete($user->id);
4166 // TODO: remove from cohorts using standard API here.
4168 // Remove user tags.
4169 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4171 // Unconditionally unenrol from all courses.
4172 enrol_user_delete($user);
4174 // Unenrol from all roles in all contexts.
4175 // This might be slow but it is really needed - modules might do some extra cleanup!
4176 role_unassign_all(array('userid' => $user->id));
4178 // Notify the competency subsystem.
4179 \core_competency\api::hook_user_deleted($user->id);
4181 // Now do a brute force cleanup.
4183 // Delete all user events and subscription events.
4184 $DB->delete_records_select('event', 'userid = :userid AND subscriptionid IS NOT NULL', ['userid' => $user->id]);
4186 // Now, delete all calendar subscription from the user.
4187 $DB->delete_records('event_subscriptions', ['userid' => $user->id]);
4189 // Remove from all cohorts.
4190 $DB->delete_records('cohort_members', array('userid' => $user->id));
4192 // Remove from all groups.
4193 $DB->delete_records('groups_members', array('userid' => $user->id));
4195 // Brute force unenrol from all courses.
4196 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4198 // Purge user preferences.
4199 $DB->delete_records('user_preferences', array('userid' => $user->id));
4201 // Purge user extra profile info.
4202 $DB->delete_records('user_info_data', array('userid' => $user->id));
4204 // Purge log of previous password hashes.
4205 $DB->delete_records('user_password_history', array('userid' => $user->id));
4207 // Last course access not necessary either.
4208 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4209 // Remove all user tokens.
4210 $DB->delete_records('external_tokens', array('userid' => $user->id));
4212 // Unauthorise the user for all services.
4213 $DB->delete_records('external_services_users', array('userid' => $user->id));
4215 // Remove users private keys.
4216 $DB->delete_records('user_private_key', array('userid' => $user->id));
4218 // Remove users customised pages.
4219 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4221 // Remove user's oauth2 refresh tokens, if present.
4222 $DB->delete_records('oauth2_refresh_token', array('userid' => $user->id));
4224 // Delete user from $SESSION->bulk_users.
4225 if (isset($SESSION->bulk_users[$user->id])) {
4226 unset($SESSION->bulk_users[$user->id]);
4229 // Force logout - may fail if file based sessions used, sorry.
4230 \core\session\manager::kill_user_sessions($user->id);
4232 // Generate username from email address, or a fake email.
4233 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4235 $deltime = time();
4236 $deltimelength = core_text::strlen((string) $deltime);
4238 // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
4239 $delname = clean_param($delemail, PARAM_USERNAME);
4240 $delname = core_text::substr($delname, 0, 100 - ($deltimelength + 1)) . ".{$deltime}";
4242 // Workaround for bulk deletes of users with the same email address.
4243 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4244 $delname++;
4247 // Mark internal user record as "deleted".
4248 $updateuser = new stdClass();
4249 $updateuser->id = $user->id;
4250 $updateuser->deleted = 1;
4251 $updateuser->username = $delname; // Remember it just in case.
4252 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4253 $updateuser->idnumber = ''; // Clear this field to free it up.
4254 $updateuser->picture = 0;
4255 $updateuser->timemodified = $deltime;
4257 // Don't trigger update event, as user is being deleted.
4258 user_update_user($updateuser, false, false);
4260 // Delete all content associated with the user context, but not the context itself.
4261 $usercontext->delete_content();
4263 // Delete any search data.
4264 \core_search\manager::context_deleted($usercontext);
4266 // Any plugin that needs to cleanup should register this event.
4267 // Trigger event.
4268 $event = \core\event\user_deleted::create(
4269 array(
4270 'objectid' => $user->id,
4271 'relateduserid' => $user->id,
4272 'context' => $usercontext,
4273 'other' => array(
4274 'username' => $user->username,
4275 'email' => $user->email,
4276 'idnumber' => $user->idnumber,
4277 'picture' => $user->picture,
4278 'mnethostid' => $user->mnethostid
4282 $event->add_record_snapshot('user', $olduser);
4283 $event->trigger();
4285 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4286 // should know about this updated property persisted to the user's table.
4287 $user->timemodified = $updateuser->timemodified;
4289 // Notify auth plugin - do not block the delete even when plugin fails.
4290 $authplugin = get_auth_plugin($user->auth);
4291 $authplugin->user_delete($user);
4293 return true;
4297 * Retrieve the guest user object.
4299 * @return stdClass A {@link $USER} object
4301 function guest_user() {
4302 global $CFG, $DB;
4304 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4305 $newuser->confirmed = 1;
4306 $newuser->lang = get_newuser_language();
4307 $newuser->lastip = getremoteaddr();
4310 return $newuser;
4314 * Authenticates a user against the chosen authentication mechanism
4316 * Given a username and password, this function looks them
4317 * up using the currently selected authentication mechanism,
4318 * and if the authentication is successful, it returns a
4319 * valid $user object from the 'user' table.
4321 * Uses auth_ functions from the currently active auth module
4323 * After authenticate_user_login() returns success, you will need to
4324 * log that the user has logged in, and call complete_user_login() to set
4325 * the session up.
4327 * Note: this function works only with non-mnet accounts!
4329 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4330 * @param string $password User's password
4331 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4332 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4333 * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4334 * @return stdClass|false A {@link $USER} object or false if error
4336 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4337 global $CFG, $DB, $PAGE;
4338 require_once("$CFG->libdir/authlib.php");
4340 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4341 // we have found the user
4343 } else if (!empty($CFG->authloginviaemail)) {
4344 if ($email = clean_param($username, PARAM_EMAIL)) {
4345 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4346 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4347 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4348 if (count($users) === 1) {
4349 // Use email for login only if unique.
4350 $user = reset($users);
4351 $user = get_complete_user_data('id', $user->id);
4352 $username = $user->username;
4354 unset($users);
4358 // Make sure this request came from the login form.
4359 if (!\core\session\manager::validate_login_token($logintoken)) {
4360 $failurereason = AUTH_LOGIN_FAILED;
4362 // Trigger login failed event (specifying the ID of the found user, if available).
4363 \core\event\user_login_failed::create([
4364 'userid' => ($user->id ?? 0),
4365 'other' => [
4366 'username' => $username,
4367 'reason' => $failurereason,
4369 ])->trigger();
4371 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4372 return false;
4375 $authsenabled = get_enabled_auth_plugins();
4377 if ($user) {
4378 // Use manual if auth not set.
4379 $auth = empty($user->auth) ? 'manual' : $user->auth;
4381 if (in_array($user->auth, $authsenabled)) {
4382 $authplugin = get_auth_plugin($user->auth);
4383 $authplugin->pre_user_login_hook($user);
4386 if (!empty($user->suspended)) {
4387 $failurereason = AUTH_LOGIN_SUSPENDED;
4389 // Trigger login failed event.
4390 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4391 'other' => array('username' => $username, 'reason' => $failurereason)));
4392 $event->trigger();
4393 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4394 return false;
4396 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4397 // Legacy way to suspend user.
4398 $failurereason = AUTH_LOGIN_SUSPENDED;
4400 // Trigger login failed event.
4401 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4402 'other' => array('username' => $username, 'reason' => $failurereason)));
4403 $event->trigger();
4404 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4405 return false;
4407 $auths = array($auth);
4409 } else {
4410 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4411 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4412 $failurereason = AUTH_LOGIN_NOUSER;
4414 // Trigger login failed event.
4415 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4416 'reason' => $failurereason)));
4417 $event->trigger();
4418 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4419 return false;
4422 // User does not exist.
4423 $auths = $authsenabled;
4424 $user = new stdClass();
4425 $user->id = 0;
4428 if ($ignorelockout) {
4429 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4430 // or this function is called from a SSO script.
4431 } else if ($user->id) {
4432 // Verify login lockout after other ways that may prevent user login.
4433 if (login_is_lockedout($user)) {
4434 $failurereason = AUTH_LOGIN_LOCKOUT;
4436 // Trigger login failed event.
4437 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4438 'other' => array('username' => $username, 'reason' => $failurereason)));
4439 $event->trigger();
4441 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4442 return false;
4444 } else {
4445 // We can not lockout non-existing accounts.
4448 foreach ($auths as $auth) {
4449 $authplugin = get_auth_plugin($auth);
4451 // On auth fail fall through to the next plugin.
4452 if (!$authplugin->user_login($username, $password)) {
4453 continue;
4456 // Before performing login actions, check if user still passes password policy, if admin setting is enabled.
4457 if (!empty($CFG->passwordpolicycheckonlogin)) {
4458 $errmsg = '';
4459 $passed = check_password_policy($password, $errmsg, $user);
4460 if (!$passed) {
4461 // First trigger event for failure.
4462 $failedevent = \core\event\user_password_policy_failed::create_from_user($user);
4463 $failedevent->trigger();
4465 // If able to change password, set flag and move on.
4466 if ($authplugin->can_change_password()) {
4467 // Check if we are on internal change password page, or service is external, don't show notification.
4468 $internalchangeurl = new moodle_url('/login/change_password.php');
4469 if (!($PAGE->has_set_url() && $internalchangeurl->compare($PAGE->url)) && $authplugin->is_internal()) {
4470 \core\notification::error(get_string('passwordpolicynomatch', '', $errmsg));
4472 set_user_preference('auth_forcepasswordchange', 1, $user);
4473 } else if ($authplugin->can_reset_password()) {
4474 // Else force a reset if possible.
4475 \core\notification::error(get_string('forcepasswordresetnotice', '', $errmsg));
4476 redirect(new moodle_url('/login/forgot_password.php'));
4477 } else {
4478 $notifymsg = get_string('forcepasswordresetfailurenotice', '', $errmsg);
4479 // If support page is set, add link for help.
4480 if (!empty($CFG->supportpage)) {
4481 $link = \html_writer::link($CFG->supportpage, $CFG->supportpage);
4482 $link = \html_writer::tag('p', $link);
4483 $notifymsg .= $link;
4486 // If no change or reset is possible, add a notification for user.
4487 \core\notification::error($notifymsg);
4492 // Successful authentication.
4493 if ($user->id) {
4494 // User already exists in database.
4495 if (empty($user->auth)) {
4496 // For some reason auth isn't set yet.
4497 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4498 $user->auth = $auth;
4501 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4502 // the current hash algorithm while we have access to the user's password.
4503 update_internal_user_password($user, $password);
4505 if ($authplugin->is_synchronised_with_external()) {
4506 // Update user record from external DB.
4507 $user = update_user_record_by_id($user->id);
4509 } else {
4510 // The user is authenticated but user creation may be disabled.
4511 if (!empty($CFG->authpreventaccountcreation)) {
4512 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4514 // Trigger login failed event.
4515 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4516 'reason' => $failurereason)));
4517 $event->trigger();
4519 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4520 $_SERVER['HTTP_USER_AGENT']);
4521 return false;
4522 } else {
4523 $user = create_user_record($username, $password, $auth);
4527 $authplugin->sync_roles($user);
4529 foreach ($authsenabled as $hau) {
4530 $hauth = get_auth_plugin($hau);
4531 $hauth->user_authenticated_hook($user, $username, $password);
4534 if (empty($user->id)) {
4535 $failurereason = AUTH_LOGIN_NOUSER;
4536 // Trigger login failed event.
4537 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4538 'reason' => $failurereason)));
4539 $event->trigger();
4540 return false;
4543 if (!empty($user->suspended)) {
4544 // Just in case some auth plugin suspended account.
4545 $failurereason = AUTH_LOGIN_SUSPENDED;
4546 // Trigger login failed event.
4547 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4548 'other' => array('username' => $username, 'reason' => $failurereason)));
4549 $event->trigger();
4550 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4551 return false;
4554 login_attempt_valid($user);
4555 $failurereason = AUTH_LOGIN_OK;
4556 return $user;
4559 // Failed if all the plugins have failed.
4560 if (debugging('', DEBUG_ALL)) {
4561 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4564 if ($user->id) {
4565 login_attempt_failed($user);
4566 $failurereason = AUTH_LOGIN_FAILED;
4567 // Trigger login failed event.
4568 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4569 'other' => array('username' => $username, 'reason' => $failurereason)));
4570 $event->trigger();
4571 } else {
4572 $failurereason = AUTH_LOGIN_NOUSER;
4573 // Trigger login failed event.
4574 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4575 'reason' => $failurereason)));
4576 $event->trigger();
4579 return false;
4583 * Call to complete the user login process after authenticate_user_login()
4584 * has succeeded. It will setup the $USER variable and other required bits
4585 * and pieces.
4587 * NOTE:
4588 * - It will NOT log anything -- up to the caller to decide what to log.
4589 * - this function does not set any cookies any more!
4591 * @param stdClass $user
4592 * @param array $extrauserinfo
4593 * @return stdClass A {@link $USER} object - BC only, do not use
4595 function complete_user_login($user, array $extrauserinfo = []) {
4596 global $CFG, $DB, $USER, $SESSION;
4598 \core\session\manager::login_user($user);
4600 // Reload preferences from DB.
4601 unset($USER->preference);
4602 check_user_preferences_loaded($USER);
4604 // Update login times.
4605 update_user_login_times();
4607 // Extra session prefs init.
4608 set_login_session_preferences();
4610 // Trigger login event.
4611 $event = \core\event\user_loggedin::create(
4612 array(
4613 'userid' => $USER->id,
4614 'objectid' => $USER->id,
4615 'other' => [
4616 'username' => $USER->username,
4617 'extrauserinfo' => $extrauserinfo
4621 $event->trigger();
4623 // Check if the user is using a new browser or session (a new MoodleSession cookie is set in that case).
4624 // If the user is accessing from the same IP, ignore everything (most of the time will be a new session in the same browser).
4625 // Skip Web Service requests, CLI scripts, AJAX scripts, and request from the mobile app itself.
4626 $loginip = getremoteaddr();
4627 $isnewip = isset($SESSION->userpreviousip) && $SESSION->userpreviousip != $loginip;
4628 $isvalidenv = (!WS_SERVER && !CLI_SCRIPT && !NO_MOODLE_COOKIES) || PHPUNIT_TEST;
4630 if (!empty($SESSION->isnewsessioncookie) && $isnewip && $isvalidenv && !\core_useragent::is_moodle_app()) {
4632 $logintime = time();
4633 $ismoodleapp = false;
4634 $useragent = \core_useragent::get_user_agent_string();
4636 // Schedule adhoc task to sent a login notification to the user.
4637 $task = new \core\task\send_login_notifications();
4638 $task->set_userid($USER->id);
4639 $task->set_custom_data(compact('ismoodleapp', 'useragent', 'loginip', 'logintime'));
4640 $task->set_component('core');
4641 \core\task\manager::queue_adhoc_task($task);
4644 // Queue migrating the messaging data, if we need to.
4645 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4646 // Check if there are any legacy messages to migrate.
4647 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4648 \core_message\task\migrate_message_data::queue_task($USER->id);
4649 } else {
4650 set_user_preference('core_message_migrate_data', true, $USER->id);
4654 if (isguestuser()) {
4655 // No need to continue when user is THE guest.
4656 return $USER;
4659 if (CLI_SCRIPT) {
4660 // We can redirect to password change URL only in browser.
4661 return $USER;
4664 // Select password change url.
4665 $userauth = get_auth_plugin($USER->auth);
4667 // Check whether the user should be changing password.
4668 if (get_user_preferences('auth_forcepasswordchange', false)) {
4669 if ($userauth->can_change_password()) {
4670 if ($changeurl = $userauth->change_password_url()) {
4671 redirect($changeurl);
4672 } else {
4673 require_once($CFG->dirroot . '/login/lib.php');
4674 $SESSION->wantsurl = core_login_get_return_url();
4675 redirect($CFG->wwwroot.'/login/change_password.php');
4677 } else {
4678 throw new \moodle_exception('nopasswordchangeforced', 'auth');
4681 return $USER;
4685 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4687 * @param string $password String to check.
4688 * @return boolean True if the $password matches the format of an md5 sum.
4690 function password_is_legacy_hash($password) {
4691 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4695 * Compare password against hash stored in user object to determine if it is valid.
4697 * If necessary it also updates the stored hash to the current format.
4699 * @param stdClass $user (Password property may be updated).
4700 * @param string $password Plain text password.
4701 * @return bool True if password is valid.
4703 function validate_internal_user_password($user, $password) {
4704 global $CFG;
4706 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4707 // Internal password is not used at all, it can not validate.
4708 return false;
4711 // If hash isn't a legacy (md5) hash, validate using the library function.
4712 if (!password_is_legacy_hash($user->password)) {
4713 return password_verify($password, $user->password);
4716 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4717 // is valid we can then update it to the new algorithm.
4719 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4720 $validated = false;
4722 if ($user->password === md5($password.$sitesalt)
4723 or $user->password === md5($password)
4724 or $user->password === md5(addslashes($password).$sitesalt)
4725 or $user->password === md5(addslashes($password))) {
4726 // Note: we are intentionally using the addslashes() here because we
4727 // need to accept old password hashes of passwords with magic quotes.
4728 $validated = true;
4730 } else {
4731 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4732 $alt = 'passwordsaltalt'.$i;
4733 if (!empty($CFG->$alt)) {
4734 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4735 $validated = true;
4736 break;
4742 if ($validated) {
4743 // If the password matches the existing md5 hash, update to the
4744 // current hash algorithm while we have access to the user's password.
4745 update_internal_user_password($user, $password);
4748 return $validated;
4752 * Calculate hash for a plain text password.
4754 * @param string $password Plain text password to be hashed.
4755 * @param bool $fasthash If true, use a low cost factor when generating the hash
4756 * This is much faster to generate but makes the hash
4757 * less secure. It is used when lots of hashes need to
4758 * be generated quickly.
4759 * @return string The hashed password.
4761 * @throws moodle_exception If a problem occurs while generating the hash.
4763 function hash_internal_user_password($password, $fasthash = false) {
4764 global $CFG;
4766 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4767 $options = ($fasthash) ? array('cost' => 4) : array();
4769 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4771 if ($generatedhash === false || $generatedhash === null) {
4772 throw new moodle_exception('Failed to generate password hash.');
4775 return $generatedhash;
4779 * Update password hash in user object (if necessary).
4781 * The password is updated if:
4782 * 1. The password has changed (the hash of $user->password is different
4783 * to the hash of $password).
4784 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4785 * md5 algorithm).
4787 * Updating the password will modify the $user object and the database
4788 * record to use the current hashing algorithm.
4789 * It will remove Web Services user tokens too.
4791 * @param stdClass $user User object (password property may be updated).
4792 * @param string $password Plain text password.
4793 * @param bool $fasthash If true, use a low cost factor when generating the hash
4794 * This is much faster to generate but makes the hash
4795 * less secure. It is used when lots of hashes need to
4796 * be generated quickly.
4797 * @return bool Always returns true.
4799 function update_internal_user_password($user, $password, $fasthash = false) {
4800 global $CFG, $DB;
4802 // Figure out what the hashed password should be.
4803 if (!isset($user->auth)) {
4804 debugging('User record in update_internal_user_password() must include field auth',
4805 DEBUG_DEVELOPER);
4806 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4808 $authplugin = get_auth_plugin($user->auth);
4809 if ($authplugin->prevent_local_passwords()) {
4810 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4811 } else {
4812 $hashedpassword = hash_internal_user_password($password, $fasthash);
4815 $algorithmchanged = false;
4817 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4818 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4819 $passwordchanged = ($user->password !== $hashedpassword);
4821 } else if (isset($user->password)) {
4822 // If verification fails then it means the password has changed.
4823 $passwordchanged = !password_verify($password, $user->password);
4824 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4825 } else {
4826 // While creating new user, password in unset in $user object, to avoid
4827 // saving it with user_create()
4828 $passwordchanged = true;
4831 if ($passwordchanged || $algorithmchanged) {
4832 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4833 $user->password = $hashedpassword;
4835 // Trigger event.
4836 $user = $DB->get_record('user', array('id' => $user->id));
4837 \core\event\user_password_updated::create_from_user($user)->trigger();
4839 // Remove WS user tokens.
4840 if (!empty($CFG->passwordchangetokendeletion)) {
4841 require_once($CFG->dirroot.'/webservice/lib.php');
4842 webservice::delete_user_ws_tokens($user->id);
4846 return true;
4850 * Get a complete user record, which includes all the info in the user record.
4852 * Intended for setting as $USER session variable
4854 * @param string $field The user field to be checked for a given value.
4855 * @param string $value The value to match for $field.
4856 * @param int $mnethostid
4857 * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4858 * found. Otherwise, it will just return false.
4859 * @return mixed False, or A {@link $USER} object.
4861 function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4862 global $CFG, $DB;
4864 if (!$field || !$value) {
4865 return false;
4868 // Change the field to lowercase.
4869 $field = core_text::strtolower($field);
4871 // List of case insensitive fields.
4872 $caseinsensitivefields = ['email'];
4874 // Username input is forced to lowercase and should be case sensitive.
4875 if ($field == 'username') {
4876 $value = core_text::strtolower($value);
4879 // Build the WHERE clause for an SQL query.
4880 $params = array('fieldval' => $value);
4882 // Do a case-insensitive query, if necessary. These are generally very expensive. The performance can be improved on some DBs
4883 // such as MySQL by pre-filtering users with accent-insensitive subselect.
4884 if (in_array($field, $caseinsensitivefields)) {
4885 $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4886 $idsubselect = $DB->sql_equal($field, ':fieldval2', false, false);
4887 $params['fieldval2'] = $value;
4888 } else {
4889 $fieldselect = "$field = :fieldval";
4890 $idsubselect = '';
4892 $constraints = "$fieldselect AND deleted <> 1";
4894 // If we are loading user data based on anything other than id,
4895 // we must also restrict our search based on mnet host.
4896 if ($field != 'id') {
4897 if (empty($mnethostid)) {
4898 // If empty, we restrict to local users.
4899 $mnethostid = $CFG->mnet_localhost_id;
4902 if (!empty($mnethostid)) {
4903 $params['mnethostid'] = $mnethostid;
4904 $constraints .= " AND mnethostid = :mnethostid";
4907 if ($idsubselect) {
4908 $constraints .= " AND id IN (SELECT id FROM {user} WHERE {$idsubselect})";
4911 // Get all the basic user data.
4912 try {
4913 // Make sure that there's only a single record that matches our query.
4914 // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4915 // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4916 $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST);
4917 } catch (dml_exception $exception) {
4918 if ($throwexception) {
4919 throw $exception;
4920 } else {
4921 // Return false when no records or multiple records were found.
4922 return false;
4926 // Get various settings and preferences.
4928 // Preload preference cache.
4929 check_user_preferences_loaded($user);
4931 // Load course enrolment related stuff.
4932 $user->lastcourseaccess = array(); // During last session.
4933 $user->currentcourseaccess = array(); // During current session.
4934 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4935 foreach ($lastaccesses as $lastaccess) {
4936 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4940 // Add cohort theme.
4941 if (!empty($CFG->allowcohortthemes)) {
4942 require_once($CFG->dirroot . '/cohort/lib.php');
4943 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4944 $user->cohorttheme = $cohorttheme;
4948 // Add the custom profile fields to the user record.
4949 $user->profile = array();
4950 if (!isguestuser($user)) {
4951 require_once($CFG->dirroot.'/user/profile/lib.php');
4952 profile_load_custom_fields($user);
4955 // Rewrite some variables if necessary.
4956 if (!empty($user->description)) {
4957 // No need to cart all of it around.
4958 $user->description = true;
4960 if (isguestuser($user)) {
4961 // Guest language always same as site.
4962 $user->lang = get_newuser_language();
4963 // Name always in current language.
4964 $user->firstname = get_string('guestuser');
4965 $user->lastname = ' ';
4968 return $user;
4972 * Validate a password against the configured password policy
4974 * @param string $password the password to be checked against the password policy
4975 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4976 * @param stdClass $user the user object to perform password validation against. Defaults to null if not provided.
4978 * @return bool true if the password is valid according to the policy. false otherwise.
4980 function check_password_policy($password, &$errmsg, $user = null) {
4981 global $CFG;
4983 if (!empty($CFG->passwordpolicy)) {
4984 $errmsg = '';
4985 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4986 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4988 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4989 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4991 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4992 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4994 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4995 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4997 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4998 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
5000 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
5001 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
5004 // Fire any additional password policy functions from plugins.
5005 // Plugin functions should output an error message string or empty string for success.
5006 $pluginsfunction = get_plugins_with_function('check_password_policy');
5007 foreach ($pluginsfunction as $plugintype => $plugins) {
5008 foreach ($plugins as $pluginfunction) {
5009 $pluginerr = $pluginfunction($password, $user);
5010 if ($pluginerr) {
5011 $errmsg .= '<div>'. $pluginerr .'</div>';
5017 if ($errmsg == '') {
5018 return true;
5019 } else {
5020 return false;
5026 * When logging in, this function is run to set certain preferences for the current SESSION.
5028 function set_login_session_preferences() {
5029 global $SESSION;
5031 $SESSION->justloggedin = true;
5033 unset($SESSION->lang);
5034 unset($SESSION->forcelang);
5035 unset($SESSION->load_navigation_admin);
5040 * Delete a course, including all related data from the database, and any associated files.
5042 * @param mixed $courseorid The id of the course or course object to delete.
5043 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5044 * @return bool true if all the removals succeeded. false if there were any failures. If this
5045 * method returns false, some of the removals will probably have succeeded, and others
5046 * failed, but you have no way of knowing which.
5048 function delete_course($courseorid, $showfeedback = true) {
5049 global $DB;
5051 if (is_object($courseorid)) {
5052 $courseid = $courseorid->id;
5053 $course = $courseorid;
5054 } else {
5055 $courseid = $courseorid;
5056 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
5057 return false;
5060 $context = context_course::instance($courseid);
5062 // Frontpage course can not be deleted!!
5063 if ($courseid == SITEID) {
5064 return false;
5067 // Allow plugins to use this course before we completely delete it.
5068 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
5069 foreach ($pluginsfunction as $plugintype => $plugins) {
5070 foreach ($plugins as $pluginfunction) {
5071 $pluginfunction($course);
5076 // Tell the search manager we are about to delete a course. This prevents us sending updates
5077 // for each individual context being deleted.
5078 \core_search\manager::course_deleting_start($courseid);
5080 $handler = core_course\customfield\course_handler::create();
5081 $handler->delete_instance($courseid);
5083 // Make the course completely empty.
5084 remove_course_contents($courseid, $showfeedback);
5086 // Delete the course and related context instance.
5087 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
5089 $DB->delete_records("course", array("id" => $courseid));
5090 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5092 // Reset all course related caches here.
5093 core_courseformat\base::reset_course_cache($courseid);
5095 // Tell search that we have deleted the course so it can delete course data from the index.
5096 \core_search\manager::course_deleting_finish($courseid);
5098 // Trigger a course deleted event.
5099 $event = \core\event\course_deleted::create(array(
5100 'objectid' => $course->id,
5101 'context' => $context,
5102 'other' => array(
5103 'shortname' => $course->shortname,
5104 'fullname' => $course->fullname,
5105 'idnumber' => $course->idnumber
5108 $event->add_record_snapshot('course', $course);
5109 $event->trigger();
5111 return true;
5115 * Clear a course out completely, deleting all content but don't delete the course itself.
5117 * This function does not verify any permissions.
5119 * Please note this function also deletes all user enrolments,
5120 * enrolment instances and role assignments by default.
5122 * $options:
5123 * - 'keep_roles_and_enrolments' - false by default
5124 * - 'keep_groups_and_groupings' - false by default
5126 * @param int $courseid The id of the course that is being deleted
5127 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5128 * @param array $options extra options
5129 * @return bool true if all the removals succeeded. false if there were any failures. If this
5130 * method returns false, some of the removals will probably have succeeded, and others
5131 * failed, but you have no way of knowing which.
5133 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5134 global $CFG, $DB, $OUTPUT;
5136 require_once($CFG->libdir.'/badgeslib.php');
5137 require_once($CFG->libdir.'/completionlib.php');
5138 require_once($CFG->libdir.'/questionlib.php');
5139 require_once($CFG->libdir.'/gradelib.php');
5140 require_once($CFG->dirroot.'/group/lib.php');
5141 require_once($CFG->dirroot.'/comment/lib.php');
5142 require_once($CFG->dirroot.'/rating/lib.php');
5143 require_once($CFG->dirroot.'/notes/lib.php');
5145 // Handle course badges.
5146 badges_handle_course_deletion($courseid);
5148 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5149 $strdeleted = get_string('deleted').' - ';
5151 // Some crazy wishlist of stuff we should skip during purging of course content.
5152 $options = (array)$options;
5154 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5155 $coursecontext = context_course::instance($courseid);
5156 $fs = get_file_storage();
5158 // Delete course completion information, this has to be done before grades and enrols.
5159 $cc = new completion_info($course);
5160 $cc->clear_criteria();
5161 if ($showfeedback) {
5162 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5165 // Remove all data from gradebook - this needs to be done before course modules
5166 // because while deleting this information, the system may need to reference
5167 // the course modules that own the grades.
5168 remove_course_grades($courseid, $showfeedback);
5169 remove_grade_letters($coursecontext, $showfeedback);
5171 // Delete course blocks in any all child contexts,
5172 // they may depend on modules so delete them first.
5173 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5174 foreach ($childcontexts as $childcontext) {
5175 blocks_delete_all_for_context($childcontext->id);
5177 unset($childcontexts);
5178 blocks_delete_all_for_context($coursecontext->id);
5179 if ($showfeedback) {
5180 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5183 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $courseid]);
5184 rebuild_course_cache($courseid, true);
5186 // Get the list of all modules that are properly installed.
5187 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5189 // Delete every instance of every module,
5190 // this has to be done before deleting of course level stuff.
5191 $locations = core_component::get_plugin_list('mod');
5192 foreach ($locations as $modname => $moddir) {
5193 if ($modname === 'NEWMODULE') {
5194 continue;
5196 if (array_key_exists($modname, $allmodules)) {
5197 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5198 FROM {".$modname."} m
5199 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5200 WHERE m.course = :courseid";
5201 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5202 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5204 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5205 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5207 if ($instances) {
5208 foreach ($instances as $cm) {
5209 if ($cm->id) {
5210 // Delete activity context questions and question categories.
5211 question_delete_activity($cm);
5212 // Notify the competency subsystem.
5213 \core_competency\api::hook_course_module_deleted($cm);
5215 // Delete all tag instances associated with the instance of this module.
5216 core_tag_tag::delete_instances("mod_{$modname}", null, context_module::instance($cm->id)->id);
5217 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
5219 if (function_exists($moddelete)) {
5220 // This purges all module data in related tables, extra user prefs, settings, etc.
5221 $moddelete($cm->modinstance);
5222 } else {
5223 // NOTE: we should not allow installation of modules with missing delete support!
5224 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5225 $DB->delete_records($modname, array('id' => $cm->modinstance));
5228 if ($cm->id) {
5229 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5230 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5231 $DB->delete_records('course_modules_completion', ['coursemoduleid' => $cm->id]);
5232 $DB->delete_records('course_modules_viewed', ['coursemoduleid' => $cm->id]);
5233 $DB->delete_records('course_modules', array('id' => $cm->id));
5234 rebuild_course_cache($cm->course, true);
5238 if ($instances and $showfeedback) {
5239 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5241 } else {
5242 // Ooops, this module is not properly installed, force-delete it in the next block.
5246 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5248 // Delete completion defaults.
5249 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5251 // Remove all data from availability and completion tables that is associated
5252 // with course-modules belonging to this course. Note this is done even if the
5253 // features are not enabled now, in case they were enabled previously.
5254 $DB->delete_records_subquery('course_modules_completion', 'coursemoduleid', 'id',
5255 'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
5256 $DB->delete_records_subquery('course_modules_viewed', 'coursemoduleid', 'id',
5257 'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
5259 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5260 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5261 $allmodulesbyid = array_flip($allmodules);
5262 foreach ($cms as $cm) {
5263 if (array_key_exists($cm->module, $allmodulesbyid)) {
5264 try {
5265 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5266 } catch (Exception $e) {
5267 // Ignore weird or missing table problems.
5270 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5271 $DB->delete_records('course_modules', array('id' => $cm->id));
5272 rebuild_course_cache($cm->course, true);
5275 if ($showfeedback) {
5276 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5279 // Delete questions and question categories.
5280 question_delete_course($course);
5281 if ($showfeedback) {
5282 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5285 // Delete content bank contents.
5286 $cb = new \core_contentbank\contentbank();
5287 $cbdeleted = $cb->delete_contents($coursecontext);
5288 if ($showfeedback && $cbdeleted) {
5289 echo $OUTPUT->notification($strdeleted.get_string('contentbank', 'contentbank'), 'notifysuccess');
5292 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5293 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5294 foreach ($childcontexts as $childcontext) {
5295 $childcontext->delete();
5297 unset($childcontexts);
5299 // Remove roles and enrolments by default.
5300 if (empty($options['keep_roles_and_enrolments'])) {
5301 // This hack is used in restore when deleting contents of existing course.
5302 // During restore, we should remove only enrolment related data that the user performing the restore has a
5303 // permission to remove.
5304 $userid = $options['userid'] ?? null;
5305 enrol_course_delete($course, $userid);
5306 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5307 if ($showfeedback) {
5308 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5312 // Delete any groups, removing members and grouping/course links first.
5313 if (empty($options['keep_groups_and_groupings'])) {
5314 groups_delete_groupings($course->id, $showfeedback);
5315 groups_delete_groups($course->id, $showfeedback);
5318 // Filters be gone!
5319 filter_delete_all_for_context($coursecontext->id);
5321 // Notes, you shall not pass!
5322 note_delete_all($course->id);
5324 // Die comments!
5325 comment::delete_comments($coursecontext->id);
5327 // Ratings are history too.
5328 $delopt = new stdclass();
5329 $delopt->contextid = $coursecontext->id;
5330 $rm = new rating_manager();
5331 $rm->delete_ratings($delopt);
5333 // Delete course tags.
5334 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5336 // Give the course format the opportunity to remove its obscure data.
5337 $format = course_get_format($course);
5338 $format->delete_format_data();
5340 // Notify the competency subsystem.
5341 \core_competency\api::hook_course_deleted($course);
5343 // Delete calendar events.
5344 $DB->delete_records('event', array('courseid' => $course->id));
5345 $fs->delete_area_files($coursecontext->id, 'calendar');
5347 // Delete all related records in other core tables that may have a courseid
5348 // This array stores the tables that need to be cleared, as
5349 // table_name => column_name that contains the course id.
5350 $tablestoclear = array(
5351 'backup_courses' => 'courseid', // Scheduled backup stuff.
5352 'user_lastaccess' => 'courseid', // User access info.
5354 foreach ($tablestoclear as $table => $col) {
5355 $DB->delete_records($table, array($col => $course->id));
5358 // Delete all course backup files.
5359 $fs->delete_area_files($coursecontext->id, 'backup');
5361 // Cleanup course record - remove links to deleted stuff.
5362 $oldcourse = new stdClass();
5363 $oldcourse->id = $course->id;
5364 $oldcourse->summary = '';
5365 $oldcourse->cacherev = 0;
5366 $oldcourse->legacyfiles = 0;
5367 if (!empty($options['keep_groups_and_groupings'])) {
5368 $oldcourse->defaultgroupingid = 0;
5370 $DB->update_record('course', $oldcourse);
5372 // Delete course sections.
5373 $DB->delete_records('course_sections', array('course' => $course->id));
5375 // Delete legacy, section and any other course files.
5376 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5378 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5379 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5380 // Easy, do not delete the context itself...
5381 $coursecontext->delete_content();
5382 } else {
5383 // Hack alert!!!!
5384 // We can not drop all context stuff because it would bork enrolments and roles,
5385 // there might be also files used by enrol plugins...
5388 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5389 // also some non-standard unsupported plugins may try to store something there.
5390 fulldelete($CFG->dataroot.'/'.$course->id);
5392 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5393 course_modinfo::purge_course_cache($courseid);
5395 // Trigger a course content deleted event.
5396 $event = \core\event\course_content_deleted::create(array(
5397 'objectid' => $course->id,
5398 'context' => $coursecontext,
5399 'other' => array('shortname' => $course->shortname,
5400 'fullname' => $course->fullname,
5401 'options' => $options) // Passing this for legacy reasons.
5403 $event->add_record_snapshot('course', $course);
5404 $event->trigger();
5406 return true;
5410 * Change dates in module - used from course reset.
5412 * @param string $modname forum, assignment, etc
5413 * @param array $fields array of date fields from mod table
5414 * @param int $timeshift time difference
5415 * @param int $courseid
5416 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5417 * @return bool success
5419 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5420 global $CFG, $DB;
5421 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5423 $return = true;
5424 $params = array($timeshift, $courseid);
5425 foreach ($fields as $field) {
5426 $updatesql = "UPDATE {".$modname."}
5427 SET $field = $field + ?
5428 WHERE course=? AND $field<>0";
5429 if ($modid) {
5430 $updatesql .= ' AND id=?';
5431 $params[] = $modid;
5433 $return = $DB->execute($updatesql, $params) && $return;
5436 return $return;
5440 * This function will empty a course of user data.
5441 * It will retain the activities and the structure of the course.
5443 * @param object $data an object containing all the settings including courseid (without magic quotes)
5444 * @return array status array of array component, item, error
5446 function reset_course_userdata($data) {
5447 global $CFG, $DB;
5448 require_once($CFG->libdir.'/gradelib.php');
5449 require_once($CFG->libdir.'/completionlib.php');
5450 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5451 require_once($CFG->dirroot.'/group/lib.php');
5453 $data->courseid = $data->id;
5454 $context = context_course::instance($data->courseid);
5456 $eventparams = array(
5457 'context' => $context,
5458 'courseid' => $data->id,
5459 'other' => array(
5460 'reset_options' => (array) $data
5463 $event = \core\event\course_reset_started::create($eventparams);
5464 $event->trigger();
5466 // Calculate the time shift of dates.
5467 if (!empty($data->reset_start_date)) {
5468 // Time part of course startdate should be zero.
5469 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5470 } else {
5471 $data->timeshift = 0;
5474 // Result array: component, item, error.
5475 $status = array();
5477 // Start the resetting.
5478 $componentstr = get_string('general');
5480 // Move the course start time.
5481 if (!empty($data->reset_start_date) and $data->timeshift) {
5482 // Change course start data.
5483 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5484 // Update all course and group events - do not move activity events.
5485 $updatesql = "UPDATE {event}
5486 SET timestart = timestart + ?
5487 WHERE courseid=? AND instance=0";
5488 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5490 // Update any date activity restrictions.
5491 if ($CFG->enableavailability) {
5492 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5495 // Update completion expected dates.
5496 if ($CFG->enablecompletion) {
5497 $modinfo = get_fast_modinfo($data->courseid);
5498 $changed = false;
5499 foreach ($modinfo->get_cms() as $cm) {
5500 if ($cm->completion && !empty($cm->completionexpected)) {
5501 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5502 array('id' => $cm->id));
5503 $changed = true;
5507 // Clear course cache if changes made.
5508 if ($changed) {
5509 rebuild_course_cache($data->courseid, true);
5512 // Update course date completion criteria.
5513 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5516 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5519 if (!empty($data->reset_end_date)) {
5520 // If the user set a end date value respect it.
5521 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5522 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5523 // If there is a time shift apply it to the end date as well.
5524 $enddate = $data->reset_end_date_old + $data->timeshift;
5525 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5528 if (!empty($data->reset_events)) {
5529 $DB->delete_records('event', array('courseid' => $data->courseid));
5530 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5533 if (!empty($data->reset_notes)) {
5534 require_once($CFG->dirroot.'/notes/lib.php');
5535 note_delete_all($data->courseid);
5536 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5539 if (!empty($data->delete_blog_associations)) {
5540 require_once($CFG->dirroot.'/blog/lib.php');
5541 blog_remove_associations_for_course($data->courseid);
5542 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5545 if (!empty($data->reset_completion)) {
5546 // Delete course and activity completion information.
5547 $course = $DB->get_record('course', array('id' => $data->courseid));
5548 $cc = new completion_info($course);
5549 $cc->delete_all_completion_data();
5550 $status[] = array('component' => $componentstr,
5551 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5554 if (!empty($data->reset_competency_ratings)) {
5555 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5556 $status[] = array('component' => $componentstr,
5557 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5560 $componentstr = get_string('roles');
5562 if (!empty($data->reset_roles_overrides)) {
5563 $children = $context->get_child_contexts();
5564 foreach ($children as $child) {
5565 $child->delete_capabilities();
5567 $context->delete_capabilities();
5568 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5571 if (!empty($data->reset_roles_local)) {
5572 $children = $context->get_child_contexts();
5573 foreach ($children as $child) {
5574 role_unassign_all(array('contextid' => $child->id));
5576 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5579 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5580 $data->unenrolled = array();
5581 if (!empty($data->unenrol_users)) {
5582 $plugins = enrol_get_plugins(true);
5583 $instances = enrol_get_instances($data->courseid, true);
5584 foreach ($instances as $key => $instance) {
5585 if (!isset($plugins[$instance->enrol])) {
5586 unset($instances[$key]);
5587 continue;
5591 $usersroles = enrol_get_course_users_roles($data->courseid);
5592 foreach ($data->unenrol_users as $withroleid) {
5593 if ($withroleid) {
5594 $sql = "SELECT ue.*
5595 FROM {user_enrolments} ue
5596 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5597 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5598 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5599 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5601 } else {
5602 // Without any role assigned at course context.
5603 $sql = "SELECT ue.*
5604 FROM {user_enrolments} ue
5605 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5606 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5607 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5608 WHERE ra.id IS null";
5609 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5612 $rs = $DB->get_recordset_sql($sql, $params);
5613 foreach ($rs as $ue) {
5614 if (!isset($instances[$ue->enrolid])) {
5615 continue;
5617 $instance = $instances[$ue->enrolid];
5618 $plugin = $plugins[$instance->enrol];
5619 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5620 continue;
5623 if ($withroleid && count($usersroles[$ue->userid]) > 1) {
5624 // If we don't remove all roles and user has more than one role, just remove this role.
5625 role_unassign($withroleid, $ue->userid, $context->id);
5627 unset($usersroles[$ue->userid][$withroleid]);
5628 } else {
5629 // If we remove all roles or user has only one role, unenrol user from course.
5630 $plugin->unenrol_user($instance, $ue->userid);
5632 $data->unenrolled[$ue->userid] = $ue->userid;
5634 $rs->close();
5637 if (!empty($data->unenrolled)) {
5638 $status[] = array(
5639 'component' => $componentstr,
5640 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5641 'error' => false
5645 $componentstr = get_string('groups');
5647 // Remove all group members.
5648 if (!empty($data->reset_groups_members)) {
5649 groups_delete_group_members($data->courseid);
5650 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5653 // Remove all groups.
5654 if (!empty($data->reset_groups_remove)) {
5655 groups_delete_groups($data->courseid, false);
5656 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5659 // Remove all grouping members.
5660 if (!empty($data->reset_groupings_members)) {
5661 groups_delete_groupings_groups($data->courseid, false);
5662 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5665 // Remove all groupings.
5666 if (!empty($data->reset_groupings_remove)) {
5667 groups_delete_groupings($data->courseid, false);
5668 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5671 // Look in every instance of every module for data to delete.
5672 $unsupportedmods = array();
5673 if ($allmods = $DB->get_records('modules') ) {
5674 foreach ($allmods as $mod) {
5675 $modname = $mod->name;
5676 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5677 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5678 if (file_exists($modfile)) {
5679 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5680 continue; // Skip mods with no instances.
5682 include_once($modfile);
5683 if (function_exists($moddeleteuserdata)) {
5684 $modstatus = $moddeleteuserdata($data);
5685 if (is_array($modstatus)) {
5686 $status = array_merge($status, $modstatus);
5687 } else {
5688 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5690 } else {
5691 $unsupportedmods[] = $mod;
5693 } else {
5694 debugging('Missing lib.php in '.$modname.' module!');
5696 // Update calendar events for all modules.
5697 course_module_bulk_update_calendar_events($modname, $data->courseid);
5701 // Mention unsupported mods.
5702 if (!empty($unsupportedmods)) {
5703 foreach ($unsupportedmods as $mod) {
5704 $status[] = array(
5705 'component' => get_string('modulenameplural', $mod->name),
5706 'item' => '',
5707 'error' => get_string('resetnotimplemented')
5712 $componentstr = get_string('gradebook', 'grades');
5713 // Reset gradebook,.
5714 if (!empty($data->reset_gradebook_items)) {
5715 remove_course_grades($data->courseid, false);
5716 grade_grab_course_grades($data->courseid);
5717 grade_regrade_final_grades($data->courseid);
5718 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5720 } else if (!empty($data->reset_gradebook_grades)) {
5721 grade_course_reset($data->courseid);
5722 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5724 // Reset comments.
5725 if (!empty($data->reset_comments)) {
5726 require_once($CFG->dirroot.'/comment/lib.php');
5727 comment::reset_course_page_comments($context);
5730 $event = \core\event\course_reset_ended::create($eventparams);
5731 $event->trigger();
5733 return $status;
5737 * Generate an email processing address.
5739 * @param int $modid
5740 * @param string $modargs
5741 * @return string Returns email processing address
5743 function generate_email_processing_address($modid, $modargs) {
5744 global $CFG;
5746 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5747 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5753 * @todo Finish documenting this function
5755 * @param string $modargs
5756 * @param string $body Currently unused
5758 function moodle_process_email($modargs, $body) {
5759 global $DB;
5761 // The first char should be an unencoded letter. We'll take this as an action.
5762 switch ($modargs[0]) {
5763 case 'B': { // Bounce.
5764 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5765 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5766 // Check the half md5 of their email.
5767 $md5check = substr(md5($user->email), 0, 16);
5768 if ($md5check == substr($modargs, -16)) {
5769 set_bounce_count($user);
5771 // Else maybe they've already changed it?
5774 break;
5775 // Maybe more later?
5779 // CORRESPONDENCE.
5782 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5784 * @param string $action 'get', 'buffer', 'close' or 'flush'
5785 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5787 function get_mailer($action='get') {
5788 global $CFG;
5790 /** @var moodle_phpmailer $mailer */
5791 static $mailer = null;
5792 static $counter = 0;
5794 if (!isset($CFG->smtpmaxbulk)) {
5795 $CFG->smtpmaxbulk = 1;
5798 if ($action == 'get') {
5799 $prevkeepalive = false;
5801 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5802 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5803 $counter++;
5804 // Reset the mailer.
5805 $mailer->Priority = 3;
5806 $mailer->CharSet = 'UTF-8'; // Our default.
5807 $mailer->ContentType = "text/plain";
5808 $mailer->Encoding = "8bit";
5809 $mailer->From = "root@localhost";
5810 $mailer->FromName = "Root User";
5811 $mailer->Sender = "";
5812 $mailer->Subject = "";
5813 $mailer->Body = "";
5814 $mailer->AltBody = "";
5815 $mailer->ConfirmReadingTo = "";
5817 $mailer->clearAllRecipients();
5818 $mailer->clearReplyTos();
5819 $mailer->clearAttachments();
5820 $mailer->clearCustomHeaders();
5821 return $mailer;
5824 $prevkeepalive = $mailer->SMTPKeepAlive;
5825 get_mailer('flush');
5828 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5829 $mailer = new moodle_phpmailer();
5831 $counter = 1;
5833 if ($CFG->smtphosts == 'qmail') {
5834 // Use Qmail system.
5835 $mailer->isQmail();
5837 } else if (empty($CFG->smtphosts)) {
5838 // Use PHP mail() = sendmail.
5839 $mailer->isMail();
5841 } else {
5842 // Use SMTP directly.
5843 $mailer->isSMTP();
5844 if (!empty($CFG->debugsmtp) && (!empty($CFG->debugdeveloper))) {
5845 $mailer->SMTPDebug = 3;
5847 // Specify main and backup servers.
5848 $mailer->Host = $CFG->smtphosts;
5849 // Specify secure connection protocol.
5850 $mailer->SMTPSecure = $CFG->smtpsecure;
5851 // Use previous keepalive.
5852 $mailer->SMTPKeepAlive = $prevkeepalive;
5854 if ($CFG->smtpuser) {
5855 // Use SMTP authentication.
5856 $mailer->SMTPAuth = true;
5857 $mailer->Username = $CFG->smtpuser;
5858 $mailer->Password = $CFG->smtppass;
5862 return $mailer;
5865 $nothing = null;
5867 // Keep smtp session open after sending.
5868 if ($action == 'buffer') {
5869 if (!empty($CFG->smtpmaxbulk)) {
5870 get_mailer('flush');
5871 $m = get_mailer();
5872 if ($m->Mailer == 'smtp') {
5873 $m->SMTPKeepAlive = true;
5876 return $nothing;
5879 // Close smtp session, but continue buffering.
5880 if ($action == 'flush') {
5881 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5882 if (!empty($mailer->SMTPDebug)) {
5883 echo '<pre>'."\n";
5885 $mailer->SmtpClose();
5886 if (!empty($mailer->SMTPDebug)) {
5887 echo '</pre>';
5890 return $nothing;
5893 // Close smtp session, do not buffer anymore.
5894 if ($action == 'close') {
5895 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5896 get_mailer('flush');
5897 $mailer->SMTPKeepAlive = false;
5899 $mailer = null; // Better force new instance.
5900 return $nothing;
5905 * A helper function to test for email diversion
5907 * @param string $email
5908 * @return bool Returns true if the email should be diverted
5910 function email_should_be_diverted($email) {
5911 global $CFG;
5913 if (empty($CFG->divertallemailsto)) {
5914 return false;
5917 if (empty($CFG->divertallemailsexcept)) {
5918 return true;
5921 $patterns = array_map('trim', preg_split("/[\s,]+/", $CFG->divertallemailsexcept, -1, PREG_SPLIT_NO_EMPTY));
5922 foreach ($patterns as $pattern) {
5923 if (preg_match("/$pattern/", $email)) {
5924 return false;
5928 return true;
5932 * Generate a unique email Message-ID using the moodle domain and install path
5934 * @param string $localpart An optional unique message id prefix.
5935 * @return string The formatted ID ready for appending to the email headers.
5937 function generate_email_messageid($localpart = null) {
5938 global $CFG;
5940 $urlinfo = parse_url($CFG->wwwroot);
5941 $base = '@' . $urlinfo['host'];
5943 // If multiple moodles are on the same domain we want to tell them
5944 // apart so we add the install path to the local part. This means
5945 // that the id local part should never contain a / character so
5946 // we can correctly parse the id to reassemble the wwwroot.
5947 if (isset($urlinfo['path'])) {
5948 $base = $urlinfo['path'] . $base;
5951 if (empty($localpart)) {
5952 $localpart = uniqid('', true);
5955 // Because we may have an option /installpath suffix to the local part
5956 // of the id we need to escape any / chars which are in the $localpart.
5957 $localpart = str_replace('/', '%2F', $localpart);
5959 return '<' . $localpart . $base . '>';
5963 * Send an email to a specified user
5965 * @param stdClass $user A {@link $USER} object
5966 * @param stdClass $from A {@link $USER} object
5967 * @param string $subject plain text subject line of the email
5968 * @param string $messagetext plain text version of the message
5969 * @param string $messagehtml complete html version of the message (optional)
5970 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in one of
5971 * the following directories: $CFG->cachedir, $CFG->dataroot, $CFG->dirroot, $CFG->localcachedir, $CFG->tempdir
5972 * @param string $attachname the name of the file (extension indicates MIME)
5973 * @param bool $usetrueaddress determines whether $from email address should
5974 * be sent out. Will be overruled by user profile setting for maildisplay
5975 * @param string $replyto Email address to reply to
5976 * @param string $replytoname Name of reply to recipient
5977 * @param int $wordwrapwidth custom word wrap width, default 79
5978 * @return bool Returns true if mail was sent OK and false if there was an error.
5980 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5981 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5983 global $CFG, $PAGE, $SITE;
5985 if (empty($user) or empty($user->id)) {
5986 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5987 return false;
5990 if (empty($user->email)) {
5991 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5992 return false;
5995 if (!empty($user->deleted)) {
5996 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5997 return false;
6000 if (defined('BEHAT_SITE_RUNNING')) {
6001 // Fake email sending in behat.
6002 return true;
6005 if (!empty($CFG->noemailever)) {
6006 // Hidden setting for development sites, set in config.php if needed.
6007 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
6008 return true;
6011 if (email_should_be_diverted($user->email)) {
6012 $subject = "[DIVERTED {$user->email}] $subject";
6013 $user = clone($user);
6014 $user->email = $CFG->divertallemailsto;
6017 // Skip mail to suspended users.
6018 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
6019 return true;
6022 if (!validate_email($user->email)) {
6023 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
6024 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
6025 return false;
6028 if (over_bounce_threshold($user)) {
6029 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
6030 return false;
6033 // TLD .invalid is specifically reserved for invalid domain names.
6034 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
6035 if (substr($user->email, -8) == '.invalid') {
6036 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
6037 return true; // This is not an error.
6040 // If the user is a remote mnet user, parse the email text for URL to the
6041 // wwwroot and modify the url to direct the user's browser to login at their
6042 // home site (identity provider - idp) before hitting the link itself.
6043 if (is_mnet_remote_user($user)) {
6044 require_once($CFG->dirroot.'/mnet/lib.php');
6046 $jumpurl = mnet_get_idp_jump_url($user);
6047 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
6049 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
6050 $callback,
6051 $messagetext);
6052 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
6053 $callback,
6054 $messagehtml);
6056 $mail = get_mailer();
6058 if (!empty($mail->SMTPDebug)) {
6059 echo '<pre>' . "\n";
6062 $temprecipients = array();
6063 $tempreplyto = array();
6065 // Make sure that we fall back onto some reasonable no-reply address.
6066 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
6067 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
6069 if (!validate_email($noreplyaddress)) {
6070 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
6071 $noreplyaddress = $noreplyaddressdefault;
6074 // Make up an email address for handling bounces.
6075 if (!empty($CFG->handlebounces)) {
6076 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
6077 $mail->Sender = generate_email_processing_address(0, $modargs);
6078 } else {
6079 $mail->Sender = $noreplyaddress;
6082 // Make sure that the explicit replyto is valid, fall back to the implicit one.
6083 if (!empty($replyto) && !validate_email($replyto)) {
6084 debugging('email_to_user: Invalid replyto-email '.s($replyto));
6085 $replyto = $noreplyaddress;
6088 if (is_string($from)) { // So we can pass whatever we want if there is need.
6089 $mail->From = $noreplyaddress;
6090 $mail->FromName = $from;
6091 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
6092 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6093 // in a course with the sender.
6094 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
6095 if (!validate_email($from->email)) {
6096 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
6097 // Better not to use $noreplyaddress in this case.
6098 return false;
6100 $mail->From = $from->email;
6101 $fromdetails = new stdClass();
6102 $fromdetails->name = fullname($from);
6103 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6104 $fromdetails->siteshortname = format_string($SITE->shortname);
6105 $fromstring = $fromdetails->name;
6106 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
6107 $fromstring = get_string('emailvia', 'core', $fromdetails);
6109 $mail->FromName = $fromstring;
6110 if (empty($replyto)) {
6111 $tempreplyto[] = array($from->email, fullname($from));
6113 } else {
6114 $mail->From = $noreplyaddress;
6115 $fromdetails = new stdClass();
6116 $fromdetails->name = fullname($from);
6117 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6118 $fromdetails->siteshortname = format_string($SITE->shortname);
6119 $fromstring = $fromdetails->name;
6120 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
6121 $fromstring = get_string('emailvia', 'core', $fromdetails);
6123 $mail->FromName = $fromstring;
6124 if (empty($replyto)) {
6125 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
6129 if (!empty($replyto)) {
6130 $tempreplyto[] = array($replyto, $replytoname);
6133 $temprecipients[] = array($user->email, fullname($user));
6135 // Set word wrap.
6136 $mail->WordWrap = $wordwrapwidth;
6138 if (!empty($from->customheaders)) {
6139 // Add custom headers.
6140 if (is_array($from->customheaders)) {
6141 foreach ($from->customheaders as $customheader) {
6142 $mail->addCustomHeader($customheader);
6144 } else {
6145 $mail->addCustomHeader($from->customheaders);
6149 // If the X-PHP-Originating-Script email header is on then also add an additional
6150 // header with details of where exactly in moodle the email was triggered from,
6151 // either a call to message_send() or to email_to_user().
6152 if (ini_get('mail.add_x_header')) {
6154 $stack = debug_backtrace(false);
6155 $origin = $stack[0];
6157 foreach ($stack as $depth => $call) {
6158 if ($call['function'] == 'message_send') {
6159 $origin = $call;
6163 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
6164 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
6165 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
6168 if (!empty($CFG->emailheaders)) {
6169 $headers = array_map('trim', explode("\n", $CFG->emailheaders));
6170 foreach ($headers as $header) {
6171 if (!empty($header)) {
6172 $mail->addCustomHeader($header);
6177 if (!empty($from->priority)) {
6178 $mail->Priority = $from->priority;
6181 $renderer = $PAGE->get_renderer('core');
6182 $context = array(
6183 'sitefullname' => $SITE->fullname,
6184 'siteshortname' => $SITE->shortname,
6185 'sitewwwroot' => $CFG->wwwroot,
6186 'subject' => $subject,
6187 'prefix' => $CFG->emailsubjectprefix,
6188 'to' => $user->email,
6189 'toname' => fullname($user),
6190 'from' => $mail->From,
6191 'fromname' => $mail->FromName,
6193 if (!empty($tempreplyto[0])) {
6194 $context['replyto'] = $tempreplyto[0][0];
6195 $context['replytoname'] = $tempreplyto[0][1];
6197 if ($user->id > 0) {
6198 $context['touserid'] = $user->id;
6199 $context['tousername'] = $user->username;
6202 if (!empty($user->mailformat) && $user->mailformat == 1) {
6203 // Only process html templates if the user preferences allow html email.
6205 if (!$messagehtml) {
6206 // If no html has been given, BUT there is an html wrapping template then
6207 // auto convert the text to html and then wrap it.
6208 $messagehtml = trim(text_to_html($messagetext));
6210 $context['body'] = $messagehtml;
6211 $messagehtml = $renderer->render_from_template('core/email_html', $context);
6214 $context['body'] = html_to_text(nl2br($messagetext));
6215 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
6216 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
6217 $messagetext = $renderer->render_from_template('core/email_text', $context);
6219 // Autogenerate a MessageID if it's missing.
6220 if (empty($mail->MessageID)) {
6221 $mail->MessageID = generate_email_messageid();
6224 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6225 // Don't ever send HTML to users who don't want it.
6226 $mail->isHTML(true);
6227 $mail->Encoding = 'quoted-printable';
6228 $mail->Body = $messagehtml;
6229 $mail->AltBody = "\n$messagetext\n";
6230 } else {
6231 $mail->IsHTML(false);
6232 $mail->Body = "\n$messagetext\n";
6235 if ($attachment && $attachname) {
6236 if (preg_match( "~\\.\\.~" , $attachment )) {
6237 // Security check for ".." in dir path.
6238 $supportuser = core_user::get_support_user();
6239 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6240 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6241 } else {
6242 require_once($CFG->libdir.'/filelib.php');
6243 $mimetype = mimeinfo('type', $attachname);
6245 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6246 // The absolute (real) path is also fetched to ensure that comparisons to allowed paths are compared equally.
6247 $attachpath = str_replace('\\', '/', realpath($attachment));
6249 // Build an array of all filepaths from which attachments can be added (normalised slashes, absolute/real path).
6250 $allowedpaths = array_map(function(string $path): string {
6251 return str_replace('\\', '/', realpath($path));
6252 }, [
6253 $CFG->cachedir,
6254 $CFG->dataroot,
6255 $CFG->dirroot,
6256 $CFG->localcachedir,
6257 $CFG->tempdir,
6258 $CFG->localrequestdir,
6261 // Set addpath to true.
6262 $addpath = true;
6264 // Check if attachment includes one of the allowed paths.
6265 foreach (array_filter($allowedpaths) as $allowedpath) {
6266 // Set addpath to false if the attachment includes one of the allowed paths.
6267 if (strpos($attachpath, $allowedpath) === 0) {
6268 $addpath = false;
6269 break;
6273 // If the attachment is a full path to a file in the multiple allowed paths, use it as is,
6274 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6275 if ($addpath == true) {
6276 $attachment = $CFG->dataroot . '/' . $attachment;
6279 $mail->addAttachment($attachment, $attachname, 'base64', $mimetype);
6283 // Check if the email should be sent in an other charset then the default UTF-8.
6284 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6286 // Use the defined site mail charset or eventually the one preferred by the recipient.
6287 $charset = $CFG->sitemailcharset;
6288 if (!empty($CFG->allowusermailcharset)) {
6289 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6290 $charset = $useremailcharset;
6294 // Convert all the necessary strings if the charset is supported.
6295 $charsets = get_list_of_charsets();
6296 unset($charsets['UTF-8']);
6297 if (in_array($charset, $charsets)) {
6298 $mail->CharSet = $charset;
6299 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6300 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6301 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6302 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6304 foreach ($temprecipients as $key => $values) {
6305 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6307 foreach ($tempreplyto as $key => $values) {
6308 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6313 foreach ($temprecipients as $values) {
6314 $mail->addAddress($values[0], $values[1]);
6316 foreach ($tempreplyto as $values) {
6317 $mail->addReplyTo($values[0], $values[1]);
6320 if (!empty($CFG->emaildkimselector)) {
6321 $domain = substr(strrchr($mail->From, "@"), 1);
6322 $pempath = "{$CFG->dataroot}/dkim/{$domain}/{$CFG->emaildkimselector}.private";
6323 if (file_exists($pempath)) {
6324 $mail->DKIM_domain = $domain;
6325 $mail->DKIM_private = $pempath;
6326 $mail->DKIM_selector = $CFG->emaildkimselector;
6327 $mail->DKIM_identity = $mail->From;
6328 } else {
6329 debugging("Email DKIM selector chosen due to {$mail->From} but no certificate found at $pempath", DEBUG_DEVELOPER);
6333 if ($mail->send()) {
6334 set_send_count($user);
6335 if (!empty($mail->SMTPDebug)) {
6336 echo '</pre>';
6338 return true;
6339 } else {
6340 // Trigger event for failing to send email.
6341 $event = \core\event\email_failed::create(array(
6342 'context' => context_system::instance(),
6343 'userid' => $from->id,
6344 'relateduserid' => $user->id,
6345 'other' => array(
6346 'subject' => $subject,
6347 'message' => $messagetext,
6348 'errorinfo' => $mail->ErrorInfo
6351 $event->trigger();
6352 if (CLI_SCRIPT) {
6353 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6355 if (!empty($mail->SMTPDebug)) {
6356 echo '</pre>';
6358 return false;
6363 * Check to see if a user's real email address should be used for the "From" field.
6365 * @param object $from The user object for the user we are sending the email from.
6366 * @param object $user The user object that we are sending the email to.
6367 * @param array $unused No longer used.
6368 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6370 function can_send_from_real_email_address($from, $user, $unused = null) {
6371 global $CFG;
6372 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6373 return false;
6375 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6376 // Email is in the list of allowed domains for sending email,
6377 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6378 // in a course with the sender.
6379 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6380 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6381 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6382 && enrol_get_shared_courses($user, $from, false, true)))) {
6383 return true;
6385 return false;
6389 * Generate a signoff for emails based on support settings
6391 * @return string
6393 function generate_email_signoff() {
6394 global $CFG, $OUTPUT;
6396 $signoff = "\n";
6397 if (!empty($CFG->supportname)) {
6398 $signoff .= $CFG->supportname."\n";
6401 $supportemail = $OUTPUT->supportemail(['class' => 'font-weight-bold']);
6403 if ($supportemail) {
6404 $signoff .= "\n" . $supportemail . "\n";
6407 return $signoff;
6411 * Sets specified user's password and send the new password to the user via email.
6413 * @param stdClass $user A {@link $USER} object
6414 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6415 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6417 function setnew_password_and_mail($user, $fasthash = false) {
6418 global $CFG, $DB;
6420 // We try to send the mail in language the user understands,
6421 // unfortunately the filter_string() does not support alternative langs yet
6422 // so multilang will not work properly for site->fullname.
6423 $lang = empty($user->lang) ? get_newuser_language() : $user->lang;
6425 $site = get_site();
6427 $supportuser = core_user::get_support_user();
6429 $newpassword = generate_password();
6431 update_internal_user_password($user, $newpassword, $fasthash);
6433 $a = new stdClass();
6434 $a->firstname = fullname($user, true);
6435 $a->sitename = format_string($site->fullname);
6436 $a->username = $user->username;
6437 $a->newpassword = $newpassword;
6438 $a->link = $CFG->wwwroot .'/login/?lang='.$lang;
6439 $a->signoff = generate_email_signoff();
6441 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6443 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6445 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6446 return email_to_user($user, $supportuser, $subject, $message);
6451 * Resets specified user's password and send the new password to the user via email.
6453 * @param stdClass $user A {@link $USER} object
6454 * @return bool Returns true if mail was sent OK and false if there was an error.
6456 function reset_password_and_mail($user) {
6457 global $CFG;
6459 $site = get_site();
6460 $supportuser = core_user::get_support_user();
6462 $userauth = get_auth_plugin($user->auth);
6463 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6464 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6465 return false;
6468 $newpassword = generate_password();
6470 if (!$userauth->user_update_password($user, $newpassword)) {
6471 throw new \moodle_exception("cannotsetpassword");
6474 $a = new stdClass();
6475 $a->firstname = $user->firstname;
6476 $a->lastname = $user->lastname;
6477 $a->sitename = format_string($site->fullname);
6478 $a->username = $user->username;
6479 $a->newpassword = $newpassword;
6480 $a->link = $CFG->wwwroot .'/login/change_password.php';
6481 $a->signoff = generate_email_signoff();
6483 $message = get_string('newpasswordtext', '', $a);
6485 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6487 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6489 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6490 return email_to_user($user, $supportuser, $subject, $message);
6494 * Send email to specified user with confirmation text and activation link.
6496 * @param stdClass $user A {@link $USER} object
6497 * @param string $confirmationurl user confirmation URL
6498 * @return bool Returns true if mail was sent OK and false if there was an error.
6500 function send_confirmation_email($user, $confirmationurl = null) {
6501 global $CFG;
6503 $site = get_site();
6504 $supportuser = core_user::get_support_user();
6506 $data = new stdClass();
6507 $data->sitename = format_string($site->fullname);
6508 $data->admin = generate_email_signoff();
6510 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6512 if (empty($confirmationurl)) {
6513 $confirmationurl = '/login/confirm.php';
6516 $confirmationurl = new moodle_url($confirmationurl);
6517 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6518 $confirmationurl->remove_params('data');
6519 $confirmationpath = $confirmationurl->out(false);
6521 // We need to custom encode the username to include trailing dots in the link.
6522 // Because of this custom encoding we can't use moodle_url directly.
6523 // Determine if a query string is present in the confirmation url.
6524 $hasquerystring = strpos($confirmationpath, '?') !== false;
6525 // Perform normal url encoding of the username first.
6526 $username = urlencode($user->username);
6527 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6528 $username = str_replace('.', '%2E', $username);
6530 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6532 $message = get_string('emailconfirmation', '', $data);
6533 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6535 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6536 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6540 * Sends a password change confirmation email.
6542 * @param stdClass $user A {@link $USER} object
6543 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6544 * @return bool Returns true if mail was sent OK and false if there was an error.
6546 function send_password_change_confirmation_email($user, $resetrecord) {
6547 global $CFG;
6549 $site = get_site();
6550 $supportuser = core_user::get_support_user();
6551 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6553 $data = new stdClass();
6554 $data->firstname = $user->firstname;
6555 $data->lastname = $user->lastname;
6556 $data->username = $user->username;
6557 $data->sitename = format_string($site->fullname);
6558 $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6559 $data->admin = generate_email_signoff();
6560 $data->resetminutes = $pwresetmins;
6562 $message = get_string('emailresetconfirmation', '', $data);
6563 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6565 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6566 return email_to_user($user, $supportuser, $subject, $message);
6571 * Sends an email containing information on how to change your password.
6573 * @param stdClass $user A {@link $USER} object
6574 * @return bool Returns true if mail was sent OK and false if there was an error.
6576 function send_password_change_info($user) {
6577 $site = get_site();
6578 $supportuser = core_user::get_support_user();
6580 $data = new stdClass();
6581 $data->firstname = $user->firstname;
6582 $data->lastname = $user->lastname;
6583 $data->username = $user->username;
6584 $data->sitename = format_string($site->fullname);
6585 $data->admin = generate_email_signoff();
6587 if (!is_enabled_auth($user->auth)) {
6588 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6589 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6590 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6591 return email_to_user($user, $supportuser, $subject, $message);
6594 $userauth = get_auth_plugin($user->auth);
6595 ['subject' => $subject, 'message' => $message] = $userauth->get_password_change_info($user);
6597 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6598 return email_to_user($user, $supportuser, $subject, $message);
6602 * Check that an email is allowed. It returns an error message if there was a problem.
6604 * @param string $email Content of email
6605 * @return string|false
6607 function email_is_not_allowed($email) {
6608 global $CFG;
6610 // Comparing lowercase domains.
6611 $email = strtolower($email);
6612 if (!empty($CFG->allowemailaddresses)) {
6613 $allowed = explode(' ', strtolower($CFG->allowemailaddresses));
6614 foreach ($allowed as $allowedpattern) {
6615 $allowedpattern = trim($allowedpattern);
6616 if (!$allowedpattern) {
6617 continue;
6619 if (strpos($allowedpattern, '.') === 0) {
6620 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6621 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6622 return false;
6625 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6626 return false;
6629 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6631 } else if (!empty($CFG->denyemailaddresses)) {
6632 $denied = explode(' ', strtolower($CFG->denyemailaddresses));
6633 foreach ($denied as $deniedpattern) {
6634 $deniedpattern = trim($deniedpattern);
6635 if (!$deniedpattern) {
6636 continue;
6638 if (strpos($deniedpattern, '.') === 0) {
6639 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6640 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6641 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6644 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6645 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6650 return false;
6653 // FILE HANDLING.
6656 * Returns local file storage instance
6658 * @return file_storage
6660 function get_file_storage($reset = false) {
6661 global $CFG;
6663 static $fs = null;
6665 if ($reset) {
6666 $fs = null;
6667 return;
6670 if ($fs) {
6671 return $fs;
6674 require_once("$CFG->libdir/filelib.php");
6676 $fs = new file_storage();
6678 return $fs;
6682 * Returns local file storage instance
6684 * @return file_browser
6686 function get_file_browser() {
6687 global $CFG;
6689 static $fb = null;
6691 if ($fb) {
6692 return $fb;
6695 require_once("$CFG->libdir/filelib.php");
6697 $fb = new file_browser();
6699 return $fb;
6703 * Returns file packer
6705 * @param string $mimetype default application/zip
6706 * @return file_packer
6708 function get_file_packer($mimetype='application/zip') {
6709 global $CFG;
6711 static $fp = array();
6713 if (isset($fp[$mimetype])) {
6714 return $fp[$mimetype];
6717 switch ($mimetype) {
6718 case 'application/zip':
6719 case 'application/vnd.moodle.profiling':
6720 $classname = 'zip_packer';
6721 break;
6723 case 'application/x-gzip' :
6724 $classname = 'tgz_packer';
6725 break;
6727 case 'application/vnd.moodle.backup':
6728 $classname = 'mbz_packer';
6729 break;
6731 default:
6732 return false;
6735 require_once("$CFG->libdir/filestorage/$classname.php");
6736 $fp[$mimetype] = new $classname();
6738 return $fp[$mimetype];
6742 * Returns current name of file on disk if it exists.
6744 * @param string $newfile File to be verified
6745 * @return string Current name of file on disk if true
6747 function valid_uploaded_file($newfile) {
6748 if (empty($newfile)) {
6749 return '';
6751 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6752 return $newfile['tmp_name'];
6753 } else {
6754 return '';
6759 * Returns the maximum size for uploading files.
6761 * There are seven possible upload limits:
6762 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6763 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6764 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6765 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6766 * 5. by the Moodle admin in $CFG->maxbytes
6767 * 6. by the teacher in the current course $course->maxbytes
6768 * 7. by the teacher for the current module, eg $assignment->maxbytes
6770 * These last two are passed to this function as arguments (in bytes).
6771 * Anything defined as 0 is ignored.
6772 * The smallest of all the non-zero numbers is returned.
6774 * @todo Finish documenting this function
6776 * @param int $sitebytes Set maximum size
6777 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6778 * @param int $modulebytes Current module ->maxbytes (in bytes)
6779 * @param bool $unused This parameter has been deprecated and is not used any more.
6780 * @return int The maximum size for uploading files.
6782 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6784 if (! $filesize = ini_get('upload_max_filesize')) {
6785 $filesize = '5M';
6787 $minimumsize = get_real_size($filesize);
6789 if ($postsize = ini_get('post_max_size')) {
6790 $postsize = get_real_size($postsize);
6791 if ($postsize < $minimumsize) {
6792 $minimumsize = $postsize;
6796 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6797 $minimumsize = $sitebytes;
6800 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6801 $minimumsize = $coursebytes;
6804 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6805 $minimumsize = $modulebytes;
6808 return $minimumsize;
6812 * Returns the maximum size for uploading files for the current user
6814 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6816 * @param context $context The context in which to check user capabilities
6817 * @param int $sitebytes Set maximum size
6818 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6819 * @param int $modulebytes Current module ->maxbytes (in bytes)
6820 * @param stdClass $user The user
6821 * @param bool $unused This parameter has been deprecated and is not used any more.
6822 * @return int The maximum size for uploading files.
6824 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6825 $unused = false) {
6826 global $USER;
6828 if (empty($user)) {
6829 $user = $USER;
6832 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6833 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6836 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6840 * Returns an array of possible sizes in local language
6842 * Related to {@link get_max_upload_file_size()} - this function returns an
6843 * array of possible sizes in an array, translated to the
6844 * local language.
6846 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6848 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6849 * with the value set to 0. This option will be the first in the list.
6851 * @uses SORT_NUMERIC
6852 * @param int $sitebytes Set maximum size
6853 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6854 * @param int $modulebytes Current module ->maxbytes (in bytes)
6855 * @param int|array $custombytes custom upload size/s which will be added to list,
6856 * Only value/s smaller then maxsize will be added to list.
6857 * @return array
6859 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6860 global $CFG;
6862 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6863 return array();
6866 if ($sitebytes == 0) {
6867 // Will get the minimum of upload_max_filesize or post_max_size.
6868 $sitebytes = get_max_upload_file_size();
6871 $filesize = array();
6872 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6873 5242880, 10485760, 20971520, 52428800, 104857600,
6874 262144000, 524288000, 786432000, 1073741824,
6875 2147483648, 4294967296, 8589934592);
6877 // If custombytes is given and is valid then add it to the list.
6878 if (is_number($custombytes) and $custombytes > 0) {
6879 $custombytes = (int)$custombytes;
6880 if (!in_array($custombytes, $sizelist)) {
6881 $sizelist[] = $custombytes;
6883 } else if (is_array($custombytes)) {
6884 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6887 // Allow maxbytes to be selected if it falls outside the above boundaries.
6888 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6889 // Note: get_real_size() is used in order to prevent problems with invalid values.
6890 $sizelist[] = get_real_size($CFG->maxbytes);
6893 foreach ($sizelist as $sizebytes) {
6894 if ($sizebytes < $maxsize && $sizebytes > 0) {
6895 $filesize[(string)intval($sizebytes)] = display_size($sizebytes, 0);
6899 $limitlevel = '';
6900 $displaysize = '';
6901 if ($modulebytes &&
6902 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6903 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6904 $limitlevel = get_string('activity', 'core');
6905 $displaysize = display_size($modulebytes, 0);
6906 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6908 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6909 $limitlevel = get_string('course', 'core');
6910 $displaysize = display_size($coursebytes, 0);
6911 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6913 } else if ($sitebytes) {
6914 $limitlevel = get_string('site', 'core');
6915 $displaysize = display_size($sitebytes, 0);
6916 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6919 krsort($filesize, SORT_NUMERIC);
6920 if ($limitlevel) {
6921 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6922 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6925 return $filesize;
6929 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6931 * If excludefiles is defined, then that file/directory is ignored
6932 * If getdirs is true, then (sub)directories are included in the output
6933 * If getfiles is true, then files are included in the output
6934 * (at least one of these must be true!)
6936 * @todo Finish documenting this function. Add examples of $excludefile usage.
6938 * @param string $rootdir A given root directory to start from
6939 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6940 * @param bool $descend If true then subdirectories are recursed as well
6941 * @param bool $getdirs If true then (sub)directories are included in the output
6942 * @param bool $getfiles If true then files are included in the output
6943 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6945 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6947 $dirs = array();
6949 if (!$getdirs and !$getfiles) { // Nothing to show.
6950 return $dirs;
6953 if (!is_dir($rootdir)) { // Must be a directory.
6954 return $dirs;
6957 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6958 return $dirs;
6961 if (!is_array($excludefiles)) {
6962 $excludefiles = array($excludefiles);
6965 while (false !== ($file = readdir($dir))) {
6966 $firstchar = substr($file, 0, 1);
6967 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6968 continue;
6970 $fullfile = $rootdir .'/'. $file;
6971 if (filetype($fullfile) == 'dir') {
6972 if ($getdirs) {
6973 $dirs[] = $file;
6975 if ($descend) {
6976 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6977 foreach ($subdirs as $subdir) {
6978 $dirs[] = $file .'/'. $subdir;
6981 } else if ($getfiles) {
6982 $dirs[] = $file;
6985 closedir($dir);
6987 asort($dirs);
6989 return $dirs;
6994 * Adds up all the files in a directory and works out the size.
6996 * @param string $rootdir The directory to start from
6997 * @param string $excludefile A file to exclude when summing directory size
6998 * @return int The summed size of all files and subfiles within the root directory
7000 function get_directory_size($rootdir, $excludefile='') {
7001 global $CFG;
7003 // Do it this way if we can, it's much faster.
7004 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
7005 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
7006 $output = null;
7007 $return = null;
7008 exec($command, $output, $return);
7009 if (is_array($output)) {
7010 // We told it to return k.
7011 return get_real_size(intval($output[0]).'k');
7015 if (!is_dir($rootdir)) {
7016 // Must be a directory.
7017 return 0;
7020 if (!$dir = @opendir($rootdir)) {
7021 // Can't open it for some reason.
7022 return 0;
7025 $size = 0;
7027 while (false !== ($file = readdir($dir))) {
7028 $firstchar = substr($file, 0, 1);
7029 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
7030 continue;
7032 $fullfile = $rootdir .'/'. $file;
7033 if (filetype($fullfile) == 'dir') {
7034 $size += get_directory_size($fullfile, $excludefile);
7035 } else {
7036 $size += filesize($fullfile);
7039 closedir($dir);
7041 return $size;
7045 * Converts bytes into display form
7047 * @param int $size The size to convert to human readable form
7048 * @param int $decimalplaces If specified, uses fixed number of decimal places
7049 * @param string $fixedunits If specified, uses fixed units (e.g. 'KB')
7050 * @return string Display version of size
7052 function display_size($size, int $decimalplaces = 1, string $fixedunits = ''): string {
7054 static $units;
7056 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
7057 return get_string('unlimited');
7060 if (empty($units)) {
7061 $units[] = get_string('sizeb');
7062 $units[] = get_string('sizekb');
7063 $units[] = get_string('sizemb');
7064 $units[] = get_string('sizegb');
7065 $units[] = get_string('sizetb');
7066 $units[] = get_string('sizepb');
7069 switch ($fixedunits) {
7070 case 'PB' :
7071 $magnitude = 5;
7072 break;
7073 case 'TB' :
7074 $magnitude = 4;
7075 break;
7076 case 'GB' :
7077 $magnitude = 3;
7078 break;
7079 case 'MB' :
7080 $magnitude = 2;
7081 break;
7082 case 'KB' :
7083 $magnitude = 1;
7084 break;
7085 case 'B' :
7086 $magnitude = 0;
7087 break;
7088 case '':
7089 $magnitude = floor(log($size, 1024));
7090 $magnitude = max(0, min(5, $magnitude));
7091 break;
7092 default:
7093 throw new coding_exception('Unknown fixed units value: ' . $fixedunits);
7096 // Special case for magnitude 0 (bytes) - never use decimal places.
7097 $nbsp = "\xc2\xa0";
7098 if ($magnitude === 0) {
7099 return round($size) . $nbsp . $units[$magnitude];
7102 // Convert to specified units.
7103 $sizeinunit = $size / 1024 ** $magnitude;
7105 // Fixed decimal places.
7106 return sprintf('%.' . $decimalplaces . 'f', $sizeinunit) . $nbsp . $units[$magnitude];
7110 * Cleans a given filename by removing suspicious or troublesome characters
7112 * @see clean_param()
7113 * @param string $string file name
7114 * @return string cleaned file name
7116 function clean_filename($string) {
7117 return clean_param($string, PARAM_FILE);
7120 // STRING TRANSLATION.
7123 * Returns the code for the current language
7125 * @category string
7126 * @return string
7128 function current_language() {
7129 global $CFG, $PAGE, $SESSION, $USER;
7131 if (!empty($SESSION->forcelang)) {
7132 // Allows overriding course-forced language (useful for admins to check
7133 // issues in courses whose language they don't understand).
7134 // Also used by some code to temporarily get language-related information in a
7135 // specific language (see force_current_language()).
7136 $return = $SESSION->forcelang;
7138 } else if (!empty($PAGE->cm->lang)) {
7139 // Activity language, if set.
7140 $return = $PAGE->cm->lang;
7142 } else if (!empty($PAGE->course->id) && $PAGE->course->id != SITEID && !empty($PAGE->course->lang)) {
7143 // Course language can override all other settings for this page.
7144 $return = $PAGE->course->lang;
7146 } else if (!empty($SESSION->lang)) {
7147 // Session language can override other settings.
7148 $return = $SESSION->lang;
7150 } else if (!empty($USER->lang)) {
7151 $return = $USER->lang;
7153 } else if (isset($CFG->lang)) {
7154 $return = $CFG->lang;
7156 } else {
7157 $return = 'en';
7160 // Just in case this slipped in from somewhere by accident.
7161 $return = str_replace('_utf8', '', $return);
7163 return $return;
7167 * Fix the current language to the given language code.
7169 * @param string $lang The language code to use.
7170 * @return void
7172 function fix_current_language(string $lang): void {
7173 global $CFG, $COURSE, $SESSION, $USER;
7175 if (!get_string_manager()->translation_exists($lang)) {
7176 throw new coding_exception("The language pack for $lang is not available");
7179 $fixglobal = '';
7180 $fixlang = 'lang';
7181 if (!empty($SESSION->forcelang)) {
7182 $fixglobal = $SESSION;
7183 $fixlang = 'forcelang';
7184 } else if (!empty($COURSE->id) && $COURSE->id != SITEID && !empty($COURSE->lang)) {
7185 $fixglobal = $COURSE;
7186 } else if (!empty($SESSION->lang)) {
7187 $fixglobal = $SESSION;
7188 } else if (!empty($USER->lang)) {
7189 $fixglobal = $USER;
7190 } else if (isset($CFG->lang)) {
7191 set_config('lang', $lang);
7194 if ($fixglobal) {
7195 $fixglobal->$fixlang = $lang;
7200 * Returns parent language of current active language if defined
7202 * @category string
7203 * @param string $lang null means current language
7204 * @return string
7206 function get_parent_language($lang=null) {
7208 $parentlang = get_string_manager()->get_string('parentlanguage', 'langconfig', null, $lang);
7210 if ($parentlang === 'en') {
7211 $parentlang = '';
7214 return $parentlang;
7218 * Force the current language to get strings and dates localised in the given language.
7220 * After calling this function, all strings will be provided in the given language
7221 * until this function is called again, or equivalent code is run.
7223 * @param string $language
7224 * @return string previous $SESSION->forcelang value
7226 function force_current_language($language) {
7227 global $SESSION;
7228 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
7229 if ($language !== $sessionforcelang) {
7230 // Setting forcelang to null or an empty string disables its effect.
7231 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
7232 $SESSION->forcelang = $language;
7233 moodle_setlocale();
7236 return $sessionforcelang;
7240 * Returns current string_manager instance.
7242 * The param $forcereload is needed for CLI installer only where the string_manager instance
7243 * must be replaced during the install.php script life time.
7245 * @category string
7246 * @param bool $forcereload shall the singleton be released and new instance created instead?
7247 * @return core_string_manager
7249 function get_string_manager($forcereload=false) {
7250 global $CFG;
7252 static $singleton = null;
7254 if ($forcereload) {
7255 $singleton = null;
7257 if ($singleton === null) {
7258 if (empty($CFG->early_install_lang)) {
7260 $transaliases = array();
7261 if (empty($CFG->langlist)) {
7262 $translist = array();
7263 } else {
7264 $translist = explode(',', $CFG->langlist);
7265 $translist = array_map('trim', $translist);
7266 // Each language in the $CFG->langlist can has an "alias" that would substitute the default language name.
7267 foreach ($translist as $i => $value) {
7268 $parts = preg_split('/\s*\|\s*/', $value, 2);
7269 if (count($parts) == 2) {
7270 $transaliases[$parts[0]] = $parts[1];
7271 $translist[$i] = $parts[0];
7276 if (!empty($CFG->config_php_settings['customstringmanager'])) {
7277 $classname = $CFG->config_php_settings['customstringmanager'];
7279 if (class_exists($classname)) {
7280 $implements = class_implements($classname);
7282 if (isset($implements['core_string_manager'])) {
7283 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7284 return $singleton;
7286 } else {
7287 debugging('Unable to instantiate custom string manager: class '.$classname.
7288 ' does not implement the core_string_manager interface.');
7291 } else {
7292 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7296 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7298 } else {
7299 $singleton = new core_string_manager_install();
7303 return $singleton;
7307 * Returns a localized string.
7309 * Returns the translated string specified by $identifier as
7310 * for $module. Uses the same format files as STphp.
7311 * $a is an object, string or number that can be used
7312 * within translation strings
7314 * eg 'hello {$a->firstname} {$a->lastname}'
7315 * or 'hello {$a}'
7317 * If you would like to directly echo the localized string use
7318 * the function {@link print_string()}
7320 * Example usage of this function involves finding the string you would
7321 * like a local equivalent of and using its identifier and module information
7322 * to retrieve it.<br/>
7323 * If you open moodle/lang/en/moodle.php and look near line 278
7324 * you will find a string to prompt a user for their word for 'course'
7325 * <code>
7326 * $string['course'] = 'Course';
7327 * </code>
7328 * So if you want to display the string 'Course'
7329 * in any language that supports it on your site
7330 * you just need to use the identifier 'course'
7331 * <code>
7332 * $mystring = '<strong>'. get_string('course') .'</strong>';
7333 * or
7334 * </code>
7335 * If the string you want is in another file you'd take a slightly
7336 * different approach. Looking in moodle/lang/en/calendar.php you find
7337 * around line 75:
7338 * <code>
7339 * $string['typecourse'] = 'Course event';
7340 * </code>
7341 * If you want to display the string "Course event" in any language
7342 * supported you would use the identifier 'typecourse' and the module 'calendar'
7343 * (because it is in the file calendar.php):
7344 * <code>
7345 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7346 * </code>
7348 * As a last resort, should the identifier fail to map to a string
7349 * the returned string will be [[ $identifier ]]
7351 * In Moodle 2.3 there is a new argument to this function $lazyload.
7352 * Setting $lazyload to true causes get_string to return a lang_string object
7353 * rather than the string itself. The fetching of the string is then put off until
7354 * the string object is first used. The object can be used by calling it's out
7355 * method or by casting the object to a string, either directly e.g.
7356 * (string)$stringobject
7357 * or indirectly by using the string within another string or echoing it out e.g.
7358 * echo $stringobject
7359 * return "<p>{$stringobject}</p>";
7360 * It is worth noting that using $lazyload and attempting to use the string as an
7361 * array key will cause a fatal error as objects cannot be used as array keys.
7362 * But you should never do that anyway!
7363 * For more information {@link lang_string}
7365 * @category string
7366 * @param string $identifier The key identifier for the localized string
7367 * @param string $component The module where the key identifier is stored,
7368 * usually expressed as the filename in the language pack without the
7369 * .php on the end but can also be written as mod/forum or grade/export/xls.
7370 * If none is specified then moodle.php is used.
7371 * @param string|object|array $a An object, string or number that can be used
7372 * within translation strings
7373 * @param bool $lazyload If set to true a string object is returned instead of
7374 * the string itself. The string then isn't calculated until it is first used.
7375 * @return string The localized string.
7376 * @throws coding_exception
7378 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7379 global $CFG;
7381 // If the lazy load argument has been supplied return a lang_string object
7382 // instead.
7383 // We need to make sure it is true (and a bool) as you will see below there
7384 // used to be a forth argument at one point.
7385 if ($lazyload === true) {
7386 return new lang_string($identifier, $component, $a);
7389 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7390 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7393 // There is now a forth argument again, this time it is a boolean however so
7394 // we can still check for the old extralocations parameter.
7395 if (!is_bool($lazyload) && !empty($lazyload)) {
7396 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7399 if (strpos((string)$component, '/') !== false) {
7400 debugging('The module name you passed to get_string is the deprecated format ' .
7401 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7402 $componentpath = explode('/', $component);
7404 switch ($componentpath[0]) {
7405 case 'mod':
7406 $component = $componentpath[1];
7407 break;
7408 case 'blocks':
7409 case 'block':
7410 $component = 'block_'.$componentpath[1];
7411 break;
7412 case 'enrol':
7413 $component = 'enrol_'.$componentpath[1];
7414 break;
7415 case 'format':
7416 $component = 'format_'.$componentpath[1];
7417 break;
7418 case 'grade':
7419 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7420 break;
7424 $result = get_string_manager()->get_string($identifier, $component, $a);
7426 // Debugging feature lets you display string identifier and component.
7427 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7428 $result .= ' {' . $identifier . '/' . $component . '}';
7430 return $result;
7434 * Converts an array of strings to their localized value.
7436 * @param array $array An array of strings
7437 * @param string $component The language module that these strings can be found in.
7438 * @return stdClass translated strings.
7440 function get_strings($array, $component = '') {
7441 $string = new stdClass;
7442 foreach ($array as $item) {
7443 $string->$item = get_string($item, $component);
7445 return $string;
7449 * Prints out a translated string.
7451 * Prints out a translated string using the return value from the {@link get_string()} function.
7453 * Example usage of this function when the string is in the moodle.php file:<br/>
7454 * <code>
7455 * echo '<strong>';
7456 * print_string('course');
7457 * echo '</strong>';
7458 * </code>
7460 * Example usage of this function when the string is not in the moodle.php file:<br/>
7461 * <code>
7462 * echo '<h1>';
7463 * print_string('typecourse', 'calendar');
7464 * echo '</h1>';
7465 * </code>
7467 * @category string
7468 * @param string $identifier The key identifier for the localized string
7469 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7470 * @param string|object|array $a An object, string or number that can be used within translation strings
7472 function print_string($identifier, $component = '', $a = null) {
7473 echo get_string($identifier, $component, $a);
7477 * Returns a list of charset codes
7479 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7480 * (checking that such charset is supported by the texlib library!)
7482 * @return array And associative array with contents in the form of charset => charset
7484 function get_list_of_charsets() {
7486 $charsets = array(
7487 'EUC-JP' => 'EUC-JP',
7488 'ISO-2022-JP'=> 'ISO-2022-JP',
7489 'ISO-8859-1' => 'ISO-8859-1',
7490 'SHIFT-JIS' => 'SHIFT-JIS',
7491 'GB2312' => 'GB2312',
7492 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7493 'UTF-8' => 'UTF-8');
7495 asort($charsets);
7497 return $charsets;
7501 * Returns a list of valid and compatible themes
7503 * @return array
7505 function get_list_of_themes() {
7506 global $CFG;
7508 $themes = array();
7510 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7511 $themelist = explode(',', $CFG->themelist);
7512 } else {
7513 $themelist = array_keys(core_component::get_plugin_list("theme"));
7516 foreach ($themelist as $key => $themename) {
7517 $theme = theme_config::load($themename);
7518 $themes[$themename] = $theme;
7521 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7523 return $themes;
7527 * Factory function for emoticon_manager
7529 * @return emoticon_manager singleton
7531 function get_emoticon_manager() {
7532 static $singleton = null;
7534 if (is_null($singleton)) {
7535 $singleton = new emoticon_manager();
7538 return $singleton;
7542 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7544 * Whenever this manager mentiones 'emoticon object', the following data
7545 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7546 * altidentifier and altcomponent
7548 * @see admin_setting_emoticons
7550 * @copyright 2010 David Mudrak
7551 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7553 class emoticon_manager {
7556 * Returns the currently enabled emoticons
7558 * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
7559 * @return array of emoticon objects
7561 public function get_emoticons($selectable = false) {
7562 global $CFG;
7563 $notselectable = ['martin', 'egg'];
7565 if (empty($CFG->emoticons)) {
7566 return array();
7569 $emoticons = $this->decode_stored_config($CFG->emoticons);
7571 if (!is_array($emoticons)) {
7572 // Something is wrong with the format of stored setting.
7573 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7574 return array();
7576 if ($selectable) {
7577 foreach ($emoticons as $index => $emote) {
7578 if (in_array($emote->altidentifier, $notselectable)) {
7579 // Skip this one.
7580 unset($emoticons[$index]);
7585 return $emoticons;
7589 * Converts emoticon object into renderable pix_emoticon object
7591 * @param stdClass $emoticon emoticon object
7592 * @param array $attributes explicit HTML attributes to set
7593 * @return pix_emoticon
7595 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7596 $stringmanager = get_string_manager();
7597 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7598 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7599 } else {
7600 $alt = s($emoticon->text);
7602 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7606 * Encodes the array of emoticon objects into a string storable in config table
7608 * @see self::decode_stored_config()
7609 * @param array $emoticons array of emtocion objects
7610 * @return string
7612 public function encode_stored_config(array $emoticons) {
7613 return json_encode($emoticons);
7617 * Decodes the string into an array of emoticon objects
7619 * @see self::encode_stored_config()
7620 * @param string $encoded
7621 * @return string|null
7623 public function decode_stored_config($encoded) {
7624 $decoded = json_decode($encoded);
7625 if (!is_array($decoded)) {
7626 return null;
7628 return $decoded;
7632 * Returns default set of emoticons supported by Moodle
7634 * @return array of sdtClasses
7636 public function default_emoticons() {
7637 return array(
7638 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7639 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7640 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7641 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7642 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7643 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7644 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7645 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7646 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7647 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7648 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7649 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7650 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7651 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7652 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7653 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7654 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7655 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7656 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7657 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7658 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7659 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7660 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7661 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7662 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7663 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7664 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7665 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7666 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7667 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7672 * Helper method preparing the stdClass with the emoticon properties
7674 * @param string|array $text or array of strings
7675 * @param string $imagename to be used by {@link pix_emoticon}
7676 * @param string $altidentifier alternative string identifier, null for no alt
7677 * @param string $altcomponent where the alternative string is defined
7678 * @param string $imagecomponent to be used by {@link pix_emoticon}
7679 * @return stdClass
7681 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7682 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7683 return (object)array(
7684 'text' => $text,
7685 'imagename' => $imagename,
7686 'imagecomponent' => $imagecomponent,
7687 'altidentifier' => $altidentifier,
7688 'altcomponent' => $altcomponent,
7693 // ENCRYPTION.
7696 * rc4encrypt
7698 * @param string $data Data to encrypt.
7699 * @return string The now encrypted data.
7701 function rc4encrypt($data) {
7702 return endecrypt(get_site_identifier(), $data, '');
7706 * rc4decrypt
7708 * @param string $data Data to decrypt.
7709 * @return string The now decrypted data.
7711 function rc4decrypt($data) {
7712 return endecrypt(get_site_identifier(), $data, 'de');
7716 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7718 * @todo Finish documenting this function
7720 * @param string $pwd The password to use when encrypting or decrypting
7721 * @param string $data The data to be decrypted/encrypted
7722 * @param string $case Either 'de' for decrypt or '' for encrypt
7723 * @return string
7725 function endecrypt ($pwd, $data, $case) {
7727 if ($case == 'de') {
7728 $data = urldecode($data);
7731 $key[] = '';
7732 $box[] = '';
7733 $pwdlength = strlen($pwd);
7735 for ($i = 0; $i <= 255; $i++) {
7736 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7737 $box[$i] = $i;
7740 $x = 0;
7742 for ($i = 0; $i <= 255; $i++) {
7743 $x = ($x + $box[$i] + $key[$i]) % 256;
7744 $tempswap = $box[$i];
7745 $box[$i] = $box[$x];
7746 $box[$x] = $tempswap;
7749 $cipher = '';
7751 $a = 0;
7752 $j = 0;
7754 for ($i = 0; $i < strlen($data); $i++) {
7755 $a = ($a + 1) % 256;
7756 $j = ($j + $box[$a]) % 256;
7757 $temp = $box[$a];
7758 $box[$a] = $box[$j];
7759 $box[$j] = $temp;
7760 $k = $box[(($box[$a] + $box[$j]) % 256)];
7761 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7762 $cipher .= chr($cipherby);
7765 if ($case == 'de') {
7766 $cipher = urldecode(urlencode($cipher));
7767 } else {
7768 $cipher = urlencode($cipher);
7771 return $cipher;
7774 // ENVIRONMENT CHECKING.
7777 * This method validates a plug name. It is much faster than calling clean_param.
7779 * @param string $name a string that might be a plugin name.
7780 * @return bool if this string is a valid plugin name.
7782 function is_valid_plugin_name($name) {
7783 // This does not work for 'mod', bad luck, use any other type.
7784 return core_component::is_valid_plugin_name('tool', $name);
7788 * Get a list of all the plugins of a given type that define a certain API function
7789 * in a certain file. The plugin component names and function names are returned.
7791 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7792 * @param string $function the part of the name of the function after the
7793 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7794 * names like report_courselist_hook.
7795 * @param string $file the name of file within the plugin that defines the
7796 * function. Defaults to lib.php.
7797 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7798 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7800 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7801 global $CFG;
7803 // We don't include here as all plugin types files would be included.
7804 $plugins = get_plugins_with_function($function, $file, false);
7806 if (empty($plugins[$plugintype])) {
7807 return array();
7810 $allplugins = core_component::get_plugin_list($plugintype);
7812 // Reformat the array and include the files.
7813 $pluginfunctions = array();
7814 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7816 // Check that it has not been removed and the file is still available.
7817 if (!empty($allplugins[$pluginname])) {
7819 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7820 if (file_exists($filepath)) {
7821 include_once($filepath);
7823 // Now that the file is loaded, we must verify the function still exists.
7824 if (function_exists($functionname)) {
7825 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7826 } else {
7827 // Invalidate the cache for next run.
7828 \cache_helper::invalidate_by_definition('core', 'plugin_functions');
7834 return $pluginfunctions;
7838 * Get a list of all the plugins that define a certain API function in a certain file.
7840 * @param string $function the part of the name of the function after the
7841 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7842 * names like report_courselist_hook.
7843 * @param string $file the name of file within the plugin that defines the
7844 * function. Defaults to lib.php.
7845 * @param bool $include Whether to include the files that contain the functions or not.
7846 * @return array with [plugintype][plugin] = functionname
7848 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7849 global $CFG;
7851 if (during_initial_install() || isset($CFG->upgraderunning)) {
7852 // API functions _must not_ be called during an installation or upgrade.
7853 return [];
7856 $cache = \cache::make('core', 'plugin_functions');
7858 // Including both although I doubt that we will find two functions definitions with the same name.
7859 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7860 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7861 $pluginfunctions = $cache->get($key);
7862 $dirty = false;
7864 // Use the plugin manager to check that plugins are currently installed.
7865 $pluginmanager = \core_plugin_manager::instance();
7867 if ($pluginfunctions !== false) {
7869 // Checking that the files are still available.
7870 foreach ($pluginfunctions as $plugintype => $plugins) {
7872 $allplugins = \core_component::get_plugin_list($plugintype);
7873 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7874 foreach ($plugins as $plugin => $function) {
7875 if (!isset($installedplugins[$plugin])) {
7876 // Plugin code is still present on disk but it is not installed.
7877 $dirty = true;
7878 break 2;
7881 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7882 if (empty($allplugins[$plugin])) {
7883 $dirty = true;
7884 break 2;
7887 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7888 if ($include && $fileexists) {
7889 // Include the files if it was requested.
7890 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7891 } else if (!$fileexists) {
7892 // If the file is not available any more it should not be returned.
7893 $dirty = true;
7894 break 2;
7897 // Check if the function still exists in the file.
7898 if ($include && !function_exists($function)) {
7899 $dirty = true;
7900 break 2;
7905 // If the cache is dirty, we should fall through and let it rebuild.
7906 if (!$dirty) {
7907 return $pluginfunctions;
7911 $pluginfunctions = array();
7913 // To fill the cached. Also, everything should continue working with cache disabled.
7914 $plugintypes = \core_component::get_plugin_types();
7915 foreach ($plugintypes as $plugintype => $unused) {
7917 // We need to include files here.
7918 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7919 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7920 foreach ($pluginswithfile as $plugin => $notused) {
7922 if (!isset($installedplugins[$plugin])) {
7923 continue;
7926 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7928 $pluginfunction = false;
7929 if (function_exists($fullfunction)) {
7930 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7931 $pluginfunction = $fullfunction;
7933 } else if ($plugintype === 'mod') {
7934 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7935 $shortfunction = $plugin . '_' . $function;
7936 if (function_exists($shortfunction)) {
7937 $pluginfunction = $shortfunction;
7941 if ($pluginfunction) {
7942 if (empty($pluginfunctions[$plugintype])) {
7943 $pluginfunctions[$plugintype] = array();
7945 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7950 $cache->set($key, $pluginfunctions);
7952 return $pluginfunctions;
7957 * Lists plugin-like directories within specified directory
7959 * This function was originally used for standard Moodle plugins, please use
7960 * new core_component::get_plugin_list() now.
7962 * This function is used for general directory listing and backwards compatility.
7964 * @param string $directory relative directory from root
7965 * @param string $exclude dir name to exclude from the list (defaults to none)
7966 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7967 * @return array Sorted array of directory names found under the requested parameters
7969 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7970 global $CFG;
7972 $plugins = array();
7974 if (empty($basedir)) {
7975 $basedir = $CFG->dirroot .'/'. $directory;
7977 } else {
7978 $basedir = $basedir .'/'. $directory;
7981 if ($CFG->debugdeveloper and empty($exclude)) {
7982 // Make sure devs do not use this to list normal plugins,
7983 // this is intended for general directories that are not plugins!
7985 $subtypes = core_component::get_plugin_types();
7986 if (in_array($basedir, $subtypes)) {
7987 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7989 unset($subtypes);
7992 $ignorelist = array_flip(array_filter([
7993 'CVS',
7994 '_vti_cnf',
7995 'amd',
7996 'classes',
7997 'simpletest',
7998 'tests',
7999 'templates',
8000 'yui',
8001 $exclude,
8002 ]));
8004 if (file_exists($basedir) && filetype($basedir) == 'dir') {
8005 if (!$dirhandle = opendir($basedir)) {
8006 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
8007 return array();
8009 while (false !== ($dir = readdir($dirhandle))) {
8010 if (strpos($dir, '.') === 0) {
8011 // Ignore directories starting with .
8012 // These are treated as hidden directories.
8013 continue;
8015 if (array_key_exists($dir, $ignorelist)) {
8016 // This directory features on the ignore list.
8017 continue;
8019 if (filetype($basedir .'/'. $dir) != 'dir') {
8020 continue;
8022 $plugins[] = $dir;
8024 closedir($dirhandle);
8026 if ($plugins) {
8027 asort($plugins);
8029 return $plugins;
8033 * Invoke plugin's callback functions
8035 * @param string $type plugin type e.g. 'mod'
8036 * @param string $name plugin name
8037 * @param string $feature feature name
8038 * @param string $action feature's action
8039 * @param array $params parameters of callback function, should be an array
8040 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
8041 * @return mixed
8043 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
8045 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
8046 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
8050 * Invoke component's callback functions
8052 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
8053 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
8054 * @param array $params parameters of callback function
8055 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
8056 * @return mixed
8058 function component_callback($component, $function, array $params = array(), $default = null) {
8060 $functionname = component_callback_exists($component, $function);
8062 if ($params && (array_keys($params) !== range(0, count($params) - 1))) {
8063 // PHP 8 allows to have associative arrays in the call_user_func_array() parameters but
8064 // PHP 7 does not. Using associative arrays can result in different behavior in different PHP versions.
8065 // See https://php.watch/versions/8.0/named-parameters#named-params-call_user_func_array
8066 // This check can be removed when minimum PHP version for Moodle is raised to 8.
8067 debugging('Parameters array can not be an associative array while Moodle supports both PHP 7 and PHP 8.',
8068 DEBUG_DEVELOPER);
8069 $params = array_values($params);
8072 if ($functionname) {
8073 // Function exists, so just return function result.
8074 $ret = call_user_func_array($functionname, $params);
8075 if (is_null($ret)) {
8076 return $default;
8077 } else {
8078 return $ret;
8081 return $default;
8085 * Determine if a component callback exists and return the function name to call. Note that this
8086 * function will include the required library files so that the functioname returned can be
8087 * called directly.
8089 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
8090 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
8091 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
8092 * @throws coding_exception if invalid component specfied
8094 function component_callback_exists($component, $function) {
8095 global $CFG; // This is needed for the inclusions.
8097 $cleancomponent = clean_param($component, PARAM_COMPONENT);
8098 if (empty($cleancomponent)) {
8099 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8101 $component = $cleancomponent;
8103 list($type, $name) = core_component::normalize_component($component);
8104 $component = $type . '_' . $name;
8106 $oldfunction = $name.'_'.$function;
8107 $function = $component.'_'.$function;
8109 $dir = core_component::get_component_directory($component);
8110 if (empty($dir)) {
8111 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8114 // Load library and look for function.
8115 if (file_exists($dir.'/lib.php')) {
8116 require_once($dir.'/lib.php');
8119 if (!function_exists($function) and function_exists($oldfunction)) {
8120 if ($type !== 'mod' and $type !== 'core') {
8121 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
8123 $function = $oldfunction;
8126 if (function_exists($function)) {
8127 return $function;
8129 return false;
8133 * Call the specified callback method on the provided class.
8135 * If the callback returns null, then the default value is returned instead.
8136 * If the class does not exist, then the default value is returned.
8138 * @param string $classname The name of the class to call upon.
8139 * @param string $methodname The name of the staticically defined method on the class.
8140 * @param array $params The arguments to pass into the method.
8141 * @param mixed $default The default value.
8142 * @return mixed The return value.
8144 function component_class_callback($classname, $methodname, array $params, $default = null) {
8145 if (!class_exists($classname)) {
8146 return $default;
8149 if (!method_exists($classname, $methodname)) {
8150 return $default;
8153 $fullfunction = $classname . '::' . $methodname;
8154 $result = call_user_func_array($fullfunction, $params);
8156 if (null === $result) {
8157 return $default;
8158 } else {
8159 return $result;
8164 * Checks whether a plugin supports a specified feature.
8166 * @param string $type Plugin type e.g. 'mod'
8167 * @param string $name Plugin name e.g. 'forum'
8168 * @param string $feature Feature code (FEATURE_xx constant)
8169 * @param mixed $default default value if feature support unknown
8170 * @return mixed Feature result (false if not supported, null if feature is unknown,
8171 * otherwise usually true but may have other feature-specific value such as array)
8172 * @throws coding_exception
8174 function plugin_supports($type, $name, $feature, $default = null) {
8175 global $CFG;
8177 if ($type === 'mod' and $name === 'NEWMODULE') {
8178 // Somebody forgot to rename the module template.
8179 return false;
8182 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
8183 if (empty($component)) {
8184 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8187 $function = null;
8189 if ($type === 'mod') {
8190 // We need this special case because we support subplugins in modules,
8191 // otherwise it would end up in infinite loop.
8192 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8193 include_once("$CFG->dirroot/mod/$name/lib.php");
8194 $function = $component.'_supports';
8195 if (!function_exists($function)) {
8196 // Legacy non-frankenstyle function name.
8197 $function = $name.'_supports';
8201 } else {
8202 if (!$path = core_component::get_plugin_directory($type, $name)) {
8203 // Non existent plugin type.
8204 return false;
8206 if (file_exists("$path/lib.php")) {
8207 include_once("$path/lib.php");
8208 $function = $component.'_supports';
8212 if ($function and function_exists($function)) {
8213 $supports = $function($feature);
8214 if (is_null($supports)) {
8215 // Plugin does not know - use default.
8216 return $default;
8217 } else {
8218 return $supports;
8222 // Plugin does not care, so use default.
8223 return $default;
8227 * Returns true if the current version of PHP is greater that the specified one.
8229 * @todo Check PHP version being required here is it too low?
8231 * @param string $version The version of php being tested.
8232 * @return bool
8234 function check_php_version($version='5.2.4') {
8235 return (version_compare(phpversion(), $version) >= 0);
8239 * Determine if moodle installation requires update.
8241 * Checks version numbers of main code and all plugins to see
8242 * if there are any mismatches.
8244 * @return bool
8246 function moodle_needs_upgrading() {
8247 global $CFG;
8249 if (empty($CFG->version)) {
8250 return true;
8253 // There is no need to purge plugininfo caches here because
8254 // these caches are not used during upgrade and they are purged after
8255 // every upgrade.
8257 if (empty($CFG->allversionshash)) {
8258 return true;
8261 $hash = core_component::get_all_versions_hash();
8263 return ($hash !== $CFG->allversionshash);
8267 * Returns the major version of this site
8269 * Moodle version numbers consist of three numbers separated by a dot, for
8270 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
8271 * called major version. This function extracts the major version from either
8272 * $CFG->release (default) or eventually from the $release variable defined in
8273 * the main version.php.
8275 * @param bool $fromdisk should the version if source code files be used
8276 * @return string|false the major version like '2.3', false if could not be determined
8278 function moodle_major_version($fromdisk = false) {
8279 global $CFG;
8281 if ($fromdisk) {
8282 $release = null;
8283 require($CFG->dirroot.'/version.php');
8284 if (empty($release)) {
8285 return false;
8288 } else {
8289 if (empty($CFG->release)) {
8290 return false;
8292 $release = $CFG->release;
8295 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8296 return $matches[0];
8297 } else {
8298 return false;
8302 // MISCELLANEOUS.
8305 * Gets the system locale
8307 * @return string Retuns the current locale.
8309 function moodle_getlocale() {
8310 global $CFG;
8312 // Fetch the correct locale based on ostype.
8313 if ($CFG->ostype == 'WINDOWS') {
8314 $stringtofetch = 'localewin';
8315 } else {
8316 $stringtofetch = 'locale';
8319 if (!empty($CFG->locale)) { // Override locale for all language packs.
8320 return $CFG->locale;
8323 return get_string($stringtofetch, 'langconfig');
8327 * Sets the system locale
8329 * @category string
8330 * @param string $locale Can be used to force a locale
8332 function moodle_setlocale($locale='') {
8333 global $CFG;
8335 static $currentlocale = ''; // Last locale caching.
8337 $oldlocale = $currentlocale;
8339 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8340 if (!empty($locale)) {
8341 $currentlocale = $locale;
8342 } else {
8343 $currentlocale = moodle_getlocale();
8346 // Do nothing if locale already set up.
8347 if ($oldlocale == $currentlocale) {
8348 return;
8351 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8352 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8353 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8355 // Get current values.
8356 $monetary= setlocale (LC_MONETARY, 0);
8357 $numeric = setlocale (LC_NUMERIC, 0);
8358 $ctype = setlocale (LC_CTYPE, 0);
8359 if ($CFG->ostype != 'WINDOWS') {
8360 $messages= setlocale (LC_MESSAGES, 0);
8362 // Set locale to all.
8363 $result = setlocale (LC_ALL, $currentlocale);
8364 // If setting of locale fails try the other utf8 or utf-8 variant,
8365 // some operating systems support both (Debian), others just one (OSX).
8366 if ($result === false) {
8367 if (stripos($currentlocale, '.UTF-8') !== false) {
8368 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8369 setlocale (LC_ALL, $newlocale);
8370 } else if (stripos($currentlocale, '.UTF8') !== false) {
8371 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8372 setlocale (LC_ALL, $newlocale);
8375 // Set old values.
8376 setlocale (LC_MONETARY, $monetary);
8377 setlocale (LC_NUMERIC, $numeric);
8378 if ($CFG->ostype != 'WINDOWS') {
8379 setlocale (LC_MESSAGES, $messages);
8381 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8382 // To workaround a well-known PHP problem with Turkish letter Ii.
8383 setlocale (LC_CTYPE, $ctype);
8388 * Count words in a string.
8390 * Words are defined as things between whitespace.
8392 * @category string
8393 * @param string $string The text to be searched for words. May be HTML.
8394 * @return int The count of words in the specified string
8396 function count_words($string) {
8397 // Before stripping tags, add a space after the close tag of anything that is not obviously inline.
8398 // Also, br is a special case because it definitely delimits a word, but has no close tag.
8399 $string = preg_replace('~
8400 ( # Capture the tag we match.
8401 </ # Start of close tag.
8402 (?! # Do not match any of these specific close tag names.
8403 a> | b> | del> | em> | i> |
8404 ins> | s> | small> |
8405 strong> | sub> | sup> | u>
8407 \w+ # But, apart from those execptions, match any tag name.
8408 > # End of close tag.
8410 <br> | <br\s*/> # Special cases that are not close tags.
8412 ~x', '$1 ', $string); // Add a space after the close tag.
8413 // Now remove HTML tags.
8414 $string = strip_tags($string);
8415 // Decode HTML entities.
8416 $string = html_entity_decode($string, ENT_COMPAT);
8418 // Now, the word count is the number of blocks of characters separated
8419 // by any sort of space. That seems to be the definition used by all other systems.
8420 // To be precise about what is considered to separate words:
8421 // * Anything that Unicode considers a 'Separator'
8422 // * Anything that Unicode considers a 'Control character'
8423 // * An em- or en- dash.
8424 return count(preg_split('~[\p{Z}\p{Cc}—–]+~u', $string, -1, PREG_SPLIT_NO_EMPTY));
8428 * Count letters in a string.
8430 * Letters are defined as chars not in tags and different from whitespace.
8432 * @category string
8433 * @param string $string The text to be searched for letters. May be HTML.
8434 * @return int The count of letters in the specified text.
8436 function count_letters($string) {
8437 $string = strip_tags($string); // Tags are out now.
8438 $string = html_entity_decode($string, ENT_COMPAT);
8439 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8441 return core_text::strlen($string);
8445 * Generate and return a random string of the specified length.
8447 * @param int $length The length of the string to be created.
8448 * @return string
8450 function random_string($length=15) {
8451 $randombytes = random_bytes_emulate($length);
8452 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8453 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8454 $pool .= '0123456789';
8455 $poollen = strlen($pool);
8456 $string = '';
8457 for ($i = 0; $i < $length; $i++) {
8458 $rand = ord($randombytes[$i]);
8459 $string .= substr($pool, ($rand%($poollen)), 1);
8461 return $string;
8465 * Generate a complex random string (useful for md5 salts)
8467 * This function is based on the above {@link random_string()} however it uses a
8468 * larger pool of characters and generates a string between 24 and 32 characters
8470 * @param int $length Optional if set generates a string to exactly this length
8471 * @return string
8473 function complex_random_string($length=null) {
8474 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8475 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8476 $poollen = strlen($pool);
8477 if ($length===null) {
8478 $length = floor(rand(24, 32));
8480 $randombytes = random_bytes_emulate($length);
8481 $string = '';
8482 for ($i = 0; $i < $length; $i++) {
8483 $rand = ord($randombytes[$i]);
8484 $string .= $pool[($rand%$poollen)];
8486 return $string;
8490 * Try to generates cryptographically secure pseudo-random bytes.
8492 * Note this is achieved by fallbacking between:
8493 * - PHP 7 random_bytes().
8494 * - OpenSSL openssl_random_pseudo_bytes().
8495 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8497 * @param int $length requested length in bytes
8498 * @return string binary data
8500 function random_bytes_emulate($length) {
8501 global $CFG;
8502 if ($length <= 0) {
8503 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8504 return '';
8506 if (function_exists('random_bytes')) {
8507 // Use PHP 7 goodness.
8508 $hash = @random_bytes($length);
8509 if ($hash !== false) {
8510 return $hash;
8513 if (function_exists('openssl_random_pseudo_bytes')) {
8514 // If you have the openssl extension enabled.
8515 $hash = openssl_random_pseudo_bytes($length);
8516 if ($hash !== false) {
8517 return $hash;
8521 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8522 $staticdata = serialize($CFG) . serialize($_SERVER);
8523 $hash = '';
8524 do {
8525 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8526 } while (strlen($hash) < $length);
8528 return substr($hash, 0, $length);
8532 * Given some text (which may contain HTML) and an ideal length,
8533 * this function truncates the text neatly on a word boundary if possible
8535 * @category string
8536 * @param string $text text to be shortened
8537 * @param int $ideal ideal string length
8538 * @param boolean $exact if false, $text will not be cut mid-word
8539 * @param string $ending The string to append if the passed string is truncated
8540 * @return string $truncate shortened string
8542 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8543 // If the plain text is shorter than the maximum length, return the whole text.
8544 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8545 return $text;
8548 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8549 // and only tag in its 'line'.
8550 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8552 $totallength = core_text::strlen($ending);
8553 $truncate = '';
8555 // This array stores information about open and close tags and their position
8556 // in the truncated string. Each item in the array is an object with fields
8557 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8558 // (byte position in truncated text).
8559 $tagdetails = array();
8561 foreach ($lines as $linematchings) {
8562 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8563 if (!empty($linematchings[1])) {
8564 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8565 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8566 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8567 // Record closing tag.
8568 $tagdetails[] = (object) array(
8569 'open' => false,
8570 'tag' => core_text::strtolower($tagmatchings[1]),
8571 'pos' => core_text::strlen($truncate),
8574 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8575 // Record opening tag.
8576 $tagdetails[] = (object) array(
8577 'open' => true,
8578 'tag' => core_text::strtolower($tagmatchings[1]),
8579 'pos' => core_text::strlen($truncate),
8581 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8582 $tagdetails[] = (object) array(
8583 'open' => true,
8584 'tag' => core_text::strtolower('if'),
8585 'pos' => core_text::strlen($truncate),
8587 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8588 $tagdetails[] = (object) array(
8589 'open' => false,
8590 'tag' => core_text::strtolower('if'),
8591 'pos' => core_text::strlen($truncate),
8595 // Add html-tag to $truncate'd text.
8596 $truncate .= $linematchings[1];
8599 // Calculate the length of the plain text part of the line; handle entities as one character.
8600 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8601 if ($totallength + $contentlength > $ideal) {
8602 // The number of characters which are left.
8603 $left = $ideal - $totallength;
8604 $entitieslength = 0;
8605 // Search for html entities.
8606 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)) {
8607 // Calculate the real length of all entities in the legal range.
8608 foreach ($entities[0] as $entity) {
8609 if ($entity[1]+1-$entitieslength <= $left) {
8610 $left--;
8611 $entitieslength += core_text::strlen($entity[0]);
8612 } else {
8613 // No more characters left.
8614 break;
8618 $breakpos = $left + $entitieslength;
8620 // If the words shouldn't be cut in the middle...
8621 if (!$exact) {
8622 // Search the last occurence of a space.
8623 for (; $breakpos > 0; $breakpos--) {
8624 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8625 if ($char === '.' or $char === ' ') {
8626 $breakpos += 1;
8627 break;
8628 } else if (strlen($char) > 2) {
8629 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8630 $breakpos += 1;
8631 break;
8636 if ($breakpos == 0) {
8637 // This deals with the test_shorten_text_no_spaces case.
8638 $breakpos = $left + $entitieslength;
8639 } else if ($breakpos > $left + $entitieslength) {
8640 // This deals with the previous for loop breaking on the first char.
8641 $breakpos = $left + $entitieslength;
8644 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8645 // Maximum length is reached, so get off the loop.
8646 break;
8647 } else {
8648 $truncate .= $linematchings[2];
8649 $totallength += $contentlength;
8652 // If the maximum length is reached, get off the loop.
8653 if ($totallength >= $ideal) {
8654 break;
8658 // Add the defined ending to the text.
8659 $truncate .= $ending;
8661 // Now calculate the list of open html tags based on the truncate position.
8662 $opentags = array();
8663 foreach ($tagdetails as $taginfo) {
8664 if ($taginfo->open) {
8665 // Add tag to the beginning of $opentags list.
8666 array_unshift($opentags, $taginfo->tag);
8667 } else {
8668 // Can have multiple exact same open tags, close the last one.
8669 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8670 if ($pos !== false) {
8671 unset($opentags[$pos]);
8676 // Close all unclosed html-tags.
8677 foreach ($opentags as $tag) {
8678 if ($tag === 'if') {
8679 $truncate .= '<!--<![endif]-->';
8680 } else {
8681 $truncate .= '</' . $tag . '>';
8685 return $truncate;
8689 * Shortens a given filename by removing characters positioned after the ideal string length.
8690 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8691 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8693 * @param string $filename file name
8694 * @param int $length ideal string length
8695 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8696 * @return string $shortened shortened file name
8698 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8699 $shortened = $filename;
8700 // Extract a part of the filename if it's char size exceeds the ideal string length.
8701 if (core_text::strlen($filename) > $length) {
8702 // Exclude extension if present in filename.
8703 $mimetypes = get_mimetypes_array();
8704 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8705 if ($extension && !empty($mimetypes[$extension])) {
8706 $basename = pathinfo($filename, PATHINFO_FILENAME);
8707 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8708 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8709 $shortened .= '.' . $extension;
8710 } else {
8711 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8712 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8715 return $shortened;
8719 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8721 * @param array $path The paths to reduce the length.
8722 * @param int $length Ideal string length
8723 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8724 * @return array $result Shortened paths in array.
8726 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8727 $result = null;
8729 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8730 $carry[] = shorten_filename($singlepath, $length, $includehash);
8731 return $carry;
8732 }, []);
8734 return $result;
8738 * Given dates in seconds, how many weeks is the date from startdate
8739 * The first week is 1, the second 2 etc ...
8741 * @param int $startdate Timestamp for the start date
8742 * @param int $thedate Timestamp for the end date
8743 * @return string
8745 function getweek ($startdate, $thedate) {
8746 if ($thedate < $startdate) {
8747 return 0;
8750 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8754 * Returns a randomly generated password of length $maxlen. inspired by
8756 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8757 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8759 * @param int $maxlen The maximum size of the password being generated.
8760 * @return string
8762 function generate_password($maxlen=10) {
8763 global $CFG;
8765 if (empty($CFG->passwordpolicy)) {
8766 $fillers = PASSWORD_DIGITS;
8767 $wordlist = file($CFG->wordlist);
8768 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8769 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8770 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8771 $password = $word1 . $filler1 . $word2;
8772 } else {
8773 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8774 $digits = $CFG->minpassworddigits;
8775 $lower = $CFG->minpasswordlower;
8776 $upper = $CFG->minpasswordupper;
8777 $nonalphanum = $CFG->minpasswordnonalphanum;
8778 $total = $lower + $upper + $digits + $nonalphanum;
8779 // Var minlength should be the greater one of the two ( $minlen and $total ).
8780 $minlen = $minlen < $total ? $total : $minlen;
8781 // Var maxlen can never be smaller than minlen.
8782 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8783 $additional = $maxlen - $total;
8785 // Make sure we have enough characters to fulfill
8786 // complexity requirements.
8787 $passworddigits = PASSWORD_DIGITS;
8788 while ($digits > strlen($passworddigits)) {
8789 $passworddigits .= PASSWORD_DIGITS;
8791 $passwordlower = PASSWORD_LOWER;
8792 while ($lower > strlen($passwordlower)) {
8793 $passwordlower .= PASSWORD_LOWER;
8795 $passwordupper = PASSWORD_UPPER;
8796 while ($upper > strlen($passwordupper)) {
8797 $passwordupper .= PASSWORD_UPPER;
8799 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8800 while ($nonalphanum > strlen($passwordnonalphanum)) {
8801 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8804 // Now mix and shuffle it all.
8805 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8806 substr(str_shuffle ($passwordupper), 0, $upper) .
8807 substr(str_shuffle ($passworddigits), 0, $digits) .
8808 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8809 substr(str_shuffle ($passwordlower .
8810 $passwordupper .
8811 $passworddigits .
8812 $passwordnonalphanum), 0 , $additional));
8815 return substr ($password, 0, $maxlen);
8819 * Given a float, prints it nicely.
8820 * Localized floats must not be used in calculations!
8822 * The stripzeros feature is intended for making numbers look nicer in small
8823 * areas where it is not necessary to indicate the degree of accuracy by showing
8824 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8825 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8827 * @param float $float The float to print
8828 * @param int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision).
8829 * @param bool $localized use localized decimal separator
8830 * @param bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after
8831 * the decimal point are always striped if $decimalpoints is -1.
8832 * @return string locale float
8834 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8835 if (is_null($float)) {
8836 return '';
8838 if ($localized) {
8839 $separator = get_string('decsep', 'langconfig');
8840 } else {
8841 $separator = '.';
8843 if ($decimalpoints == -1) {
8844 // The following counts the number of decimals.
8845 // It is safe as both floatval() and round() functions have same behaviour when non-numeric values are provided.
8846 $floatval = floatval($float);
8847 for ($decimalpoints = 0; $floatval != round($float, $decimalpoints); $decimalpoints++);
8850 $result = number_format($float, $decimalpoints, $separator, '');
8851 if ($stripzeros && $decimalpoints > 0) {
8852 // Remove zeros and final dot if not needed.
8853 // However, only do this if there is a decimal point!
8854 $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
8856 return $result;
8860 * Converts locale specific floating point/comma number back to standard PHP float value
8861 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8863 * @param string $localefloat locale aware float representation
8864 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8865 * @return mixed float|bool - false or the parsed float.
8867 function unformat_float($localefloat, $strict = false) {
8868 $localefloat = trim((string)$localefloat);
8870 if ($localefloat == '') {
8871 return null;
8874 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8875 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8877 if ($strict && !is_numeric($localefloat)) {
8878 return false;
8881 return (float)$localefloat;
8885 * Given a simple array, this shuffles it up just like shuffle()
8886 * Unlike PHP's shuffle() this function works on any machine.
8888 * @param array $array The array to be rearranged
8889 * @return array
8891 function swapshuffle($array) {
8893 $last = count($array) - 1;
8894 for ($i = 0; $i <= $last; $i++) {
8895 $from = rand(0, $last);
8896 $curr = $array[$i];
8897 $array[$i] = $array[$from];
8898 $array[$from] = $curr;
8900 return $array;
8904 * Like {@link swapshuffle()}, but works on associative arrays
8906 * @param array $array The associative array to be rearranged
8907 * @return array
8909 function swapshuffle_assoc($array) {
8911 $newarray = array();
8912 $newkeys = swapshuffle(array_keys($array));
8914 foreach ($newkeys as $newkey) {
8915 $newarray[$newkey] = $array[$newkey];
8917 return $newarray;
8921 * Given an arbitrary array, and a number of draws,
8922 * this function returns an array with that amount
8923 * of items. The indexes are retained.
8925 * @todo Finish documenting this function
8927 * @param array $array
8928 * @param int $draws
8929 * @return array
8931 function draw_rand_array($array, $draws) {
8933 $return = array();
8935 $last = count($array);
8937 if ($draws > $last) {
8938 $draws = $last;
8941 while ($draws > 0) {
8942 $last--;
8944 $keys = array_keys($array);
8945 $rand = rand(0, $last);
8947 $return[$keys[$rand]] = $array[$keys[$rand]];
8948 unset($array[$keys[$rand]]);
8950 $draws--;
8953 return $return;
8957 * Calculate the difference between two microtimes
8959 * @param string $a The first Microtime
8960 * @param string $b The second Microtime
8961 * @return string
8963 function microtime_diff($a, $b) {
8964 list($adec, $asec) = explode(' ', $a);
8965 list($bdec, $bsec) = explode(' ', $b);
8966 return $bsec - $asec + $bdec - $adec;
8970 * Given a list (eg a,b,c,d,e) this function returns
8971 * an array of 1->a, 2->b, 3->c etc
8973 * @param string $list The string to explode into array bits
8974 * @param string $separator The separator used within the list string
8975 * @return array The now assembled array
8977 function make_menu_from_list($list, $separator=',') {
8979 $array = array_reverse(explode($separator, $list), true);
8980 foreach ($array as $key => $item) {
8981 $outarray[$key+1] = trim($item);
8983 return $outarray;
8987 * Creates an array that represents all the current grades that
8988 * can be chosen using the given grading type.
8990 * Negative numbers
8991 * are scales, zero is no grade, and positive numbers are maximum
8992 * grades.
8994 * @todo Finish documenting this function or better deprecated this completely!
8996 * @param int $gradingtype
8997 * @return array
8999 function make_grades_menu($gradingtype) {
9000 global $DB;
9002 $grades = array();
9003 if ($gradingtype < 0) {
9004 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
9005 return make_menu_from_list($scale->scale);
9007 } else if ($gradingtype > 0) {
9008 for ($i=$gradingtype; $i>=0; $i--) {
9009 $grades[$i] = $i .' / '. $gradingtype;
9011 return $grades;
9013 return $grades;
9017 * make_unique_id_code
9019 * @todo Finish documenting this function
9021 * @uses $_SERVER
9022 * @param string $extra Extra string to append to the end of the code
9023 * @return string
9025 function make_unique_id_code($extra = '') {
9027 $hostname = 'unknownhost';
9028 if (!empty($_SERVER['HTTP_HOST'])) {
9029 $hostname = $_SERVER['HTTP_HOST'];
9030 } else if (!empty($_ENV['HTTP_HOST'])) {
9031 $hostname = $_ENV['HTTP_HOST'];
9032 } else if (!empty($_SERVER['SERVER_NAME'])) {
9033 $hostname = $_SERVER['SERVER_NAME'];
9034 } else if (!empty($_ENV['SERVER_NAME'])) {
9035 $hostname = $_ENV['SERVER_NAME'];
9038 $date = gmdate("ymdHis");
9040 $random = random_string(6);
9042 if ($extra) {
9043 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
9044 } else {
9045 return $hostname .'+'. $date .'+'. $random;
9051 * Function to check the passed address is within the passed subnet
9053 * The parameter is a comma separated string of subnet definitions.
9054 * Subnet strings can be in one of three formats:
9055 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
9056 * 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)
9057 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
9058 * Code for type 1 modified from user posted comments by mediator at
9059 * {@link http://au.php.net/manual/en/function.ip2long.php}
9061 * @param string $addr The address you are checking
9062 * @param string $subnetstr The string of subnet addresses
9063 * @return bool
9065 function address_in_subnet($addr, $subnetstr) {
9067 if ($addr == '0.0.0.0') {
9068 return false;
9070 $subnets = explode(',', $subnetstr);
9071 $found = false;
9072 $addr = trim($addr);
9073 $addr = cleanremoteaddr($addr, false); // Normalise.
9074 if ($addr === null) {
9075 return false;
9077 $addrparts = explode(':', $addr);
9079 $ipv6 = strpos($addr, ':');
9081 foreach ($subnets as $subnet) {
9082 $subnet = trim($subnet);
9083 if ($subnet === '') {
9084 continue;
9087 if (strpos($subnet, '/') !== false) {
9088 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
9089 list($ip, $mask) = explode('/', $subnet);
9090 $mask = trim($mask);
9091 if (!is_number($mask)) {
9092 continue; // Incorect mask number, eh?
9094 $ip = cleanremoteaddr($ip, false); // Normalise.
9095 if ($ip === null) {
9096 continue;
9098 if (strpos($ip, ':') !== false) {
9099 // IPv6.
9100 if (!$ipv6) {
9101 continue;
9103 if ($mask > 128 or $mask < 0) {
9104 continue; // Nonsense.
9106 if ($mask == 0) {
9107 return true; // Any address.
9109 if ($mask == 128) {
9110 if ($ip === $addr) {
9111 return true;
9113 continue;
9115 $ipparts = explode(':', $ip);
9116 $modulo = $mask % 16;
9117 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
9118 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
9119 if (implode(':', $ipnet) === implode(':', $addrnet)) {
9120 if ($modulo == 0) {
9121 return true;
9123 $pos = ($mask-$modulo)/16;
9124 $ipnet = hexdec($ipparts[$pos]);
9125 $addrnet = hexdec($addrparts[$pos]);
9126 $mask = 0xffff << (16 - $modulo);
9127 if (($addrnet & $mask) == ($ipnet & $mask)) {
9128 return true;
9132 } else {
9133 // IPv4.
9134 if ($ipv6) {
9135 continue;
9137 if ($mask > 32 or $mask < 0) {
9138 continue; // Nonsense.
9140 if ($mask == 0) {
9141 return true;
9143 if ($mask == 32) {
9144 if ($ip === $addr) {
9145 return true;
9147 continue;
9149 $mask = 0xffffffff << (32 - $mask);
9150 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
9151 return true;
9155 } else if (strpos($subnet, '-') !== false) {
9156 // 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.
9157 $parts = explode('-', $subnet);
9158 if (count($parts) != 2) {
9159 continue;
9162 if (strpos($subnet, ':') !== false) {
9163 // IPv6.
9164 if (!$ipv6) {
9165 continue;
9167 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9168 if ($ipstart === null) {
9169 continue;
9171 $ipparts = explode(':', $ipstart);
9172 $start = hexdec(array_pop($ipparts));
9173 $ipparts[] = trim($parts[1]);
9174 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
9175 if ($ipend === null) {
9176 continue;
9178 $ipparts[7] = '';
9179 $ipnet = implode(':', $ipparts);
9180 if (strpos($addr, $ipnet) !== 0) {
9181 continue;
9183 $ipparts = explode(':', $ipend);
9184 $end = hexdec($ipparts[7]);
9186 $addrend = hexdec($addrparts[7]);
9188 if (($addrend >= $start) and ($addrend <= $end)) {
9189 return true;
9192 } else {
9193 // IPv4.
9194 if ($ipv6) {
9195 continue;
9197 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9198 if ($ipstart === null) {
9199 continue;
9201 $ipparts = explode('.', $ipstart);
9202 $ipparts[3] = trim($parts[1]);
9203 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
9204 if ($ipend === null) {
9205 continue;
9208 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9209 return true;
9213 } else {
9214 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9215 if (strpos($subnet, ':') !== false) {
9216 // IPv6.
9217 if (!$ipv6) {
9218 continue;
9220 $parts = explode(':', $subnet);
9221 $count = count($parts);
9222 if ($parts[$count-1] === '') {
9223 unset($parts[$count-1]); // Trim trailing :'s.
9224 $count--;
9225 $subnet = implode('.', $parts);
9227 $isip = cleanremoteaddr($subnet, false); // Normalise.
9228 if ($isip !== null) {
9229 if ($isip === $addr) {
9230 return true;
9232 continue;
9233 } else if ($count > 8) {
9234 continue;
9236 $zeros = array_fill(0, 8-$count, '0');
9237 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9238 if (address_in_subnet($addr, $subnet)) {
9239 return true;
9242 } else {
9243 // IPv4.
9244 if ($ipv6) {
9245 continue;
9247 $parts = explode('.', $subnet);
9248 $count = count($parts);
9249 if ($parts[$count-1] === '') {
9250 unset($parts[$count-1]); // Trim trailing .
9251 $count--;
9252 $subnet = implode('.', $parts);
9254 if ($count == 4) {
9255 $subnet = cleanremoteaddr($subnet, false); // Normalise.
9256 if ($subnet === $addr) {
9257 return true;
9259 continue;
9260 } else if ($count > 4) {
9261 continue;
9263 $zeros = array_fill(0, 4-$count, '0');
9264 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9265 if (address_in_subnet($addr, $subnet)) {
9266 return true;
9272 return false;
9276 * For outputting debugging info
9278 * @param string $string The string to write
9279 * @param string $eol The end of line char(s) to use
9280 * @param string $sleep Period to make the application sleep
9281 * This ensures any messages have time to display before redirect
9283 function mtrace($string, $eol="\n", $sleep=0) {
9284 global $CFG;
9286 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
9287 $fn = $CFG->mtrace_wrapper;
9288 $fn($string, $eol);
9289 return;
9290 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
9291 // We must explicitly call the add_line function here.
9292 // Uses of fwrite to STDOUT are not picked up by ob_start.
9293 if ($output = \core\task\logmanager::add_line("{$string}{$eol}")) {
9294 fwrite(STDOUT, $output);
9296 } else {
9297 echo $string . $eol;
9300 // Flush again.
9301 flush();
9303 // Delay to keep message on user's screen in case of subsequent redirect.
9304 if ($sleep) {
9305 sleep($sleep);
9310 * Replace 1 or more slashes or backslashes to 1 slash
9312 * @param string $path The path to strip
9313 * @return string the path with double slashes removed
9315 function cleardoubleslashes ($path) {
9316 return preg_replace('/(\/|\\\){1,}/', '/', $path);
9320 * Is the current ip in a given list?
9322 * @param string $list
9323 * @return bool
9325 function remoteip_in_list($list) {
9326 $clientip = getremoteaddr(null);
9328 if (!$clientip) {
9329 // Ensure access on cli.
9330 return true;
9332 return \core\ip_utils::is_ip_in_subnet_list($clientip, $list);
9336 * Returns most reliable client address
9338 * @param string $default If an address can't be determined, then return this
9339 * @return string The remote IP address
9341 function getremoteaddr($default='0.0.0.0') {
9342 global $CFG;
9344 if (!isset($CFG->getremoteaddrconf)) {
9345 // This will happen, for example, before just after the upgrade, as the
9346 // user is redirected to the admin screen.
9347 $variablestoskip = GETREMOTEADDR_SKIP_DEFAULT;
9348 } else {
9349 $variablestoskip = $CFG->getremoteaddrconf;
9351 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
9352 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9353 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9354 return $address ? $address : $default;
9357 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
9358 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9359 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9361 $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
9362 global $CFG;
9363 return !\core\ip_utils::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore ?? '', ',');
9366 // Multiple proxies can append values to this header including an
9367 // untrusted original request header so we must only trust the last ip.
9368 $address = end($forwardedaddresses);
9370 if (substr_count($address, ":") > 1) {
9371 // Remove port and brackets from IPv6.
9372 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9373 $address = $matches[1];
9375 } else {
9376 // Remove port from IPv4.
9377 if (substr_count($address, ":") == 1) {
9378 $parts = explode(":", $address);
9379 $address = $parts[0];
9383 $address = cleanremoteaddr($address);
9384 return $address ? $address : $default;
9387 if (!empty($_SERVER['REMOTE_ADDR'])) {
9388 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9389 return $address ? $address : $default;
9390 } else {
9391 return $default;
9396 * Cleans an ip address. Internal addresses are now allowed.
9397 * (Originally local addresses were not allowed.)
9399 * @param string $addr IPv4 or IPv6 address
9400 * @param bool $compress use IPv6 address compression
9401 * @return string normalised ip address string, null if error
9403 function cleanremoteaddr($addr, $compress=false) {
9404 $addr = trim($addr);
9406 if (strpos($addr, ':') !== false) {
9407 // Can be only IPv6.
9408 $parts = explode(':', $addr);
9409 $count = count($parts);
9411 if (strpos($parts[$count-1], '.') !== false) {
9412 // Legacy ipv4 notation.
9413 $last = array_pop($parts);
9414 $ipv4 = cleanremoteaddr($last, true);
9415 if ($ipv4 === null) {
9416 return null;
9418 $bits = explode('.', $ipv4);
9419 $parts[] = dechex($bits[0]).dechex($bits[1]);
9420 $parts[] = dechex($bits[2]).dechex($bits[3]);
9421 $count = count($parts);
9422 $addr = implode(':', $parts);
9425 if ($count < 3 or $count > 8) {
9426 return null; // Severly malformed.
9429 if ($count != 8) {
9430 if (strpos($addr, '::') === false) {
9431 return null; // Malformed.
9433 // Uncompress.
9434 $insertat = array_search('', $parts, true);
9435 $missing = array_fill(0, 1 + 8 - $count, '0');
9436 array_splice($parts, $insertat, 1, $missing);
9437 foreach ($parts as $key => $part) {
9438 if ($part === '') {
9439 $parts[$key] = '0';
9444 $adr = implode(':', $parts);
9445 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9446 return null; // Incorrect format - sorry.
9449 // Normalise 0s and case.
9450 $parts = array_map('hexdec', $parts);
9451 $parts = array_map('dechex', $parts);
9453 $result = implode(':', $parts);
9455 if (!$compress) {
9456 return $result;
9459 if ($result === '0:0:0:0:0:0:0:0') {
9460 return '::'; // All addresses.
9463 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9464 if ($compressed !== $result) {
9465 return $compressed;
9468 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9469 if ($compressed !== $result) {
9470 return $compressed;
9473 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9474 if ($compressed !== $result) {
9475 return $compressed;
9478 return $result;
9481 // First get all things that look like IPv4 addresses.
9482 $parts = array();
9483 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9484 return null;
9486 unset($parts[0]);
9488 foreach ($parts as $key => $match) {
9489 if ($match > 255) {
9490 return null;
9492 $parts[$key] = (int)$match; // Normalise 0s.
9495 return implode('.', $parts);
9500 * Is IP address a public address?
9502 * @param string $ip The ip to check
9503 * @return bool true if the ip is public
9505 function ip_is_public($ip) {
9506 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9510 * This function will make a complete copy of anything it's given,
9511 * regardless of whether it's an object or not.
9513 * @param mixed $thing Something you want cloned
9514 * @return mixed What ever it is you passed it
9516 function fullclone($thing) {
9517 return unserialize(serialize($thing));
9521 * Used to make sure that $min <= $value <= $max
9523 * Make sure that value is between min, and max
9525 * @param int $min The minimum value
9526 * @param int $value The value to check
9527 * @param int $max The maximum value
9528 * @return int
9530 function bounded_number($min, $value, $max) {
9531 if ($value < $min) {
9532 return $min;
9534 if ($value > $max) {
9535 return $max;
9537 return $value;
9541 * Check if there is a nested array within the passed array
9543 * @param array $array
9544 * @return bool true if there is a nested array false otherwise
9546 function array_is_nested($array) {
9547 foreach ($array as $value) {
9548 if (is_array($value)) {
9549 return true;
9552 return false;
9556 * get_performance_info() pairs up with init_performance_info()
9557 * loaded in setup.php. Returns an array with 'html' and 'txt'
9558 * values ready for use, and each of the individual stats provided
9559 * separately as well.
9561 * @return array
9563 function get_performance_info() {
9564 global $CFG, $PERF, $DB, $PAGE;
9566 $info = array();
9567 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9569 $info['html'] = '';
9570 if (!empty($CFG->themedesignermode)) {
9571 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9572 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9574 $info['html'] .= '<ul class="list-unstyled row mx-md-0">'; // Holds userfriendly HTML representation.
9576 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9578 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9579 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9581 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9582 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9584 if (function_exists('memory_get_usage')) {
9585 $info['memory_total'] = memory_get_usage();
9586 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9587 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9588 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9589 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9592 if (function_exists('memory_get_peak_usage')) {
9593 $info['memory_peak'] = memory_get_peak_usage();
9594 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9595 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9598 $info['html'] .= '</ul><ul class="list-unstyled row mx-md-0">';
9599 $inc = get_included_files();
9600 $info['includecount'] = count($inc);
9601 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9602 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9604 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9605 // We can not track more performance before installation or before PAGE init, sorry.
9606 return $info;
9609 $filtermanager = filter_manager::instance();
9610 if (method_exists($filtermanager, 'get_performance_summary')) {
9611 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9612 $info = array_merge($filterinfo, $info);
9613 foreach ($filterinfo as $key => $value) {
9614 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9615 $info['txt'] .= "$key: $value ";
9619 $stringmanager = get_string_manager();
9620 if (method_exists($stringmanager, 'get_performance_summary')) {
9621 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9622 $info = array_merge($filterinfo, $info);
9623 foreach ($filterinfo as $key => $value) {
9624 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9625 $info['txt'] .= "$key: $value ";
9629 if (!empty($PERF->logwrites)) {
9630 $info['logwrites'] = $PERF->logwrites;
9631 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9632 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9635 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9636 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9637 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9639 if ($DB->want_read_slave()) {
9640 $info['dbreads_slave'] = $DB->perf_get_reads_slave();
9641 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads from slave: '.$info['dbreads_slave'].'</li> ';
9642 $info['txt'] .= 'db reads from slave: '.$info['dbreads_slave'].' ';
9645 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9646 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9647 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9649 if (function_exists('posix_times')) {
9650 $ptimes = posix_times();
9651 if (is_array($ptimes)) {
9652 foreach ($ptimes as $key => $val) {
9653 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9655 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9656 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9657 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9661 // Grab the load average for the last minute.
9662 // /proc will only work under some linux configurations
9663 // while uptime is there under MacOSX/Darwin and other unices.
9664 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9665 list($serverload) = explode(' ', $loadavg[0]);
9666 unset($loadavg);
9667 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9668 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9669 $serverload = $matches[1];
9670 } else {
9671 trigger_error('Could not parse uptime output!');
9674 if (!empty($serverload)) {
9675 $info['serverload'] = $serverload;
9676 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9677 $info['txt'] .= "serverload: {$info['serverload']} ";
9680 // Display size of session if session started.
9681 if ($si = \core\session\manager::get_performance_info()) {
9682 $info['sessionsize'] = $si['size'];
9683 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9684 $info['txt'] .= $si['txt'];
9687 // Display time waiting for session if applicable.
9688 if (!empty($PERF->sessionlock['wait'])) {
9689 $sessionwait = number_format($PERF->sessionlock['wait'], 3) . ' secs';
9690 $info['html'] .= html_writer::tag('li', 'Session wait: ' . $sessionwait, [
9691 'class' => 'sessionwait col-sm-4'
9693 $info['txt'] .= 'sessionwait: ' . $sessionwait . ' ';
9696 $info['html'] .= '</ul>';
9697 $html = '';
9698 if ($stats = cache_helper::get_stats()) {
9700 $table = new html_table();
9701 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9702 $table->head = ['Mode', 'Cache item', 'Static', 'H', 'M', get_string('mappingprimary', 'cache'), 'H', 'M', 'S', 'I/O'];
9703 $table->data = [];
9704 $table->align = ['left', 'left', 'left', 'right', 'right', 'left', 'right', 'right', 'right', 'right'];
9706 $text = 'Caches used (hits/misses/sets): ';
9707 $hits = 0;
9708 $misses = 0;
9709 $sets = 0;
9710 $maxstores = 0;
9712 // We want to align static caches into their own column.
9713 $hasstatic = false;
9714 foreach ($stats as $definition => $details) {
9715 $numstores = count($details['stores']);
9716 $first = key($details['stores']);
9717 if ($first !== cache_store::STATIC_ACCEL) {
9718 $numstores++; // Add a blank space for the missing static store.
9720 $maxstores = max($maxstores, $numstores);
9723 $storec = 0;
9725 while ($storec++ < ($maxstores - 2)) {
9726 if ($storec == ($maxstores - 2)) {
9727 $table->head[] = get_string('mappingfinal', 'cache');
9728 } else {
9729 $table->head[] = "Store $storec";
9731 $table->align[] = 'left';
9732 $table->align[] = 'right';
9733 $table->align[] = 'right';
9734 $table->align[] = 'right';
9735 $table->align[] = 'right';
9736 $table->head[] = 'H';
9737 $table->head[] = 'M';
9738 $table->head[] = 'S';
9739 $table->head[] = 'I/O';
9742 ksort($stats);
9744 foreach ($stats as $definition => $details) {
9745 switch ($details['mode']) {
9746 case cache_store::MODE_APPLICATION:
9747 $modeclass = 'application';
9748 $mode = ' <span title="application cache">App</span>';
9749 break;
9750 case cache_store::MODE_SESSION:
9751 $modeclass = 'session';
9752 $mode = ' <span title="session cache">Ses</span>';
9753 break;
9754 case cache_store::MODE_REQUEST:
9755 $modeclass = 'request';
9756 $mode = ' <span title="request cache">Req</span>';
9757 break;
9759 $row = [$mode, $definition];
9761 $text .= "$definition {";
9763 $storec = 0;
9764 foreach ($details['stores'] as $store => $data) {
9766 if ($storec == 0 && $store !== cache_store::STATIC_ACCEL) {
9767 $row[] = '';
9768 $row[] = '';
9769 $row[] = '';
9770 $storec++;
9773 $hits += $data['hits'];
9774 $misses += $data['misses'];
9775 $sets += $data['sets'];
9776 if ($data['hits'] == 0 and $data['misses'] > 0) {
9777 $cachestoreclass = 'nohits bg-danger';
9778 } else if ($data['hits'] < $data['misses']) {
9779 $cachestoreclass = 'lowhits bg-warning text-dark';
9780 } else {
9781 $cachestoreclass = 'hihits';
9783 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9784 $cell = new html_table_cell($store);
9785 $cell->attributes = ['class' => $cachestoreclass];
9786 $row[] = $cell;
9787 $cell = new html_table_cell($data['hits']);
9788 $cell->attributes = ['class' => $cachestoreclass];
9789 $row[] = $cell;
9790 $cell = new html_table_cell($data['misses']);
9791 $cell->attributes = ['class' => $cachestoreclass];
9792 $row[] = $cell;
9794 if ($store !== cache_store::STATIC_ACCEL) {
9795 // The static cache is never set.
9796 $cell = new html_table_cell($data['sets']);
9797 $cell->attributes = ['class' => $cachestoreclass];
9798 $row[] = $cell;
9800 if ($data['hits'] || $data['sets']) {
9801 if ($data['iobytes'] === cache_store::IO_BYTES_NOT_SUPPORTED) {
9802 $size = '-';
9803 } else {
9804 $size = display_size($data['iobytes'], 1, 'KB');
9805 if ($data['iobytes'] >= 10 * 1024) {
9806 $cachestoreclass = ' bg-warning text-dark';
9809 } else {
9810 $size = '';
9812 $cell = new html_table_cell($size);
9813 $cell->attributes = ['class' => $cachestoreclass];
9814 $row[] = $cell;
9816 $storec++;
9818 while ($storec++ < $maxstores) {
9819 $row[] = '';
9820 $row[] = '';
9821 $row[] = '';
9822 $row[] = '';
9823 $row[] = '';
9825 $text .= '} ';
9827 $table->data[] = $row;
9830 $html .= html_writer::table($table);
9832 // Now lets also show sub totals for each cache store.
9833 $storetotals = [];
9834 $storetotal = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9835 foreach ($stats as $definition => $details) {
9836 foreach ($details['stores'] as $store => $data) {
9837 if (!array_key_exists($store, $storetotals)) {
9838 $storetotals[$store] = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9840 $storetotals[$store]['class'] = $data['class'];
9841 $storetotals[$store]['hits'] += $data['hits'];
9842 $storetotals[$store]['misses'] += $data['misses'];
9843 $storetotals[$store]['sets'] += $data['sets'];
9844 $storetotal['hits'] += $data['hits'];
9845 $storetotal['misses'] += $data['misses'];
9846 $storetotal['sets'] += $data['sets'];
9847 if ($data['iobytes'] !== cache_store::IO_BYTES_NOT_SUPPORTED) {
9848 $storetotals[$store]['iobytes'] += $data['iobytes'];
9849 $storetotal['iobytes'] += $data['iobytes'];
9854 $table = new html_table();
9855 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9856 $table->head = [get_string('storename', 'cache'), get_string('type_cachestore', 'plugin'), 'H', 'M', 'S', 'I/O'];
9857 $table->data = [];
9858 $table->align = ['left', 'left', 'right', 'right', 'right', 'right'];
9860 ksort($storetotals);
9862 foreach ($storetotals as $store => $data) {
9863 $row = [];
9864 if ($data['hits'] == 0 and $data['misses'] > 0) {
9865 $cachestoreclass = 'nohits bg-danger';
9866 } else if ($data['hits'] < $data['misses']) {
9867 $cachestoreclass = 'lowhits bg-warning text-dark';
9868 } else {
9869 $cachestoreclass = 'hihits';
9871 $cell = new html_table_cell($store);
9872 $cell->attributes = ['class' => $cachestoreclass];
9873 $row[] = $cell;
9874 $cell = new html_table_cell($data['class']);
9875 $cell->attributes = ['class' => $cachestoreclass];
9876 $row[] = $cell;
9877 $cell = new html_table_cell($data['hits']);
9878 $cell->attributes = ['class' => $cachestoreclass];
9879 $row[] = $cell;
9880 $cell = new html_table_cell($data['misses']);
9881 $cell->attributes = ['class' => $cachestoreclass];
9882 $row[] = $cell;
9883 $cell = new html_table_cell($data['sets']);
9884 $cell->attributes = ['class' => $cachestoreclass];
9885 $row[] = $cell;
9886 if ($data['hits'] || $data['sets']) {
9887 if ($data['iobytes']) {
9888 $size = display_size($data['iobytes'], 1, 'KB');
9889 } else {
9890 $size = '-';
9892 } else {
9893 $size = '';
9895 $cell = new html_table_cell($size);
9896 $cell->attributes = ['class' => $cachestoreclass];
9897 $row[] = $cell;
9898 $table->data[] = $row;
9900 if (!empty($storetotal['iobytes'])) {
9901 $size = display_size($storetotal['iobytes'], 1, 'KB');
9902 } else if (!empty($storetotal['hits']) || !empty($storetotal['sets'])) {
9903 $size = '-';
9904 } else {
9905 $size = '';
9907 $row = [
9908 get_string('total'),
9910 $storetotal['hits'],
9911 $storetotal['misses'],
9912 $storetotal['sets'],
9913 $size,
9915 $table->data[] = $row;
9917 $html .= html_writer::table($table);
9919 $info['cachesused'] = "$hits / $misses / $sets";
9920 $info['html'] .= $html;
9921 $info['txt'] .= $text.'. ';
9922 } else {
9923 $info['cachesused'] = '0 / 0 / 0';
9924 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9925 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9928 // Display lock information if any.
9929 if (!empty($PERF->locks)) {
9930 $table = new html_table();
9931 $table->attributes['class'] = 'locktimings table table-dark table-sm w-auto table-bordered';
9932 $table->head = ['Lock', 'Waited (s)', 'Obtained', 'Held for (s)'];
9933 $table->align = ['left', 'right', 'center', 'right'];
9934 $table->data = [];
9935 $text = 'Locks (waited/obtained/held):';
9936 foreach ($PERF->locks as $locktiming) {
9937 $row = [];
9938 $row[] = s($locktiming->type . '/' . $locktiming->resource);
9939 $text .= ' ' . $locktiming->type . '/' . $locktiming->resource . ' (';
9941 // The time we had to wait to get the lock.
9942 $roundedtime = number_format($locktiming->wait, 1);
9943 $cell = new html_table_cell($roundedtime);
9944 if ($locktiming->wait > 0.5) {
9945 $cell->attributes = ['class' => 'bg-warning text-dark'];
9947 $row[] = $cell;
9948 $text .= $roundedtime . '/';
9950 // Show a tick or cross for success.
9951 $row[] = $locktiming->success ? '&#x2713;' : '&#x274c;';
9952 $text .= ($locktiming->success ? 'y' : 'n') . '/';
9954 // If applicable, show how long we held the lock before releasing it.
9955 if (property_exists($locktiming, 'held')) {
9956 $roundedtime = number_format($locktiming->held, 1);
9957 $cell = new html_table_cell($roundedtime);
9958 if ($locktiming->held > 0.5) {
9959 $cell->attributes = ['class' => 'bg-warning text-dark'];
9961 $row[] = $cell;
9962 $text .= $roundedtime;
9963 } else {
9964 $row[] = '-';
9965 $text .= '-';
9967 $text .= ')';
9969 $table->data[] = $row;
9971 $info['html'] .= html_writer::table($table);
9972 $info['txt'] .= $text . '. ';
9975 $info['html'] = '<div class="performanceinfo siteinfo container-fluid px-md-0 overflow-auto pt-3">'.$info['html'].'</div>';
9976 return $info;
9980 * Renames a file or directory to a unique name within the same directory.
9982 * This function is designed to avoid any potential race conditions, and select an unused name.
9984 * @param string $filepath Original filepath
9985 * @param string $prefix Prefix to use for the temporary name
9986 * @return string|bool New file path or false if failed
9987 * @since Moodle 3.10
9989 function rename_to_unused_name(string $filepath, string $prefix = '_temp_') {
9990 $dir = dirname($filepath);
9991 $basename = $dir . '/' . $prefix;
9992 $limit = 0;
9993 while ($limit < 100) {
9994 // Select a new name based on a random number.
9995 $newfilepath = $basename . md5(mt_rand());
9997 // Attempt a rename to that new name.
9998 if (@rename($filepath, $newfilepath)) {
9999 return $newfilepath;
10002 // The first time, do some sanity checks, maybe it is failing for a good reason and there
10003 // is no point trying 100 times if so.
10004 if ($limit === 0 && (!file_exists($filepath) || !is_writable($dir))) {
10005 return false;
10007 $limit++;
10009 return false;
10013 * Delete directory or only its content
10015 * @param string $dir directory path
10016 * @param bool $contentonly
10017 * @return bool success, true also if dir does not exist
10019 function remove_dir($dir, $contentonly=false) {
10020 if (!is_dir($dir)) {
10021 // Nothing to do.
10022 return true;
10025 if (!$contentonly) {
10026 // Start by renaming the directory; this will guarantee that other processes don't write to it
10027 // while it is in the process of being deleted.
10028 $tempdir = rename_to_unused_name($dir);
10029 if ($tempdir) {
10030 // If the rename was successful then delete the $tempdir instead.
10031 $dir = $tempdir;
10033 // If the rename fails, we will continue through and attempt to delete the directory
10034 // without renaming it since that is likely to at least delete most of the files.
10037 if (!$handle = opendir($dir)) {
10038 return false;
10040 $result = true;
10041 while (false!==($item = readdir($handle))) {
10042 if ($item != '.' && $item != '..') {
10043 if (is_dir($dir.'/'.$item)) {
10044 $result = remove_dir($dir.'/'.$item) && $result;
10045 } else {
10046 $result = unlink($dir.'/'.$item) && $result;
10050 closedir($handle);
10051 if ($contentonly) {
10052 clearstatcache(); // Make sure file stat cache is properly invalidated.
10053 return $result;
10055 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
10056 clearstatcache(); // Make sure file stat cache is properly invalidated.
10057 return $result;
10061 * Detect if an object or a class contains a given property
10062 * will take an actual object or the name of a class
10064 * @param mix $obj Name of class or real object to test
10065 * @param string $property name of property to find
10066 * @return bool true if property exists
10068 function object_property_exists( $obj, $property ) {
10069 if (is_string( $obj )) {
10070 $properties = get_class_vars( $obj );
10071 } else {
10072 $properties = get_object_vars( $obj );
10074 return array_key_exists( $property, $properties );
10078 * Converts an object into an associative array
10080 * This function converts an object into an associative array by iterating
10081 * over its public properties. Because this function uses the foreach
10082 * construct, Iterators are respected. It works recursively on arrays of objects.
10083 * Arrays and simple values are returned as is.
10085 * If class has magic properties, it can implement IteratorAggregate
10086 * and return all available properties in getIterator()
10088 * @param mixed $var
10089 * @return array
10091 function convert_to_array($var) {
10092 $result = array();
10094 // Loop over elements/properties.
10095 foreach ($var as $key => $value) {
10096 // Recursively convert objects.
10097 if (is_object($value) || is_array($value)) {
10098 $result[$key] = convert_to_array($value);
10099 } else {
10100 // Simple values are untouched.
10101 $result[$key] = $value;
10104 return $result;
10108 * Detect a custom script replacement in the data directory that will
10109 * replace an existing moodle script
10111 * @return string|bool full path name if a custom script exists, false if no custom script exists
10113 function custom_script_path() {
10114 global $CFG, $SCRIPT;
10116 if ($SCRIPT === null) {
10117 // Probably some weird external script.
10118 return false;
10121 $scriptpath = $CFG->customscripts . $SCRIPT;
10123 // Check the custom script exists.
10124 if (file_exists($scriptpath) and is_file($scriptpath)) {
10125 return $scriptpath;
10126 } else {
10127 return false;
10132 * Returns whether or not the user object is a remote MNET user. This function
10133 * is in moodlelib because it does not rely on loading any of the MNET code.
10135 * @param object $user A valid user object
10136 * @return bool True if the user is from a remote Moodle.
10138 function is_mnet_remote_user($user) {
10139 global $CFG;
10141 if (!isset($CFG->mnet_localhost_id)) {
10142 include_once($CFG->dirroot . '/mnet/lib.php');
10143 $env = new mnet_environment();
10144 $env->init();
10145 unset($env);
10148 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
10152 * This function will search for browser prefereed languages, setting Moodle
10153 * to use the best one available if $SESSION->lang is undefined
10155 function setup_lang_from_browser() {
10156 global $CFG, $SESSION, $USER;
10158 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
10159 // Lang is defined in session or user profile, nothing to do.
10160 return;
10163 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
10164 return;
10167 // Extract and clean langs from headers.
10168 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
10169 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
10170 $rawlangs = explode(',', $rawlangs); // Convert to array.
10171 $langs = array();
10173 $order = 1.0;
10174 foreach ($rawlangs as $lang) {
10175 if (strpos($lang, ';') === false) {
10176 $langs[(string)$order] = $lang;
10177 $order = $order-0.01;
10178 } else {
10179 $parts = explode(';', $lang);
10180 $pos = strpos($parts[1], '=');
10181 $langs[substr($parts[1], $pos+1)] = $parts[0];
10184 krsort($langs, SORT_NUMERIC);
10186 // Look for such langs under standard locations.
10187 foreach ($langs as $lang) {
10188 // Clean it properly for include.
10189 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
10190 if (get_string_manager()->translation_exists($lang, false)) {
10191 // Lang exists, set it in session.
10192 $SESSION->lang = $lang;
10193 // We have finished. Go out.
10194 break;
10197 return;
10201 * Check if $url matches anything in proxybypass list
10203 * Any errors just result in the proxy being used (least bad)
10205 * @param string $url url to check
10206 * @return boolean true if we should bypass the proxy
10208 function is_proxybypass( $url ) {
10209 global $CFG;
10211 // Sanity check.
10212 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
10213 return false;
10216 // Get the host part out of the url.
10217 if (!$host = parse_url( $url, PHP_URL_HOST )) {
10218 return false;
10221 // Get the possible bypass hosts into an array.
10222 $matches = explode( ',', $CFG->proxybypass );
10224 // Check for a match.
10225 // (IPs need to match the left hand side and hosts the right of the url,
10226 // but we can recklessly check both as there can't be a false +ve).
10227 foreach ($matches as $match) {
10228 $match = trim($match);
10230 // Try for IP match (Left side).
10231 $lhs = substr($host, 0, strlen($match));
10232 if (strcasecmp($match, $lhs)==0) {
10233 return true;
10236 // Try for host match (Right side).
10237 $rhs = substr($host, -strlen($match));
10238 if (strcasecmp($match, $rhs)==0) {
10239 return true;
10243 // Nothing matched.
10244 return false;
10248 * Check if the passed navigation is of the new style
10250 * @param mixed $navigation
10251 * @return bool true for yes false for no
10253 function is_newnav($navigation) {
10254 if (is_array($navigation) && !empty($navigation['newnav'])) {
10255 return true;
10256 } else {
10257 return false;
10262 * Checks whether the given variable name is defined as a variable within the given object.
10264 * This will NOT work with stdClass objects, which have no class variables.
10266 * @param string $var The variable name
10267 * @param object $object The object to check
10268 * @return boolean
10270 function in_object_vars($var, $object) {
10271 $classvars = get_class_vars(get_class($object));
10272 $classvars = array_keys($classvars);
10273 return in_array($var, $classvars);
10277 * Returns an array without repeated objects.
10278 * This function is similar to array_unique, but for arrays that have objects as values
10280 * @param array $array
10281 * @param bool $keepkeyassoc
10282 * @return array
10284 function object_array_unique($array, $keepkeyassoc = true) {
10285 $duplicatekeys = array();
10286 $tmp = array();
10288 foreach ($array as $key => $val) {
10289 // Convert objects to arrays, in_array() does not support objects.
10290 if (is_object($val)) {
10291 $val = (array)$val;
10294 if (!in_array($val, $tmp)) {
10295 $tmp[] = $val;
10296 } else {
10297 $duplicatekeys[] = $key;
10301 foreach ($duplicatekeys as $key) {
10302 unset($array[$key]);
10305 return $keepkeyassoc ? $array : array_values($array);
10309 * Is a userid the primary administrator?
10311 * @param int $userid int id of user to check
10312 * @return boolean
10314 function is_primary_admin($userid) {
10315 $primaryadmin = get_admin();
10317 if ($userid == $primaryadmin->id) {
10318 return true;
10319 } else {
10320 return false;
10325 * Returns the site identifier
10327 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
10329 function get_site_identifier() {
10330 global $CFG;
10331 // Check to see if it is missing. If so, initialise it.
10332 if (empty($CFG->siteidentifier)) {
10333 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
10335 // Return it.
10336 return $CFG->siteidentifier;
10340 * Check whether the given password has no more than the specified
10341 * number of consecutive identical characters.
10343 * @param string $password password to be checked against the password policy
10344 * @param integer $maxchars maximum number of consecutive identical characters
10345 * @return bool
10347 function check_consecutive_identical_characters($password, $maxchars) {
10349 if ($maxchars < 1) {
10350 return true; // Zero 0 is to disable this check.
10352 if (strlen($password) <= $maxchars) {
10353 return true; // Too short to fail this test.
10356 $previouschar = '';
10357 $consecutivecount = 1;
10358 foreach (str_split($password) as $char) {
10359 if ($char != $previouschar) {
10360 $consecutivecount = 1;
10361 } else {
10362 $consecutivecount++;
10363 if ($consecutivecount > $maxchars) {
10364 return false; // Check failed already.
10368 $previouschar = $char;
10371 return true;
10375 * Helper function to do partial function binding.
10376 * so we can use it for preg_replace_callback, for example
10377 * this works with php functions, user functions, static methods and class methods
10378 * it returns you a callback that you can pass on like so:
10380 * $callback = partial('somefunction', $arg1, $arg2);
10381 * or
10382 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
10383 * or even
10384 * $obj = new someclass();
10385 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
10387 * and then the arguments that are passed through at calltime are appended to the argument list.
10389 * @param mixed $function a php callback
10390 * @param mixed $arg1,... $argv arguments to partially bind with
10391 * @return array Array callback
10393 function partial() {
10394 if (!class_exists('partial')) {
10396 * Used to manage function binding.
10397 * @copyright 2009 Penny Leach
10398 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10400 class partial{
10401 /** @var array */
10402 public $values = array();
10403 /** @var string The function to call as a callback. */
10404 public $func;
10406 * Constructor
10407 * @param string $func
10408 * @param array $args
10410 public function __construct($func, $args) {
10411 $this->values = $args;
10412 $this->func = $func;
10415 * Calls the callback function.
10416 * @return mixed
10418 public function method() {
10419 $args = func_get_args();
10420 return call_user_func_array($this->func, array_merge($this->values, $args));
10424 $args = func_get_args();
10425 $func = array_shift($args);
10426 $p = new partial($func, $args);
10427 return array($p, 'method');
10431 * helper function to load up and initialise the mnet environment
10432 * this must be called before you use mnet functions.
10434 * @return mnet_environment the equivalent of old $MNET global
10436 function get_mnet_environment() {
10437 global $CFG;
10438 require_once($CFG->dirroot . '/mnet/lib.php');
10439 static $instance = null;
10440 if (empty($instance)) {
10441 $instance = new mnet_environment();
10442 $instance->init();
10444 return $instance;
10448 * during xmlrpc server code execution, any code wishing to access
10449 * information about the remote peer must use this to get it.
10451 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
10453 function get_mnet_remote_client() {
10454 if (!defined('MNET_SERVER')) {
10455 debugging(get_string('notinxmlrpcserver', 'mnet'));
10456 return false;
10458 global $MNET_REMOTE_CLIENT;
10459 if (isset($MNET_REMOTE_CLIENT)) {
10460 return $MNET_REMOTE_CLIENT;
10462 return false;
10466 * during the xmlrpc server code execution, this will be called
10467 * to setup the object returned by {@link get_mnet_remote_client}
10469 * @param mnet_remote_client $client the client to set up
10470 * @throws moodle_exception
10472 function set_mnet_remote_client($client) {
10473 if (!defined('MNET_SERVER')) {
10474 throw new moodle_exception('notinxmlrpcserver', 'mnet');
10476 global $MNET_REMOTE_CLIENT;
10477 $MNET_REMOTE_CLIENT = $client;
10481 * return the jump url for a given remote user
10482 * this is used for rewriting forum post links in emails, etc
10484 * @param stdclass $user the user to get the idp url for
10486 function mnet_get_idp_jump_url($user) {
10487 global $CFG;
10489 static $mnetjumps = array();
10490 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
10491 $idp = mnet_get_peer_host($user->mnethostid);
10492 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
10493 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
10495 return $mnetjumps[$user->mnethostid];
10499 * Gets the homepage to use for the current user
10501 * @return int One of HOMEPAGE_*
10503 function get_home_page() {
10504 global $CFG;
10506 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
10507 // If dashboard is disabled, home will be set to default page.
10508 $defaultpage = get_default_home_page();
10509 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
10510 if (!empty($CFG->enabledashboard)) {
10511 return HOMEPAGE_MY;
10512 } else {
10513 return $defaultpage;
10515 } else if ($CFG->defaulthomepage == HOMEPAGE_MYCOURSES) {
10516 return HOMEPAGE_MYCOURSES;
10517 } else {
10518 $userhomepage = (int) get_user_preferences('user_home_page_preference', $defaultpage);
10519 if (empty($CFG->enabledashboard) && $userhomepage == HOMEPAGE_MY) {
10520 // If the user was using the dashboard but it's disabled, return the default home page.
10521 $userhomepage = $defaultpage;
10523 return $userhomepage;
10526 return HOMEPAGE_SITE;
10530 * Returns the default home page to display if current one is not defined or can't be applied.
10531 * The default behaviour is to return Dashboard if it's enabled or My courses page if it isn't.
10533 * @return int The default home page.
10535 function get_default_home_page(): int {
10536 global $CFG;
10538 return !empty($CFG->enabledashboard) ? HOMEPAGE_MY : HOMEPAGE_MYCOURSES;
10542 * Gets the name of a course to be displayed when showing a list of courses.
10543 * By default this is just $course->fullname but user can configure it. The
10544 * result of this function should be passed through print_string.
10545 * @param stdClass|core_course_list_element $course Moodle course object
10546 * @return string Display name of course (either fullname or short + fullname)
10548 function get_course_display_name_for_list($course) {
10549 global $CFG;
10550 if (!empty($CFG->courselistshortnames)) {
10551 if (!($course instanceof stdClass)) {
10552 $course = (object)convert_to_array($course);
10554 return get_string('courseextendednamedisplay', '', $course);
10555 } else {
10556 return $course->fullname;
10561 * Safe analogue of unserialize() that can only parse arrays
10563 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
10564 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
10565 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
10567 * @param string $expression
10568 * @return array|bool either parsed array or false if parsing was impossible.
10570 function unserialize_array($expression) {
10571 $subs = [];
10572 // Find nested arrays, parse them and store in $subs , substitute with special string.
10573 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
10574 $key = '--SUB' . count($subs) . '--';
10575 $subs[$key] = unserialize_array($matches[2]);
10576 if ($subs[$key] === false) {
10577 return false;
10579 $expression = str_replace($matches[2], $key . ';', $expression);
10582 // Check the expression is an array.
10583 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
10584 return false;
10586 // Get the size and elements of an array (key;value;key;value;....).
10587 $parts = explode(';', $matches1[2]);
10588 $size = intval($matches1[1]);
10589 if (count($parts) < $size * 2 + 1) {
10590 return false;
10592 // Analyze each part and make sure it is an integer or string or a substitute.
10593 $value = [];
10594 for ($i = 0; $i < $size * 2; $i++) {
10595 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
10596 $parts[$i] = (int)$matches2[1];
10597 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
10598 $parts[$i] = $matches3[2];
10599 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
10600 $parts[$i] = $subs[$parts[$i]];
10601 } else {
10602 return false;
10605 // Combine keys and values.
10606 for ($i = 0; $i < $size * 2; $i += 2) {
10607 $value[$parts[$i]] = $parts[$i+1];
10609 return $value;
10613 * Safe method for unserializing given input that is expected to contain only a serialized instance of an stdClass object
10615 * If any class type other than stdClass is included in the input string, it will not be instantiated and will be cast to an
10616 * stdClass object. The initial cast to array, then back to object is to ensure we are always returning the correct type,
10617 * otherwise we would return an instances of {@see __PHP_Incomplete_class} for malformed strings
10619 * @param string $input
10620 * @return stdClass
10622 function unserialize_object(string $input): stdClass {
10623 $instance = (array) unserialize($input, ['allowed_classes' => [stdClass::class]]);
10624 return (object) $instance;
10628 * The lang_string class
10630 * This special class is used to create an object representation of a string request.
10631 * It is special because processing doesn't occur until the object is first used.
10632 * The class was created especially to aid performance in areas where strings were
10633 * required to be generated but were not necessarily used.
10634 * As an example the admin tree when generated uses over 1500 strings, of which
10635 * normally only 1/3 are ever actually printed at any time.
10636 * The performance advantage is achieved by not actually processing strings that
10637 * arn't being used, as such reducing the processing required for the page.
10639 * How to use the lang_string class?
10640 * There are two methods of using the lang_string class, first through the
10641 * forth argument of the get_string function, and secondly directly.
10642 * The following are examples of both.
10643 * 1. Through get_string calls e.g.
10644 * $string = get_string($identifier, $component, $a, true);
10645 * $string = get_string('yes', 'moodle', null, true);
10646 * 2. Direct instantiation
10647 * $string = new lang_string($identifier, $component, $a, $lang);
10648 * $string = new lang_string('yes');
10650 * How do I use a lang_string object?
10651 * The lang_string object makes use of a magic __toString method so that you
10652 * are able to use the object exactly as you would use a string in most cases.
10653 * This means you are able to collect it into a variable and then directly
10654 * echo it, or concatenate it into another string, or similar.
10655 * The other thing you can do is manually get the string by calling the
10656 * lang_strings out method e.g.
10657 * $string = new lang_string('yes');
10658 * $string->out();
10659 * Also worth noting is that the out method can take one argument, $lang which
10660 * allows the developer to change the language on the fly.
10662 * When should I use a lang_string object?
10663 * The lang_string object is designed to be used in any situation where a
10664 * string may not be needed, but needs to be generated.
10665 * The admin tree is a good example of where lang_string objects should be
10666 * used.
10667 * A more practical example would be any class that requries strings that may
10668 * not be printed (after all classes get renderer by renderers and who knows
10669 * what they will do ;))
10671 * When should I not use a lang_string object?
10672 * Don't use lang_strings when you are going to use a string immediately.
10673 * There is no need as it will be processed immediately and there will be no
10674 * advantage, and in fact perhaps a negative hit as a class has to be
10675 * instantiated for a lang_string object, however get_string won't require
10676 * that.
10678 * Limitations:
10679 * 1. You cannot use a lang_string object as an array offset. Doing so will
10680 * result in PHP throwing an error. (You can use it as an object property!)
10682 * @package core
10683 * @category string
10684 * @copyright 2011 Sam Hemelryk
10685 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10687 class lang_string {
10689 /** @var string The strings identifier */
10690 protected $identifier;
10691 /** @var string The strings component. Default '' */
10692 protected $component = '';
10693 /** @var array|stdClass Any arguments required for the string. Default null */
10694 protected $a = null;
10695 /** @var string The language to use when processing the string. Default null */
10696 protected $lang = null;
10698 /** @var string The processed string (once processed) */
10699 protected $string = null;
10702 * A special boolean. If set to true then the object has been woken up and
10703 * cannot be regenerated. If this is set then $this->string MUST be used.
10704 * @var bool
10706 protected $forcedstring = false;
10709 * Constructs a lang_string object
10711 * This function should do as little processing as possible to ensure the best
10712 * performance for strings that won't be used.
10714 * @param string $identifier The strings identifier
10715 * @param string $component The strings component
10716 * @param stdClass|array $a Any arguments the string requires
10717 * @param string $lang The language to use when processing the string.
10718 * @throws coding_exception
10720 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10721 if (empty($component)) {
10722 $component = 'moodle';
10725 $this->identifier = $identifier;
10726 $this->component = $component;
10727 $this->lang = $lang;
10729 // We MUST duplicate $a to ensure that it if it changes by reference those
10730 // changes are not carried across.
10731 // To do this we always ensure $a or its properties/values are strings
10732 // and that any properties/values that arn't convertable are forgotten.
10733 if ($a !== null) {
10734 if (is_scalar($a)) {
10735 $this->a = $a;
10736 } else if ($a instanceof lang_string) {
10737 $this->a = $a->out();
10738 } else if (is_object($a) or is_array($a)) {
10739 $a = (array)$a;
10740 $this->a = array();
10741 foreach ($a as $key => $value) {
10742 // Make sure conversion errors don't get displayed (results in '').
10743 if (is_array($value)) {
10744 $this->a[$key] = '';
10745 } else if (is_object($value)) {
10746 if (method_exists($value, '__toString')) {
10747 $this->a[$key] = $value->__toString();
10748 } else {
10749 $this->a[$key] = '';
10751 } else {
10752 $this->a[$key] = (string)$value;
10758 if (debugging(false, DEBUG_DEVELOPER)) {
10759 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10760 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10762 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10763 throw new coding_exception('Invalid string compontent. Please check your string definition');
10765 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10766 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10772 * Processes the string.
10774 * This function actually processes the string, stores it in the string property
10775 * and then returns it.
10776 * You will notice that this function is VERY similar to the get_string method.
10777 * That is because it is pretty much doing the same thing.
10778 * However as this function is an upgrade it isn't as tolerant to backwards
10779 * compatibility.
10781 * @return string
10782 * @throws coding_exception
10784 protected function get_string() {
10785 global $CFG;
10787 // Check if we need to process the string.
10788 if ($this->string === null) {
10789 // Check the quality of the identifier.
10790 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10791 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);
10794 // Process the string.
10795 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10796 // Debugging feature lets you display string identifier and component.
10797 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10798 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10801 // Return the string.
10802 return $this->string;
10806 * Returns the string
10808 * @param string $lang The langauge to use when processing the string
10809 * @return string
10811 public function out($lang = null) {
10812 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10813 if ($this->forcedstring) {
10814 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10815 return $this->get_string();
10817 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10818 return $translatedstring->out();
10820 return $this->get_string();
10824 * Magic __toString method for printing a string
10826 * @return string
10828 public function __toString() {
10829 return $this->get_string();
10833 * Magic __set_state method used for var_export
10835 * @param array $array
10836 * @return self
10838 public static function __set_state(array $array): self {
10839 $tmp = new lang_string($array['identifier'], $array['component'], $array['a'], $array['lang']);
10840 $tmp->string = $array['string'];
10841 $tmp->forcedstring = $array['forcedstring'];
10842 return $tmp;
10846 * Prepares the lang_string for sleep and stores only the forcedstring and
10847 * string properties... the string cannot be regenerated so we need to ensure
10848 * it is generated for this.
10850 * @return string
10852 public function __sleep() {
10853 $this->get_string();
10854 $this->forcedstring = true;
10855 return array('forcedstring', 'string', 'lang');
10859 * Returns the identifier.
10861 * @return string
10863 public function get_identifier() {
10864 return $this->identifier;
10868 * Returns the component.
10870 * @return string
10872 public function get_component() {
10873 return $this->component;
10878 * Get human readable name describing the given callable.
10880 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10881 * It does not check if the callable actually exists.
10883 * @param callable|string|array $callable
10884 * @return string|bool Human readable name of callable, or false if not a valid callable.
10886 function get_callable_name($callable) {
10888 if (!is_callable($callable, true, $name)) {
10889 return false;
10891 } else {
10892 return $name;
10897 * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10898 * Never put your faith on this function and rely on its accuracy as there might be false positives.
10899 * It just performs some simple checks, and mainly is used for places where we want to hide some options
10900 * such as site registration when $CFG->wwwroot is not publicly accessible.
10901 * Good thing is there is no false negative.
10902 * Note that it's possible to force the result of this check by specifying $CFG->site_is_public in config.php
10904 * @return bool
10906 function site_is_public() {
10907 global $CFG;
10909 // Return early if site admin has forced this setting.
10910 if (isset($CFG->site_is_public)) {
10911 return (bool)$CFG->site_is_public;
10914 $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
10916 if ($host === 'localhost' || preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10917 $ispublic = false;
10918 } else if (\core\ip_utils::is_ip_address($host) && !ip_is_public($host)) {
10919 $ispublic = false;
10920 } else if (($address = \core\ip_utils::get_ip_address($host)) && !ip_is_public($address)) {
10921 $ispublic = false;
10922 } else {
10923 $ispublic = true;
10926 return $ispublic;