Merge branch 'MDL-77669-400' of https://github.com/andrewnicols/moodle into MOODLE_40...
[moodle.git] / lib / moodlelib.php
blob83f4c9094063a2598d8dd62692b2176952b5d60d
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);
566 // PARAMETER HANDLING.
569 * Returns a particular value for the named variable, taken from
570 * POST or GET. If the parameter doesn't exist then an error is
571 * thrown because we require this variable.
573 * This function should be used to initialise all required values
574 * in a script that are based on parameters. Usually it will be
575 * used like this:
576 * $id = required_param('id', PARAM_INT);
578 * Please note the $type parameter is now required and the value can not be array.
580 * @param string $parname the name of the page parameter we want
581 * @param string $type expected type of parameter
582 * @return mixed
583 * @throws coding_exception
585 function required_param($parname, $type) {
586 if (func_num_args() != 2 or empty($parname) or empty($type)) {
587 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
589 // POST has precedence.
590 if (isset($_POST[$parname])) {
591 $param = $_POST[$parname];
592 } else if (isset($_GET[$parname])) {
593 $param = $_GET[$parname];
594 } else {
595 print_error('missingparam', '', '', $parname);
598 if (is_array($param)) {
599 debugging('Invalid array parameter detected in required_param(): '.$parname);
600 // TODO: switch to fatal error in Moodle 2.3.
601 return required_param_array($parname, $type);
604 return clean_param($param, $type);
608 * Returns a particular array value for the named variable, taken from
609 * POST or GET. If the parameter doesn't exist then an error is
610 * thrown because we require this variable.
612 * This function should be used to initialise all required values
613 * in a script that are based on parameters. Usually it will be
614 * used like this:
615 * $ids = required_param_array('ids', PARAM_INT);
617 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
619 * @param string $parname the name of the page parameter we want
620 * @param string $type expected type of parameter
621 * @return array
622 * @throws coding_exception
624 function required_param_array($parname, $type) {
625 if (func_num_args() != 2 or empty($parname) or empty($type)) {
626 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
628 // POST has precedence.
629 if (isset($_POST[$parname])) {
630 $param = $_POST[$parname];
631 } else if (isset($_GET[$parname])) {
632 $param = $_GET[$parname];
633 } else {
634 print_error('missingparam', '', '', $parname);
636 if (!is_array($param)) {
637 print_error('missingparam', '', '', $parname);
640 $result = array();
641 foreach ($param as $key => $value) {
642 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
643 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
644 continue;
646 $result[$key] = clean_param($value, $type);
649 return $result;
653 * Returns a particular value for the named variable, taken from
654 * POST or GET, otherwise returning a given default.
656 * This function should be used to initialise all optional values
657 * in a script that are based on parameters. Usually it will be
658 * used like this:
659 * $name = optional_param('name', 'Fred', PARAM_TEXT);
661 * Please note the $type parameter is now required and the value can not be array.
663 * @param string $parname the name of the page parameter we want
664 * @param mixed $default the default value to return if nothing is found
665 * @param string $type expected type of parameter
666 * @return mixed
667 * @throws coding_exception
669 function optional_param($parname, $default, $type) {
670 if (func_num_args() != 3 or empty($parname) or empty($type)) {
671 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
674 // POST has precedence.
675 if (isset($_POST[$parname])) {
676 $param = $_POST[$parname];
677 } else if (isset($_GET[$parname])) {
678 $param = $_GET[$parname];
679 } else {
680 return $default;
683 if (is_array($param)) {
684 debugging('Invalid array parameter detected in required_param(): '.$parname);
685 // TODO: switch to $default in Moodle 2.3.
686 return optional_param_array($parname, $default, $type);
689 return clean_param($param, $type);
693 * Returns a particular array value for the named variable, taken from
694 * POST or GET, otherwise returning a given default.
696 * This function should be used to initialise all optional values
697 * in a script that are based on parameters. Usually it will be
698 * used like this:
699 * $ids = optional_param('id', array(), PARAM_INT);
701 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
703 * @param string $parname the name of the page parameter we want
704 * @param mixed $default the default value to return if nothing is found
705 * @param string $type expected type of parameter
706 * @return array
707 * @throws coding_exception
709 function optional_param_array($parname, $default, $type) {
710 if (func_num_args() != 3 or empty($parname) or empty($type)) {
711 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
714 // POST has precedence.
715 if (isset($_POST[$parname])) {
716 $param = $_POST[$parname];
717 } else if (isset($_GET[$parname])) {
718 $param = $_GET[$parname];
719 } else {
720 return $default;
722 if (!is_array($param)) {
723 debugging('optional_param_array() expects array parameters only: '.$parname);
724 return $default;
727 $result = array();
728 foreach ($param as $key => $value) {
729 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
730 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
731 continue;
733 $result[$key] = clean_param($value, $type);
736 return $result;
740 * Strict validation of parameter values, the values are only converted
741 * to requested PHP type. Internally it is using clean_param, the values
742 * before and after cleaning must be equal - otherwise
743 * an invalid_parameter_exception is thrown.
744 * Objects and classes are not accepted.
746 * @param mixed $param
747 * @param string $type PARAM_ constant
748 * @param bool $allownull are nulls valid value?
749 * @param string $debuginfo optional debug information
750 * @return mixed the $param value converted to PHP type
751 * @throws invalid_parameter_exception if $param is not of given type
753 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
754 if (is_null($param)) {
755 if ($allownull == NULL_ALLOWED) {
756 return null;
757 } else {
758 throw new invalid_parameter_exception($debuginfo);
761 if (is_array($param) or is_object($param)) {
762 throw new invalid_parameter_exception($debuginfo);
765 $cleaned = clean_param($param, $type);
767 if ($type == PARAM_FLOAT) {
768 // Do not detect precision loss here.
769 if (is_float($param) or is_int($param)) {
770 // These always fit.
771 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
772 throw new invalid_parameter_exception($debuginfo);
774 } else if ((string)$param !== (string)$cleaned) {
775 // Conversion to string is usually lossless.
776 throw new invalid_parameter_exception($debuginfo);
779 return $cleaned;
783 * Makes sure array contains only the allowed types, this function does not validate array key names!
785 * <code>
786 * $options = clean_param($options, PARAM_INT);
787 * </code>
789 * @param array|null $param the variable array we are cleaning
790 * @param string $type expected format of param after cleaning.
791 * @param bool $recursive clean recursive arrays
792 * @return array
793 * @throws coding_exception
795 function clean_param_array(?array $param, $type, $recursive = false) {
796 // Convert null to empty array.
797 $param = (array)$param;
798 foreach ($param as $key => $value) {
799 if (is_array($value)) {
800 if ($recursive) {
801 $param[$key] = clean_param_array($value, $type, true);
802 } else {
803 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
805 } else {
806 $param[$key] = clean_param($value, $type);
809 return $param;
813 * Used by {@link optional_param()} and {@link required_param()} to
814 * clean the variables and/or cast to specific types, based on
815 * an options field.
816 * <code>
817 * $course->format = clean_param($course->format, PARAM_ALPHA);
818 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
819 * </code>
821 * @param mixed $param the variable we are cleaning
822 * @param string $type expected format of param after cleaning.
823 * @return mixed
824 * @throws coding_exception
826 function clean_param($param, $type) {
827 global $CFG;
829 if (is_array($param)) {
830 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
831 } else if (is_object($param)) {
832 if (method_exists($param, '__toString')) {
833 $param = $param->__toString();
834 } else {
835 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
839 switch ($type) {
840 case PARAM_RAW:
841 // No cleaning at all.
842 $param = fix_utf8($param);
843 return $param;
845 case PARAM_RAW_TRIMMED:
846 // No cleaning, but strip leading and trailing whitespace.
847 $param = fix_utf8($param);
848 return trim($param);
850 case PARAM_CLEAN:
851 // General HTML cleaning, try to use more specific type if possible this is deprecated!
852 // Please use more specific type instead.
853 if (is_numeric($param)) {
854 return $param;
856 $param = fix_utf8($param);
857 // Sweep for scripts, etc.
858 return clean_text($param);
860 case PARAM_CLEANHTML:
861 // Clean html fragment.
862 $param = fix_utf8($param);
863 // Sweep for scripts, etc.
864 $param = clean_text($param, FORMAT_HTML);
865 return trim($param);
867 case PARAM_INT:
868 // Convert to integer.
869 return (int)$param;
871 case PARAM_FLOAT:
872 // Convert to float.
873 return (float)$param;
875 case PARAM_LOCALISEDFLOAT:
876 // Convert to float.
877 return unformat_float($param, true);
879 case PARAM_ALPHA:
880 // Remove everything not `a-z`.
881 return preg_replace('/[^a-zA-Z]/i', '', $param);
883 case PARAM_ALPHAEXT:
884 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
885 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
887 case PARAM_ALPHANUM:
888 // Remove everything not `a-zA-Z0-9`.
889 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
891 case PARAM_ALPHANUMEXT:
892 // Remove everything not `a-zA-Z0-9_-`.
893 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
895 case PARAM_SEQUENCE:
896 // Remove everything not `0-9,`.
897 return preg_replace('/[^0-9,]/i', '', $param);
899 case PARAM_BOOL:
900 // Convert to 1 or 0.
901 $tempstr = strtolower($param);
902 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
903 $param = 1;
904 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
905 $param = 0;
906 } else {
907 $param = empty($param) ? 0 : 1;
909 return $param;
911 case PARAM_NOTAGS:
912 // Strip all tags.
913 $param = fix_utf8($param);
914 return strip_tags($param);
916 case PARAM_TEXT:
917 // Leave only tags needed for multilang.
918 $param = fix_utf8($param);
919 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
920 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
921 do {
922 if (strpos($param, '</lang>') !== false) {
923 // Old and future mutilang syntax.
924 $param = strip_tags($param, '<lang>');
925 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
926 break;
928 $open = false;
929 foreach ($matches[0] as $match) {
930 if ($match === '</lang>') {
931 if ($open) {
932 $open = false;
933 continue;
934 } else {
935 break 2;
938 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
939 break 2;
940 } else {
941 $open = true;
944 if ($open) {
945 break;
947 return $param;
949 } else if (strpos($param, '</span>') !== false) {
950 // Current problematic multilang syntax.
951 $param = strip_tags($param, '<span>');
952 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
953 break;
955 $open = false;
956 foreach ($matches[0] as $match) {
957 if ($match === '</span>') {
958 if ($open) {
959 $open = false;
960 continue;
961 } else {
962 break 2;
965 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
966 break 2;
967 } else {
968 $open = true;
971 if ($open) {
972 break;
974 return $param;
976 } while (false);
977 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
978 return strip_tags($param);
980 case PARAM_COMPONENT:
981 // We do not want any guessing here, either the name is correct or not
982 // please note only normalised component names are accepted.
983 if (!preg_match('/^[a-z][a-z0-9]*(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
984 return '';
986 if (strpos($param, '__') !== false) {
987 return '';
989 if (strpos($param, 'mod_') === 0) {
990 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
991 if (substr_count($param, '_') != 1) {
992 return '';
995 return $param;
997 case PARAM_PLUGIN:
998 case PARAM_AREA:
999 // We do not want any guessing here, either the name is correct or not.
1000 if (!is_valid_plugin_name($param)) {
1001 return '';
1003 return $param;
1005 case PARAM_SAFEDIR:
1006 // Remove everything not a-zA-Z0-9_- .
1007 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
1009 case PARAM_SAFEPATH:
1010 // Remove everything not a-zA-Z0-9/_- .
1011 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
1013 case PARAM_FILE:
1014 // Strip all suspicious characters from filename.
1015 $param = fix_utf8($param);
1016 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
1017 if ($param === '.' || $param === '..') {
1018 $param = '';
1020 return $param;
1022 case PARAM_PATH:
1023 // Strip all suspicious characters from file path.
1024 $param = fix_utf8($param);
1025 $param = str_replace('\\', '/', $param);
1027 // Explode the path and clean each element using the PARAM_FILE rules.
1028 $breadcrumb = explode('/', $param);
1029 foreach ($breadcrumb as $key => $crumb) {
1030 if ($crumb === '.' && $key === 0) {
1031 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1032 } else {
1033 $crumb = clean_param($crumb, PARAM_FILE);
1035 $breadcrumb[$key] = $crumb;
1037 $param = implode('/', $breadcrumb);
1039 // Remove multiple current path (./././) and multiple slashes (///).
1040 $param = preg_replace('~//+~', '/', $param);
1041 $param = preg_replace('~/(\./)+~', '/', $param);
1042 return $param;
1044 case PARAM_HOST:
1045 // Allow FQDN or IPv4 dotted quad.
1046 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1047 // Match ipv4 dotted quad.
1048 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1049 // Confirm values are ok.
1050 if ( $match[0] > 255
1051 || $match[1] > 255
1052 || $match[3] > 255
1053 || $match[4] > 255 ) {
1054 // Hmmm, what kind of dotted quad is this?
1055 $param = '';
1057 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1058 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1059 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1061 // All is ok - $param is respected.
1062 } else {
1063 // All is not ok...
1064 $param='';
1066 return $param;
1068 case PARAM_URL:
1069 // Allow safe urls.
1070 $param = fix_utf8($param);
1071 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1072 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1073 // All is ok, param is respected.
1074 } else {
1075 // Not really ok.
1076 $param ='';
1078 return $param;
1080 case PARAM_LOCALURL:
1081 // Allow http absolute, root relative and relative URLs within wwwroot.
1082 $param = clean_param($param, PARAM_URL);
1083 if (!empty($param)) {
1085 if ($param === $CFG->wwwroot) {
1086 // Exact match;
1087 } else if (preg_match(':^/:', $param)) {
1088 // Root-relative, ok!
1089 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1090 // Absolute, and matches our wwwroot.
1091 } else {
1093 // Relative - let's make sure there are no tricks.
1094 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?') && !preg_match('/javascript:/i', $param)) {
1095 // Looks ok.
1096 } else {
1097 $param = '';
1101 return $param;
1103 case PARAM_PEM:
1104 $param = trim($param);
1105 // PEM formatted strings may contain letters/numbers and the symbols:
1106 // forward slash: /
1107 // plus sign: +
1108 // equal sign: =
1109 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1110 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1111 list($wholething, $body) = $matches;
1112 unset($wholething, $matches);
1113 $b64 = clean_param($body, PARAM_BASE64);
1114 if (!empty($b64)) {
1115 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1116 } else {
1117 return '';
1120 return '';
1122 case PARAM_BASE64:
1123 if (!empty($param)) {
1124 // PEM formatted strings may contain letters/numbers and the symbols
1125 // forward slash: /
1126 // plus sign: +
1127 // equal sign: =.
1128 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1129 return '';
1131 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1132 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1133 // than (or equal to) 64 characters long.
1134 for ($i=0, $j=count($lines); $i < $j; $i++) {
1135 if ($i + 1 == $j) {
1136 if (64 < strlen($lines[$i])) {
1137 return '';
1139 continue;
1142 if (64 != strlen($lines[$i])) {
1143 return '';
1146 return implode("\n", $lines);
1147 } else {
1148 return '';
1151 case PARAM_TAG:
1152 $param = fix_utf8($param);
1153 // Please note it is not safe to use the tag name directly anywhere,
1154 // it must be processed with s(), urlencode() before embedding anywhere.
1155 // Remove some nasties.
1156 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1157 // Convert many whitespace chars into one.
1158 $param = preg_replace('/\s+/u', ' ', $param);
1159 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1160 return $param;
1162 case PARAM_TAGLIST:
1163 $param = fix_utf8($param);
1164 $tags = explode(',', $param);
1165 $result = array();
1166 foreach ($tags as $tag) {
1167 $res = clean_param($tag, PARAM_TAG);
1168 if ($res !== '') {
1169 $result[] = $res;
1172 if ($result) {
1173 return implode(',', $result);
1174 } else {
1175 return '';
1178 case PARAM_CAPABILITY:
1179 if (get_capability_info($param)) {
1180 return $param;
1181 } else {
1182 return '';
1185 case PARAM_PERMISSION:
1186 $param = (int)$param;
1187 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1188 return $param;
1189 } else {
1190 return CAP_INHERIT;
1193 case PARAM_AUTH:
1194 $param = clean_param($param, PARAM_PLUGIN);
1195 if (empty($param)) {
1196 return '';
1197 } else if (exists_auth_plugin($param)) {
1198 return $param;
1199 } else {
1200 return '';
1203 case PARAM_LANG:
1204 $param = clean_param($param, PARAM_SAFEDIR);
1205 if (get_string_manager()->translation_exists($param)) {
1206 return $param;
1207 } else {
1208 // Specified language is not installed or param malformed.
1209 return '';
1212 case PARAM_THEME:
1213 $param = clean_param($param, PARAM_PLUGIN);
1214 if (empty($param)) {
1215 return '';
1216 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1217 return $param;
1218 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1219 return $param;
1220 } else {
1221 // Specified theme is not installed.
1222 return '';
1225 case PARAM_USERNAME:
1226 $param = fix_utf8($param);
1227 $param = trim($param);
1228 // Convert uppercase to lowercase MDL-16919.
1229 $param = core_text::strtolower($param);
1230 if (empty($CFG->extendedusernamechars)) {
1231 $param = str_replace(" " , "", $param);
1232 // Regular expression, eliminate all chars EXCEPT:
1233 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1234 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1236 return $param;
1238 case PARAM_EMAIL:
1239 $param = fix_utf8($param);
1240 if (validate_email($param)) {
1241 return $param;
1242 } else {
1243 return '';
1246 case PARAM_STRINGID:
1247 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1248 return $param;
1249 } else {
1250 return '';
1253 case PARAM_TIMEZONE:
1254 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1255 $param = fix_utf8($param);
1256 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1257 if (preg_match($timezonepattern, $param)) {
1258 return $param;
1259 } else {
1260 return '';
1263 default:
1264 // Doh! throw error, switched parameters in optional_param or another serious problem.
1265 print_error("unknownparamtype", '', '', $type);
1270 * Whether the PARAM_* type is compatible in RTL.
1272 * Being compatible with RTL means that the data they contain can flow
1273 * from right-to-left or left-to-right without compromising the user experience.
1275 * Take URLs for example, they are not RTL compatible as they should always
1276 * flow from the left to the right. This also applies to numbers, email addresses,
1277 * configuration snippets, base64 strings, etc...
1279 * This function tries to best guess which parameters can contain localised strings.
1281 * @param string $paramtype Constant PARAM_*.
1282 * @return bool
1284 function is_rtl_compatible($paramtype) {
1285 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1289 * Makes sure the data is using valid utf8, invalid characters are discarded.
1291 * Note: this function is not intended for full objects with methods and private properties.
1293 * @param mixed $value
1294 * @return mixed with proper utf-8 encoding
1296 function fix_utf8($value) {
1297 if (is_null($value) or $value === '') {
1298 return $value;
1300 } else if (is_string($value)) {
1301 if ((string)(int)$value === $value) {
1302 // Shortcut.
1303 return $value;
1305 // No null bytes expected in our data, so let's remove it.
1306 $value = str_replace("\0", '', $value);
1308 // Note: this duplicates min_fix_utf8() intentionally.
1309 static $buggyiconv = null;
1310 if ($buggyiconv === null) {
1311 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1314 if ($buggyiconv) {
1315 if (function_exists('mb_convert_encoding')) {
1316 $subst = mb_substitute_character();
1317 mb_substitute_character('none');
1318 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1319 mb_substitute_character($subst);
1321 } else {
1322 // Warn admins on admin/index.php page.
1323 $result = $value;
1326 } else {
1327 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1330 return $result;
1332 } else if (is_array($value)) {
1333 foreach ($value as $k => $v) {
1334 $value[$k] = fix_utf8($v);
1336 return $value;
1338 } else if (is_object($value)) {
1339 // Do not modify original.
1340 $value = clone($value);
1341 foreach ($value as $k => $v) {
1342 $value->$k = fix_utf8($v);
1344 return $value;
1346 } else {
1347 // This is some other type, no utf-8 here.
1348 return $value;
1353 * Return true if given value is integer or string with integer value
1355 * @param mixed $value String or Int
1356 * @return bool true if number, false if not
1358 function is_number($value) {
1359 if (is_int($value)) {
1360 return true;
1361 } else if (is_string($value)) {
1362 return ((string)(int)$value) === $value;
1363 } else {
1364 return false;
1369 * Returns host part from url.
1371 * @param string $url full url
1372 * @return string host, null if not found
1374 function get_host_from_url($url) {
1375 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1376 if ($matches) {
1377 return $matches[1];
1379 return null;
1383 * Tests whether anything was returned by text editor
1385 * This function is useful for testing whether something you got back from
1386 * the HTML editor actually contains anything. Sometimes the HTML editor
1387 * appear to be empty, but actually you get back a <br> tag or something.
1389 * @param string $string a string containing HTML.
1390 * @return boolean does the string contain any actual content - that is text,
1391 * images, objects, etc.
1393 function html_is_blank($string) {
1394 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1398 * Set a key in global configuration
1400 * Set a key/value pair in both this session's {@link $CFG} global variable
1401 * and in the 'config' database table for future sessions.
1403 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1404 * In that case it doesn't affect $CFG.
1406 * A NULL value will delete the entry.
1408 * NOTE: this function is called from lib/db/upgrade.php
1410 * @param string $name the key to set
1411 * @param string $value the value to set (without magic quotes)
1412 * @param string $plugin (optional) the plugin scope, default null
1413 * @return bool true or exception
1415 function set_config($name, $value, $plugin=null) {
1416 global $CFG, $DB;
1418 if (empty($plugin)) {
1419 if (!array_key_exists($name, $CFG->config_php_settings)) {
1420 // So it's defined for this invocation at least.
1421 if (is_null($value)) {
1422 unset($CFG->$name);
1423 } else {
1424 // Settings from db are always strings.
1425 $CFG->$name = (string)$value;
1429 if ($DB->get_field('config', 'name', array('name' => $name))) {
1430 if ($value === null) {
1431 $DB->delete_records('config', array('name' => $name));
1432 } else {
1433 $DB->set_field('config', 'value', $value, array('name' => $name));
1435 } else {
1436 if ($value !== null) {
1437 $config = new stdClass();
1438 $config->name = $name;
1439 $config->value = $value;
1440 $DB->insert_record('config', $config, false);
1442 // When setting config during a Behat test (in the CLI script, not in the web browser
1443 // requests), remember which ones are set so that we can clear them later.
1444 if (defined('BEHAT_TEST')) {
1445 if (!property_exists($CFG, 'behat_cli_added_config')) {
1446 $CFG->behat_cli_added_config = [];
1448 $CFG->behat_cli_added_config[$name] = true;
1451 if ($name === 'siteidentifier') {
1452 cache_helper::update_site_identifier($value);
1454 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1455 } else {
1456 // Plugin scope.
1457 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1458 if ($value===null) {
1459 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1460 } else {
1461 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1463 } else {
1464 if ($value !== null) {
1465 $config = new stdClass();
1466 $config->plugin = $plugin;
1467 $config->name = $name;
1468 $config->value = $value;
1469 $DB->insert_record('config_plugins', $config, false);
1472 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1475 return true;
1479 * Get configuration values from the global config table
1480 * or the config_plugins table.
1482 * If called with one parameter, it will load all the config
1483 * variables for one plugin, and return them as an object.
1485 * If called with 2 parameters it will return a string single
1486 * value or false if the value is not found.
1488 * NOTE: this function is called from lib/db/upgrade.php
1490 * @param string $plugin full component name
1491 * @param string $name default null
1492 * @return mixed hash-like object or single value, return false no config found
1493 * @throws dml_exception
1495 function get_config($plugin, $name = null) {
1496 global $CFG, $DB;
1498 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1499 $forced =& $CFG->config_php_settings;
1500 $iscore = true;
1501 $plugin = 'core';
1502 } else {
1503 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1504 $forced =& $CFG->forced_plugin_settings[$plugin];
1505 } else {
1506 $forced = array();
1508 $iscore = false;
1511 if (!isset($CFG->siteidentifier)) {
1512 try {
1513 // This may throw an exception during installation, which is how we detect the
1514 // need to install the database. For more details see {@see initialise_cfg()}.
1515 $CFG->siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1516 } catch (dml_exception $ex) {
1517 // Set siteidentifier to false. We don't want to trip this continually.
1518 $siteidentifier = false;
1519 throw $ex;
1523 if (!empty($name)) {
1524 if (array_key_exists($name, $forced)) {
1525 return (string)$forced[$name];
1526 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1527 return $CFG->siteidentifier;
1531 $cache = cache::make('core', 'config');
1532 $result = $cache->get($plugin);
1533 if ($result === false) {
1534 // The user is after a recordset.
1535 if (!$iscore) {
1536 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1537 } else {
1538 // This part is not really used any more, but anyway...
1539 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1541 $cache->set($plugin, $result);
1544 if (!empty($name)) {
1545 if (array_key_exists($name, $result)) {
1546 return $result[$name];
1548 return false;
1551 if ($plugin === 'core') {
1552 $result['siteidentifier'] = $CFG->siteidentifier;
1555 foreach ($forced as $key => $value) {
1556 if (is_null($value) or is_array($value) or is_object($value)) {
1557 // We do not want any extra mess here, just real settings that could be saved in db.
1558 unset($result[$key]);
1559 } else {
1560 // Convert to string as if it went through the DB.
1561 $result[$key] = (string)$value;
1565 return (object)$result;
1569 * Removes a key from global configuration.
1571 * NOTE: this function is called from lib/db/upgrade.php
1573 * @param string $name the key to set
1574 * @param string $plugin (optional) the plugin scope
1575 * @return boolean whether the operation succeeded.
1577 function unset_config($name, $plugin=null) {
1578 global $CFG, $DB;
1580 if (empty($plugin)) {
1581 unset($CFG->$name);
1582 $DB->delete_records('config', array('name' => $name));
1583 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1584 } else {
1585 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1586 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1589 return true;
1593 * Remove all the config variables for a given plugin.
1595 * NOTE: this function is called from lib/db/upgrade.php
1597 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1598 * @return boolean whether the operation succeeded.
1600 function unset_all_config_for_plugin($plugin) {
1601 global $DB;
1602 // Delete from the obvious config_plugins first.
1603 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1604 // Next delete any suspect settings from config.
1605 $like = $DB->sql_like('name', '?', true, true, false, '|');
1606 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1607 $DB->delete_records_select('config', $like, $params);
1608 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1609 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1611 return true;
1615 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1617 * All users are verified if they still have the necessary capability.
1619 * @param string $value the value of the config setting.
1620 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1621 * @param bool $includeadmins include administrators.
1622 * @return array of user objects.
1624 function get_users_from_config($value, $capability, $includeadmins = true) {
1625 if (empty($value) or $value === '$@NONE@$') {
1626 return array();
1629 // We have to make sure that users still have the necessary capability,
1630 // it should be faster to fetch them all first and then test if they are present
1631 // instead of validating them one-by-one.
1632 $users = get_users_by_capability(context_system::instance(), $capability);
1633 if ($includeadmins) {
1634 $admins = get_admins();
1635 foreach ($admins as $admin) {
1636 $users[$admin->id] = $admin;
1640 if ($value === '$@ALL@$') {
1641 return $users;
1644 $result = array(); // Result in correct order.
1645 $allowed = explode(',', $value);
1646 foreach ($allowed as $uid) {
1647 if (isset($users[$uid])) {
1648 $user = $users[$uid];
1649 $result[$user->id] = $user;
1653 return $result;
1658 * Invalidates browser caches and cached data in temp.
1660 * @return void
1662 function purge_all_caches() {
1663 purge_caches();
1667 * Selectively invalidate different types of cache.
1669 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1670 * areas alone or in combination.
1672 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1673 * 'muc' Purge MUC caches?
1674 * 'theme' Purge theme cache?
1675 * 'lang' Purge language string cache?
1676 * 'js' Purge javascript cache?
1677 * 'filter' Purge text filter cache?
1678 * 'other' Purge all other caches?
1680 function purge_caches($options = []) {
1681 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1682 if (empty(array_filter($options))) {
1683 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1684 } else {
1685 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1687 if ($options['muc']) {
1688 cache_helper::purge_all();
1690 if ($options['theme']) {
1691 theme_reset_all_caches();
1693 if ($options['lang']) {
1694 get_string_manager()->reset_caches();
1696 if ($options['js']) {
1697 js_reset_all_caches();
1699 if ($options['template']) {
1700 template_reset_all_caches();
1702 if ($options['filter']) {
1703 reset_text_filters_cache();
1705 if ($options['other']) {
1706 purge_other_caches();
1711 * Purge all non-MUC caches not otherwise purged in purge_caches.
1713 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1714 * {@link phpunit_util::reset_dataroot()}
1716 function purge_other_caches() {
1717 global $DB, $CFG;
1718 if (class_exists('core_plugin_manager')) {
1719 core_plugin_manager::reset_caches();
1722 // Bump up cacherev field for all courses.
1723 try {
1724 increment_revision_number('course', 'cacherev', '');
1725 } catch (moodle_exception $e) {
1726 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1729 $DB->reset_caches();
1731 // Purge all other caches: rss, simplepie, etc.
1732 clearstatcache();
1733 remove_dir($CFG->cachedir.'', true);
1735 // Make sure cache dir is writable, throws exception if not.
1736 make_cache_directory('');
1738 // This is the only place where we purge local caches, we are only adding files there.
1739 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1740 remove_dir($CFG->localcachedir, true);
1741 set_config('localcachedirpurged', time());
1742 make_localcache_directory('', true);
1743 \core\task\manager::clear_static_caches();
1747 * Get volatile flags
1749 * @param string $type
1750 * @param int $changedsince default null
1751 * @return array records array
1753 function get_cache_flags($type, $changedsince = null) {
1754 global $DB;
1756 $params = array('type' => $type, 'expiry' => time());
1757 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1758 if ($changedsince !== null) {
1759 $params['changedsince'] = $changedsince;
1760 $sqlwhere .= " AND timemodified > :changedsince";
1762 $cf = array();
1763 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1764 foreach ($flags as $flag) {
1765 $cf[$flag->name] = $flag->value;
1768 return $cf;
1772 * Get volatile flags
1774 * @param string $type
1775 * @param string $name
1776 * @param int $changedsince default null
1777 * @return string|false The cache flag value or false
1779 function get_cache_flag($type, $name, $changedsince=null) {
1780 global $DB;
1782 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1784 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1785 if ($changedsince !== null) {
1786 $params['changedsince'] = $changedsince;
1787 $sqlwhere .= " AND timemodified > :changedsince";
1790 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1794 * Set a volatile flag
1796 * @param string $type the "type" namespace for the key
1797 * @param string $name the key to set
1798 * @param string $value the value to set (without magic quotes) - null will remove the flag
1799 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1800 * @return bool Always returns true
1802 function set_cache_flag($type, $name, $value, $expiry = null) {
1803 global $DB;
1805 $timemodified = time();
1806 if ($expiry === null || $expiry < $timemodified) {
1807 $expiry = $timemodified + 24 * 60 * 60;
1808 } else {
1809 $expiry = (int)$expiry;
1812 if ($value === null) {
1813 unset_cache_flag($type, $name);
1814 return true;
1817 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1818 // This is a potential problem in DEBUG_DEVELOPER.
1819 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1820 return true; // No need to update.
1822 $f->value = $value;
1823 $f->expiry = $expiry;
1824 $f->timemodified = $timemodified;
1825 $DB->update_record('cache_flags', $f);
1826 } else {
1827 $f = new stdClass();
1828 $f->flagtype = $type;
1829 $f->name = $name;
1830 $f->value = $value;
1831 $f->expiry = $expiry;
1832 $f->timemodified = $timemodified;
1833 $DB->insert_record('cache_flags', $f);
1835 return true;
1839 * Removes a single volatile flag
1841 * @param string $type the "type" namespace for the key
1842 * @param string $name the key to set
1843 * @return bool
1845 function unset_cache_flag($type, $name) {
1846 global $DB;
1847 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1848 return true;
1852 * Garbage-collect volatile flags
1854 * @return bool Always returns true
1856 function gc_cache_flags() {
1857 global $DB;
1858 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1859 return true;
1862 // USER PREFERENCE API.
1865 * Refresh user preference cache. This is used most often for $USER
1866 * object that is stored in session, but it also helps with performance in cron script.
1868 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1870 * @package core
1871 * @category preference
1872 * @access public
1873 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1874 * @param int $cachelifetime Cache life time on the current page (in seconds)
1875 * @throws coding_exception
1876 * @return null
1878 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1879 global $DB;
1880 // Static cache, we need to check on each page load, not only every 2 minutes.
1881 static $loadedusers = array();
1883 if (!isset($user->id)) {
1884 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1887 if (empty($user->id) or isguestuser($user->id)) {
1888 // No permanent storage for not-logged-in users and guest.
1889 if (!isset($user->preference)) {
1890 $user->preference = array();
1892 return;
1895 $timenow = time();
1897 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1898 // Already loaded at least once on this page. Are we up to date?
1899 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1900 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1901 return;
1903 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1904 // No change since the lastcheck on this page.
1905 $user->preference['_lastloaded'] = $timenow;
1906 return;
1910 // OK, so we have to reload all preferences.
1911 $loadedusers[$user->id] = true;
1912 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1913 $user->preference['_lastloaded'] = $timenow;
1917 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1919 * NOTE: internal function, do not call from other code.
1921 * @package core
1922 * @access private
1923 * @param integer $userid the user whose prefs were changed.
1925 function mark_user_preferences_changed($userid) {
1926 global $CFG;
1928 if (empty($userid) or isguestuser($userid)) {
1929 // No cache flags for guest and not-logged-in users.
1930 return;
1933 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1937 * Sets a preference for the specified user.
1939 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1941 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1943 * @package core
1944 * @category preference
1945 * @access public
1946 * @param string $name The key to set as preference for the specified user
1947 * @param string $value The value to set for the $name key in the specified user's
1948 * record, null means delete current value.
1949 * @param stdClass|int|null $user A moodle user object or id, null means current user
1950 * @throws coding_exception
1951 * @return bool Always true or exception
1953 function set_user_preference($name, $value, $user = null) {
1954 global $USER, $DB;
1956 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1957 throw new coding_exception('Invalid preference name in set_user_preference() call');
1960 if (is_null($value)) {
1961 // Null means delete current.
1962 return unset_user_preference($name, $user);
1963 } else if (is_object($value)) {
1964 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1965 } else if (is_array($value)) {
1966 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1968 // Value column maximum length is 1333 characters.
1969 $value = (string)$value;
1970 if (core_text::strlen($value) > 1333) {
1971 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1974 if (is_null($user)) {
1975 $user = $USER;
1976 } else if (isset($user->id)) {
1977 // It is a valid object.
1978 } else if (is_numeric($user)) {
1979 $user = (object)array('id' => (int)$user);
1980 } else {
1981 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1984 check_user_preferences_loaded($user);
1986 if (empty($user->id) or isguestuser($user->id)) {
1987 // No permanent storage for not-logged-in users and guest.
1988 $user->preference[$name] = $value;
1989 return true;
1992 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1993 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1994 // Preference already set to this value.
1995 return true;
1997 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1999 } else {
2000 $preference = new stdClass();
2001 $preference->userid = $user->id;
2002 $preference->name = $name;
2003 $preference->value = $value;
2004 $DB->insert_record('user_preferences', $preference);
2007 // Update value in cache.
2008 $user->preference[$name] = $value;
2009 // Update the $USER in case where we've not a direct reference to $USER.
2010 if ($user !== $USER && $user->id == $USER->id) {
2011 $USER->preference[$name] = $value;
2014 // Set reload flag for other sessions.
2015 mark_user_preferences_changed($user->id);
2017 return true;
2021 * Sets a whole array of preferences for the current user
2023 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2025 * @package core
2026 * @category preference
2027 * @access public
2028 * @param array $prefarray An array of key/value pairs to be set
2029 * @param stdClass|int|null $user A moodle user object or id, null means current user
2030 * @return bool Always true or exception
2032 function set_user_preferences(array $prefarray, $user = null) {
2033 foreach ($prefarray as $name => $value) {
2034 set_user_preference($name, $value, $user);
2036 return true;
2040 * Unsets a preference completely by deleting it from the database
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 string $name The key to unset as preference for the specified user
2048 * @param stdClass|int|null $user A moodle user object or id, null means current user
2049 * @throws coding_exception
2050 * @return bool Always true or exception
2052 function unset_user_preference($name, $user = null) {
2053 global $USER, $DB;
2055 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2056 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2059 if (is_null($user)) {
2060 $user = $USER;
2061 } else if (isset($user->id)) {
2062 // It is a valid object.
2063 } else if (is_numeric($user)) {
2064 $user = (object)array('id' => (int)$user);
2065 } else {
2066 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2069 check_user_preferences_loaded($user);
2071 if (empty($user->id) or isguestuser($user->id)) {
2072 // No permanent storage for not-logged-in user and guest.
2073 unset($user->preference[$name]);
2074 return true;
2077 // Delete from DB.
2078 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2080 // Delete the preference from cache.
2081 unset($user->preference[$name]);
2082 // Update the $USER in case where we've not a direct reference to $USER.
2083 if ($user !== $USER && $user->id == $USER->id) {
2084 unset($USER->preference[$name]);
2087 // Set reload flag for other sessions.
2088 mark_user_preferences_changed($user->id);
2090 return true;
2094 * Used to fetch user preference(s)
2096 * If no arguments are supplied this function will return
2097 * all of the current user preferences as an array.
2099 * If a name is specified then this function
2100 * attempts to return that particular preference value. If
2101 * none is found, then the optional value $default is returned,
2102 * otherwise null.
2104 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2106 * @package core
2107 * @category preference
2108 * @access public
2109 * @param string $name Name of the key to use in finding a preference value
2110 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2111 * @param stdClass|int|null $user A moodle user object or id, null means current user
2112 * @throws coding_exception
2113 * @return string|mixed|null A string containing the value of a single preference. An
2114 * array with all of the preferences or null
2116 function get_user_preferences($name = null, $default = null, $user = null) {
2117 global $USER;
2119 if (is_null($name)) {
2120 // All prefs.
2121 } else if (is_numeric($name) or $name === '_lastloaded') {
2122 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2125 if (is_null($user)) {
2126 $user = $USER;
2127 } else if (isset($user->id)) {
2128 // Is a valid object.
2129 } else if (is_numeric($user)) {
2130 if ($USER->id == $user) {
2131 $user = $USER;
2132 } else {
2133 $user = (object)array('id' => (int)$user);
2135 } else {
2136 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2139 check_user_preferences_loaded($user);
2141 if (empty($name)) {
2142 // All values.
2143 return $user->preference;
2144 } else if (isset($user->preference[$name])) {
2145 // The single string value.
2146 return $user->preference[$name];
2147 } else {
2148 // Default value (null if not specified).
2149 return $default;
2153 // FUNCTIONS FOR HANDLING TIME.
2156 * Given Gregorian date parts in user time produce a GMT timestamp.
2158 * @package core
2159 * @category time
2160 * @param int $year The year part to create timestamp of
2161 * @param int $month The month part to create timestamp of
2162 * @param int $day The day part to create timestamp of
2163 * @param int $hour The hour part to create timestamp of
2164 * @param int $minute The minute part to create timestamp of
2165 * @param int $second The second part to create timestamp of
2166 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2167 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2168 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2169 * applied only if timezone is 99 or string.
2170 * @return int GMT timestamp
2172 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2173 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2174 $date->setDate((int)$year, (int)$month, (int)$day);
2175 $date->setTime((int)$hour, (int)$minute, (int)$second);
2177 $time = $date->getTimestamp();
2179 if ($time === false) {
2180 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2181 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2184 // Moodle BC DST stuff.
2185 if (!$applydst) {
2186 $time += dst_offset_on($time, $timezone);
2189 return $time;
2194 * Format a date/time (seconds) as weeks, days, hours etc as needed
2196 * Given an amount of time in seconds, returns string
2197 * formatted nicely as years, days, hours etc as needed
2199 * @package core
2200 * @category time
2201 * @uses MINSECS
2202 * @uses HOURSECS
2203 * @uses DAYSECS
2204 * @uses YEARSECS
2205 * @param int $totalsecs Time in seconds
2206 * @param stdClass $str Should be a time object
2207 * @return string A nicely formatted date/time string
2209 function format_time($totalsecs, $str = null) {
2211 $totalsecs = abs($totalsecs);
2213 if (!$str) {
2214 // Create the str structure the slow way.
2215 $str = new stdClass();
2216 $str->day = get_string('day');
2217 $str->days = get_string('days');
2218 $str->hour = get_string('hour');
2219 $str->hours = get_string('hours');
2220 $str->min = get_string('min');
2221 $str->mins = get_string('mins');
2222 $str->sec = get_string('sec');
2223 $str->secs = get_string('secs');
2224 $str->year = get_string('year');
2225 $str->years = get_string('years');
2228 $years = floor($totalsecs/YEARSECS);
2229 $remainder = $totalsecs - ($years*YEARSECS);
2230 $days = floor($remainder/DAYSECS);
2231 $remainder = $totalsecs - ($days*DAYSECS);
2232 $hours = floor($remainder/HOURSECS);
2233 $remainder = $remainder - ($hours*HOURSECS);
2234 $mins = floor($remainder/MINSECS);
2235 $secs = $remainder - ($mins*MINSECS);
2237 $ss = ($secs == 1) ? $str->sec : $str->secs;
2238 $sm = ($mins == 1) ? $str->min : $str->mins;
2239 $sh = ($hours == 1) ? $str->hour : $str->hours;
2240 $sd = ($days == 1) ? $str->day : $str->days;
2241 $sy = ($years == 1) ? $str->year : $str->years;
2243 $oyears = '';
2244 $odays = '';
2245 $ohours = '';
2246 $omins = '';
2247 $osecs = '';
2249 if ($years) {
2250 $oyears = $years .' '. $sy;
2252 if ($days) {
2253 $odays = $days .' '. $sd;
2255 if ($hours) {
2256 $ohours = $hours .' '. $sh;
2258 if ($mins) {
2259 $omins = $mins .' '. $sm;
2261 if ($secs) {
2262 $osecs = $secs .' '. $ss;
2265 if ($years) {
2266 return trim($oyears .' '. $odays);
2268 if ($days) {
2269 return trim($odays .' '. $ohours);
2271 if ($hours) {
2272 return trim($ohours .' '. $omins);
2274 if ($mins) {
2275 return trim($omins .' '. $osecs);
2277 if ($secs) {
2278 return $osecs;
2280 return get_string('now');
2284 * Returns a formatted string that represents a date in user time.
2286 * @package core
2287 * @category time
2288 * @param int $date the timestamp in UTC, as obtained from the database.
2289 * @param string $format strftime format. You should probably get this using
2290 * get_string('strftime...', 'langconfig');
2291 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2292 * not 99 then daylight saving will not be added.
2293 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2294 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2295 * If false then the leading zero is maintained.
2296 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2297 * @return string the formatted date/time.
2299 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2300 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2301 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2305 * Returns a html "time" tag with both the exact user date with timezone information
2306 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2308 * @package core
2309 * @category time
2310 * @param int $date the timestamp in UTC, as obtained from the database.
2311 * @param string $format strftime format. You should probably get this using
2312 * get_string('strftime...', 'langconfig');
2313 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2314 * not 99 then daylight saving will not be added.
2315 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2316 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2317 * If false then the leading zero is maintained.
2318 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2319 * @return string the formatted date/time.
2321 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2322 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2323 if (CLI_SCRIPT && !PHPUNIT_TEST) {
2324 return $userdatestr;
2326 $machinedate = new DateTime();
2327 $machinedate->setTimestamp(intval($date));
2328 $machinedate->setTimezone(core_date::get_user_timezone_object());
2330 return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2334 * Returns a formatted date ensuring it is UTF-8.
2336 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2337 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2339 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2340 * @param string $format strftime format.
2341 * @param int|float|string $tz the user timezone
2342 * @return string the formatted date/time.
2343 * @since Moodle 2.3.3
2345 function date_format_string($date, $format, $tz = 99) {
2346 global $CFG;
2348 $localewincharset = null;
2349 // Get the calendar type user is using.
2350 if ($CFG->ostype == 'WINDOWS') {
2351 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2352 $localewincharset = $calendartype->locale_win_charset();
2355 if ($localewincharset) {
2356 $format = core_text::convert($format, 'utf-8', $localewincharset);
2359 date_default_timezone_set(core_date::get_user_timezone($tz));
2361 if (strftime('%p', 0) === strftime('%p', HOURSECS * 18)) {
2362 $datearray = getdate($date);
2363 $format = str_replace([
2364 '%P',
2365 '%p',
2366 ], [
2367 $datearray['hours'] < 12 ? get_string('am', 'langconfig') : get_string('pm', 'langconfig'),
2368 $datearray['hours'] < 12 ? get_string('amcaps', 'langconfig') : get_string('pmcaps', 'langconfig'),
2369 ], $format);
2372 $datestring = strftime($format, $date);
2373 core_date::set_default_server_timezone();
2375 if ($localewincharset) {
2376 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2379 return $datestring;
2383 * Given a $time timestamp in GMT (seconds since epoch),
2384 * returns an array that represents the Gregorian date in user time
2386 * @package core
2387 * @category time
2388 * @param int $time Timestamp in GMT
2389 * @param float|int|string $timezone user timezone
2390 * @return array An array that represents the date in user time
2392 function usergetdate($time, $timezone=99) {
2393 if ($time === null) {
2394 // PHP8 and PHP7 return different results when getdate(null) is called.
2395 // Display warning and cast to 0 to make sure the usergetdate() behaves consistently on all versions of PHP.
2396 // In the future versions of Moodle we may consider adding a strict typehint.
2397 debugging('usergetdate() expects parameter $time to be int, null given', DEBUG_DEVELOPER);
2398 $time = 0;
2401 date_default_timezone_set(core_date::get_user_timezone($timezone));
2402 $result = getdate($time);
2403 core_date::set_default_server_timezone();
2405 return $result;
2409 * Given a GMT timestamp (seconds since epoch), offsets it by
2410 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2412 * NOTE: this function does not include DST properly,
2413 * you should use the PHP date stuff instead!
2415 * @package core
2416 * @category time
2417 * @param int $date Timestamp in GMT
2418 * @param float|int|string $timezone user timezone
2419 * @return int
2421 function usertime($date, $timezone=99) {
2422 $userdate = new DateTime('@' . $date);
2423 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2424 $dst = dst_offset_on($date, $timezone);
2426 return $date - $userdate->getOffset() + $dst;
2430 * Get a formatted string representation of an interval between two unix timestamps.
2432 * E.g.
2433 * $intervalstring = get_time_interval_string(12345600, 12345660);
2434 * Will produce the string:
2435 * '0d 0h 1m'
2437 * @param int $time1 unix timestamp
2438 * @param int $time2 unix timestamp
2439 * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2440 * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2442 function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
2443 $dtdate = new DateTime();
2444 $dtdate->setTimeStamp($time1);
2445 $dtdate2 = new DateTime();
2446 $dtdate2->setTimeStamp($time2);
2447 $interval = $dtdate2->diff($dtdate);
2448 $format = empty($format) ? get_string('dateintervaldayshoursmins', 'langconfig') : $format;
2449 return $interval->format($format);
2453 * Given a time, return the GMT timestamp of the most recent midnight
2454 * for the current user.
2456 * @package core
2457 * @category time
2458 * @param int $date Timestamp in GMT
2459 * @param float|int|string $timezone user timezone
2460 * @return int Returns a GMT timestamp
2462 function usergetmidnight($date, $timezone=99) {
2464 $userdate = usergetdate($date, $timezone);
2466 // Time of midnight of this user's day, in GMT.
2467 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2472 * Returns a string that prints the user's timezone
2474 * @package core
2475 * @category time
2476 * @param float|int|string $timezone user timezone
2477 * @return string
2479 function usertimezone($timezone=99) {
2480 $tz = core_date::get_user_timezone($timezone);
2481 return core_date::get_localised_timezone($tz);
2485 * Returns a float or a string which denotes the user's timezone
2486 * 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)
2487 * means that for this timezone there are also DST rules to be taken into account
2488 * Checks various settings and picks the most dominant of those which have a value
2490 * @package core
2491 * @category time
2492 * @param float|int|string $tz timezone to calculate GMT time offset before
2493 * calculating user timezone, 99 is default user timezone
2494 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2495 * @return float|string
2497 function get_user_timezone($tz = 99) {
2498 global $USER, $CFG;
2500 $timezones = array(
2501 $tz,
2502 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2503 isset($USER->timezone) ? $USER->timezone : 99,
2504 isset($CFG->timezone) ? $CFG->timezone : 99,
2507 $tz = 99;
2509 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2510 foreach ($timezones as $nextvalue) {
2511 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2512 $tz = $nextvalue;
2515 return is_numeric($tz) ? (float) $tz : $tz;
2519 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2520 * - Note: Daylight saving only works for string timezones and not for float.
2522 * @package core
2523 * @category time
2524 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2525 * @param int|float|string $strtimezone user timezone
2526 * @return int
2528 function dst_offset_on($time, $strtimezone = null) {
2529 $tz = core_date::get_user_timezone($strtimezone);
2530 $date = new DateTime('@' . $time);
2531 $date->setTimezone(new DateTimeZone($tz));
2532 if ($date->format('I') == '1') {
2533 if ($tz === 'Australia/Lord_Howe') {
2534 return 1800;
2536 return 3600;
2538 return 0;
2542 * Calculates when the day appears in specific month
2544 * @package core
2545 * @category time
2546 * @param int $startday starting day of the month
2547 * @param int $weekday The day when week starts (normally taken from user preferences)
2548 * @param int $month The month whose day is sought
2549 * @param int $year The year of the month whose day is sought
2550 * @return int
2552 function find_day_in_month($startday, $weekday, $month, $year) {
2553 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2555 $daysinmonth = days_in_month($month, $year);
2556 $daysinweek = count($calendartype->get_weekdays());
2558 if ($weekday == -1) {
2559 // Don't care about weekday, so return:
2560 // abs($startday) if $startday != -1
2561 // $daysinmonth otherwise.
2562 return ($startday == -1) ? $daysinmonth : abs($startday);
2565 // From now on we 're looking for a specific weekday.
2566 // Give "end of month" its actual value, since we know it.
2567 if ($startday == -1) {
2568 $startday = -1 * $daysinmonth;
2571 // Starting from day $startday, the sign is the direction.
2572 if ($startday < 1) {
2573 $startday = abs($startday);
2574 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2576 // This is the last such weekday of the month.
2577 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2578 if ($lastinmonth > $daysinmonth) {
2579 $lastinmonth -= $daysinweek;
2582 // Find the first such weekday <= $startday.
2583 while ($lastinmonth > $startday) {
2584 $lastinmonth -= $daysinweek;
2587 return $lastinmonth;
2588 } else {
2589 $indexweekday = dayofweek($startday, $month, $year);
2591 $diff = $weekday - $indexweekday;
2592 if ($diff < 0) {
2593 $diff += $daysinweek;
2596 // This is the first such weekday of the month equal to or after $startday.
2597 $firstfromindex = $startday + $diff;
2599 return $firstfromindex;
2604 * Calculate the number of days in a given month
2606 * @package core
2607 * @category time
2608 * @param int $month The month whose day count is sought
2609 * @param int $year The year of the month whose day count is sought
2610 * @return int
2612 function days_in_month($month, $year) {
2613 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2614 return $calendartype->get_num_days_in_month($year, $month);
2618 * Calculate the position in the week of a specific calendar day
2620 * @package core
2621 * @category time
2622 * @param int $day The day of the date whose position in the week is sought
2623 * @param int $month The month of the date whose position in the week is sought
2624 * @param int $year The year of the date whose position in the week is sought
2625 * @return int
2627 function dayofweek($day, $month, $year) {
2628 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2629 return $calendartype->get_weekday($year, $month, $day);
2632 // USER AUTHENTICATION AND LOGIN.
2635 * Returns full login url.
2637 * Any form submissions for authentication to this URL must include username,
2638 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2640 * @return string login url
2642 function get_login_url() {
2643 global $CFG;
2645 return "$CFG->wwwroot/login/index.php";
2649 * This function checks that the current user is logged in and has the
2650 * required privileges
2652 * This function checks that the current user is logged in, and optionally
2653 * whether they are allowed to be in a particular course and view a particular
2654 * course module.
2655 * If they are not logged in, then it redirects them to the site login unless
2656 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2657 * case they are automatically logged in as guests.
2658 * If $courseid is given and the user is not enrolled in that course then the
2659 * user is redirected to the course enrolment page.
2660 * If $cm is given and the course module is hidden and the user is not a teacher
2661 * in the course then the user is redirected to the course home page.
2663 * When $cm parameter specified, this function sets page layout to 'module'.
2664 * You need to change it manually later if some other layout needed.
2666 * @package core_access
2667 * @category access
2669 * @param mixed $courseorid id of the course or course object
2670 * @param bool $autologinguest default true
2671 * @param object $cm course module object
2672 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2673 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2674 * in order to keep redirects working properly. MDL-14495
2675 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2676 * @return mixed Void, exit, and die depending on path
2677 * @throws coding_exception
2678 * @throws require_login_exception
2679 * @throws moodle_exception
2681 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2682 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2684 // Must not redirect when byteserving already started.
2685 if (!empty($_SERVER['HTTP_RANGE'])) {
2686 $preventredirect = true;
2689 if (AJAX_SCRIPT) {
2690 // We cannot redirect for AJAX scripts either.
2691 $preventredirect = true;
2694 // Setup global $COURSE, themes, language and locale.
2695 if (!empty($courseorid)) {
2696 if (is_object($courseorid)) {
2697 $course = $courseorid;
2698 } else if ($courseorid == SITEID) {
2699 $course = clone($SITE);
2700 } else {
2701 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2703 if ($cm) {
2704 if ($cm->course != $course->id) {
2705 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2707 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2708 if (!($cm instanceof cm_info)) {
2709 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2710 // db queries so this is not really a performance concern, however it is obviously
2711 // better if you use get_fast_modinfo to get the cm before calling this.
2712 $modinfo = get_fast_modinfo($course);
2713 $cm = $modinfo->get_cm($cm->id);
2716 } else {
2717 // Do not touch global $COURSE via $PAGE->set_course(),
2718 // the reasons is we need to be able to call require_login() at any time!!
2719 $course = $SITE;
2720 if ($cm) {
2721 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2725 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2726 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2727 // risk leading the user back to the AJAX request URL.
2728 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2729 $setwantsurltome = false;
2732 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2733 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2734 if ($preventredirect) {
2735 throw new require_login_session_timeout_exception();
2736 } else {
2737 if ($setwantsurltome) {
2738 $SESSION->wantsurl = qualified_me();
2740 redirect(get_login_url());
2744 // If the user is not even logged in yet then make sure they are.
2745 if (!isloggedin()) {
2746 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2747 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2748 // Misconfigured site guest, just redirect to login page.
2749 redirect(get_login_url());
2750 exit; // Never reached.
2752 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2753 complete_user_login($guest);
2754 $USER->autologinguest = true;
2755 $SESSION->lang = $lang;
2756 } else {
2757 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2758 if ($preventredirect) {
2759 throw new require_login_exception('You are not logged in');
2762 if ($setwantsurltome) {
2763 $SESSION->wantsurl = qualified_me();
2766 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2767 $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
2768 foreach($authsequence as $authname) {
2769 $authplugin = get_auth_plugin($authname);
2770 $authplugin->pre_loginpage_hook();
2771 if (isloggedin()) {
2772 if ($cm) {
2773 $modinfo = get_fast_modinfo($course);
2774 $cm = $modinfo->get_cm($cm->id);
2776 set_access_log_user();
2777 break;
2781 // If we're still not logged in then go to the login page
2782 if (!isloggedin()) {
2783 redirect(get_login_url());
2784 exit; // Never reached.
2789 // Loginas as redirection if needed.
2790 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2791 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2792 if ($USER->loginascontext->instanceid != $course->id) {
2793 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2798 // Check whether the user should be changing password (but only if it is REALLY them).
2799 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2800 $userauth = get_auth_plugin($USER->auth);
2801 if ($userauth->can_change_password() and !$preventredirect) {
2802 if ($setwantsurltome) {
2803 $SESSION->wantsurl = qualified_me();
2805 if ($changeurl = $userauth->change_password_url()) {
2806 // Use plugin custom url.
2807 redirect($changeurl);
2808 } else {
2809 // Use moodle internal method.
2810 redirect($CFG->wwwroot .'/login/change_password.php');
2812 } else if ($userauth->can_change_password()) {
2813 throw new moodle_exception('forcepasswordchangenotice');
2814 } else {
2815 throw new moodle_exception('nopasswordchangeforced', 'auth');
2819 // Check that the user account is properly set up. If we can't redirect to
2820 // edit their profile and this is not a WS request, perform just the lax check.
2821 // It will allow them to use filepicker on the profile edit page.
2823 if ($preventredirect && !WS_SERVER) {
2824 $usernotfullysetup = user_not_fully_set_up($USER, false);
2825 } else {
2826 $usernotfullysetup = user_not_fully_set_up($USER, true);
2829 if ($usernotfullysetup) {
2830 if ($preventredirect) {
2831 throw new moodle_exception('usernotfullysetup');
2833 if ($setwantsurltome) {
2834 $SESSION->wantsurl = qualified_me();
2836 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2839 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2840 sesskey();
2842 if (\core\session\manager::is_loggedinas()) {
2843 // During a "logged in as" session we should force all content to be cleaned because the
2844 // logged in user will be viewing potentially malicious user generated content.
2845 // See MDL-63786 for more details.
2846 $CFG->forceclean = true;
2849 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2851 // Do not bother admins with any formalities, except for activities pending deletion.
2852 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2853 // Set the global $COURSE.
2854 if ($cm) {
2855 $PAGE->set_cm($cm, $course);
2856 $PAGE->set_pagelayout('incourse');
2857 } else if (!empty($courseorid)) {
2858 $PAGE->set_course($course);
2860 // Set accesstime or the user will appear offline which messes up messaging.
2861 // Do not update access time for webservice or ajax requests.
2862 if (!WS_SERVER && !AJAX_SCRIPT) {
2863 user_accesstime_log($course->id);
2866 foreach ($afterlogins as $plugintype => $plugins) {
2867 foreach ($plugins as $pluginfunction) {
2868 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2871 return;
2874 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2875 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2876 if (!defined('NO_SITEPOLICY_CHECK')) {
2877 define('NO_SITEPOLICY_CHECK', false);
2880 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2881 // Do not test if the script explicitly asked for skipping the site policies check.
2882 // Or if the user auth type is webservice.
2883 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK && $USER->auth !== 'webservice') {
2884 $manager = new \core_privacy\local\sitepolicy\manager();
2885 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2886 if ($preventredirect) {
2887 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2889 if ($setwantsurltome) {
2890 $SESSION->wantsurl = qualified_me();
2892 redirect($policyurl);
2896 // Fetch the system context, the course context, and prefetch its child contexts.
2897 $sysctx = context_system::instance();
2898 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2899 if ($cm) {
2900 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2901 } else {
2902 $cmcontext = null;
2905 // If the site is currently under maintenance, then print a message.
2906 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2907 if ($preventredirect) {
2908 throw new require_login_exception('Maintenance in progress');
2910 $PAGE->set_context(null);
2911 print_maintenance_message();
2914 // Make sure the course itself is not hidden.
2915 if ($course->id == SITEID) {
2916 // Frontpage can not be hidden.
2917 } else {
2918 if (is_role_switched($course->id)) {
2919 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2920 } else {
2921 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2922 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2923 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2924 if ($preventredirect) {
2925 throw new require_login_exception('Course is hidden');
2927 $PAGE->set_context(null);
2928 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2929 // the navigation will mess up when trying to find it.
2930 navigation_node::override_active_url(new moodle_url('/'));
2931 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2936 // Is the user enrolled?
2937 if ($course->id == SITEID) {
2938 // Everybody is enrolled on the frontpage.
2939 } else {
2940 if (\core\session\manager::is_loggedinas()) {
2941 // Make sure the REAL person can access this course first.
2942 $realuser = \core\session\manager::get_realuser();
2943 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2944 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2945 if ($preventredirect) {
2946 throw new require_login_exception('Invalid course login-as access');
2948 $PAGE->set_context(null);
2949 echo $OUTPUT->header();
2950 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2954 $access = false;
2956 if (is_role_switched($course->id)) {
2957 // Ok, user had to be inside this course before the switch.
2958 $access = true;
2960 } else if (is_viewing($coursecontext, $USER)) {
2961 // Ok, no need to mess with enrol.
2962 $access = true;
2964 } else {
2965 if (isset($USER->enrol['enrolled'][$course->id])) {
2966 if ($USER->enrol['enrolled'][$course->id] > time()) {
2967 $access = true;
2968 if (isset($USER->enrol['tempguest'][$course->id])) {
2969 unset($USER->enrol['tempguest'][$course->id]);
2970 remove_temp_course_roles($coursecontext);
2972 } else {
2973 // Expired.
2974 unset($USER->enrol['enrolled'][$course->id]);
2977 if (isset($USER->enrol['tempguest'][$course->id])) {
2978 if ($USER->enrol['tempguest'][$course->id] == 0) {
2979 $access = true;
2980 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2981 $access = true;
2982 } else {
2983 // Expired.
2984 unset($USER->enrol['tempguest'][$course->id]);
2985 remove_temp_course_roles($coursecontext);
2989 if (!$access) {
2990 // Cache not ok.
2991 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2992 if ($until !== false) {
2993 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2994 if ($until == 0) {
2995 $until = ENROL_MAX_TIMESTAMP;
2997 $USER->enrol['enrolled'][$course->id] = $until;
2998 $access = true;
3000 } else if (core_course_category::can_view_course_info($course)) {
3001 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
3002 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3003 $enrols = enrol_get_plugins(true);
3004 // First ask all enabled enrol instances in course if they want to auto enrol user.
3005 foreach ($instances as $instance) {
3006 if (!isset($enrols[$instance->enrol])) {
3007 continue;
3009 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3010 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3011 if ($until !== false) {
3012 if ($until == 0) {
3013 $until = ENROL_MAX_TIMESTAMP;
3015 $USER->enrol['enrolled'][$course->id] = $until;
3016 $access = true;
3017 break;
3020 // If not enrolled yet try to gain temporary guest access.
3021 if (!$access) {
3022 foreach ($instances as $instance) {
3023 if (!isset($enrols[$instance->enrol])) {
3024 continue;
3026 // Get a duration for the guest access, a timestamp in the future or false.
3027 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3028 if ($until !== false and $until > time()) {
3029 $USER->enrol['tempguest'][$course->id] = $until;
3030 $access = true;
3031 break;
3035 } else {
3036 // User is not enrolled and is not allowed to browse courses here.
3037 if ($preventredirect) {
3038 throw new require_login_exception('Course is not available');
3040 $PAGE->set_context(null);
3041 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3042 // the navigation will mess up when trying to find it.
3043 navigation_node::override_active_url(new moodle_url('/'));
3044 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3049 if (!$access) {
3050 if ($preventredirect) {
3051 throw new require_login_exception('Not enrolled');
3053 if ($setwantsurltome) {
3054 $SESSION->wantsurl = qualified_me();
3056 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3060 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3061 if ($cm && $cm->deletioninprogress) {
3062 if ($preventredirect) {
3063 throw new moodle_exception('activityisscheduledfordeletion');
3065 require_once($CFG->dirroot . '/course/lib.php');
3066 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3069 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3070 if ($cm && !$cm->uservisible) {
3071 if ($preventredirect) {
3072 throw new require_login_exception('Activity is hidden');
3074 // Get the error message that activity is not available and why (if explanation can be shown to the user).
3075 $PAGE->set_course($course);
3076 $renderer = $PAGE->get_renderer('course');
3077 $message = $renderer->course_section_cm_unavailable_error_message($cm);
3078 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
3081 // Set the global $COURSE.
3082 if ($cm) {
3083 $PAGE->set_cm($cm, $course);
3084 $PAGE->set_pagelayout('incourse');
3085 } else if (!empty($courseorid)) {
3086 $PAGE->set_course($course);
3089 foreach ($afterlogins as $plugintype => $plugins) {
3090 foreach ($plugins as $pluginfunction) {
3091 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3095 // Finally access granted, update lastaccess times.
3096 // Do not update access time for webservice or ajax requests.
3097 if (!WS_SERVER && !AJAX_SCRIPT) {
3098 user_accesstime_log($course->id);
3103 * A convenience function for where we must be logged in as admin
3104 * @return void
3106 function require_admin() {
3107 require_login(null, false);
3108 require_capability('moodle/site:config', context_system::instance());
3112 * This function just makes sure a user is logged out.
3114 * @package core_access
3115 * @category access
3117 function require_logout() {
3118 global $USER, $DB;
3120 if (!isloggedin()) {
3121 // This should not happen often, no need for hooks or events here.
3122 \core\session\manager::terminate_current();
3123 return;
3126 // Execute hooks before action.
3127 $authplugins = array();
3128 $authsequence = get_enabled_auth_plugins();
3129 foreach ($authsequence as $authname) {
3130 $authplugins[$authname] = get_auth_plugin($authname);
3131 $authplugins[$authname]->prelogout_hook();
3134 // Store info that gets removed during logout.
3135 $sid = session_id();
3136 $event = \core\event\user_loggedout::create(
3137 array(
3138 'userid' => $USER->id,
3139 'objectid' => $USER->id,
3140 'other' => array('sessionid' => $sid),
3143 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3144 $event->add_record_snapshot('sessions', $session);
3147 // Clone of $USER object to be used by auth plugins.
3148 $user = fullclone($USER);
3150 // Delete session record and drop $_SESSION content.
3151 \core\session\manager::terminate_current();
3153 // Trigger event AFTER action.
3154 $event->trigger();
3156 // Hook to execute auth plugins redirection after event trigger.
3157 foreach ($authplugins as $authplugin) {
3158 $authplugin->postlogout_hook($user);
3163 * Weaker version of require_login()
3165 * This is a weaker version of {@link require_login()} which only requires login
3166 * when called from within a course rather than the site page, unless
3167 * the forcelogin option is turned on.
3168 * @see require_login()
3170 * @package core_access
3171 * @category access
3173 * @param mixed $courseorid The course object or id in question
3174 * @param bool $autologinguest Allow autologin guests if that is wanted
3175 * @param object $cm Course activity module if known
3176 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3177 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3178 * in order to keep redirects working properly. MDL-14495
3179 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3180 * @return void
3181 * @throws coding_exception
3183 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3184 global $CFG, $PAGE, $SITE;
3185 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3186 or (!is_object($courseorid) and $courseorid == SITEID));
3187 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3188 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3189 // db queries so this is not really a performance concern, however it is obviously
3190 // better if you use get_fast_modinfo to get the cm before calling this.
3191 if (is_object($courseorid)) {
3192 $course = $courseorid;
3193 } else {
3194 $course = clone($SITE);
3196 $modinfo = get_fast_modinfo($course);
3197 $cm = $modinfo->get_cm($cm->id);
3199 if (!empty($CFG->forcelogin)) {
3200 // Login required for both SITE and courses.
3201 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3203 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3204 // Always login for hidden activities.
3205 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3207 } else if (isloggedin() && !isguestuser()) {
3208 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3209 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3211 } else if ($issite) {
3212 // Login for SITE not required.
3213 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3214 if (!empty($courseorid)) {
3215 if (is_object($courseorid)) {
3216 $course = $courseorid;
3217 } else {
3218 $course = clone $SITE;
3220 if ($cm) {
3221 if ($cm->course != $course->id) {
3222 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3224 $PAGE->set_cm($cm, $course);
3225 $PAGE->set_pagelayout('incourse');
3226 } else {
3227 $PAGE->set_course($course);
3229 } else {
3230 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3231 $PAGE->set_course($PAGE->course);
3233 // Do not update access time for webservice or ajax requests.
3234 if (!WS_SERVER && !AJAX_SCRIPT) {
3235 user_accesstime_log(SITEID);
3237 return;
3239 } else {
3240 // Course login always required.
3241 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3246 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3248 * @param string $keyvalue the key value
3249 * @param string $script unique script identifier
3250 * @param int $instance instance id
3251 * @return stdClass the key entry in the user_private_key table
3252 * @since Moodle 3.2
3253 * @throws moodle_exception
3255 function validate_user_key($keyvalue, $script, $instance) {
3256 global $DB;
3258 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3259 print_error('invalidkey');
3262 if (!empty($key->validuntil) and $key->validuntil < time()) {
3263 print_error('expiredkey');
3266 if ($key->iprestriction) {
3267 $remoteaddr = getremoteaddr(null);
3268 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3269 print_error('ipmismatch');
3272 return $key;
3276 * Require key login. Function terminates with error if key not found or incorrect.
3278 * @uses NO_MOODLE_COOKIES
3279 * @uses PARAM_ALPHANUM
3280 * @param string $script unique script identifier
3281 * @param int $instance optional instance id
3282 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3283 * @return int Instance ID
3285 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3286 global $DB;
3288 if (!NO_MOODLE_COOKIES) {
3289 print_error('sessioncookiesdisable');
3292 // Extra safety.
3293 \core\session\manager::write_close();
3295 if (null === $keyvalue) {
3296 $keyvalue = required_param('key', PARAM_ALPHANUM);
3299 $key = validate_user_key($keyvalue, $script, $instance);
3301 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3302 print_error('invaliduserid');
3305 core_user::require_active_user($user, true, true);
3307 // Emulate normal session.
3308 enrol_check_plugins($user);
3309 \core\session\manager::set_user($user);
3311 // Note we are not using normal login.
3312 if (!defined('USER_KEY_LOGIN')) {
3313 define('USER_KEY_LOGIN', true);
3316 // Return instance id - it might be empty.
3317 return $key->instance;
3321 * Creates a new private user access key.
3323 * @param string $script unique target identifier
3324 * @param int $userid
3325 * @param int $instance optional instance id
3326 * @param string $iprestriction optional ip restricted access
3327 * @param int $validuntil key valid only until given data
3328 * @return string access key value
3330 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3331 global $DB;
3333 $key = new stdClass();
3334 $key->script = $script;
3335 $key->userid = $userid;
3336 $key->instance = $instance;
3337 $key->iprestriction = $iprestriction;
3338 $key->validuntil = $validuntil;
3339 $key->timecreated = time();
3341 // Something long and unique.
3342 $key->value = md5($userid.'_'.time().random_string(40));
3343 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3344 // Must be unique.
3345 $key->value = md5($userid.'_'.time().random_string(40));
3347 $DB->insert_record('user_private_key', $key);
3348 return $key->value;
3352 * Delete the user's new private user access keys for a particular script.
3354 * @param string $script unique target identifier
3355 * @param int $userid
3356 * @return void
3358 function delete_user_key($script, $userid) {
3359 global $DB;
3360 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3364 * Gets a private user access key (and creates one if one doesn't exist).
3366 * @param string $script unique target identifier
3367 * @param int $userid
3368 * @param int $instance optional instance id
3369 * @param string $iprestriction optional ip restricted access
3370 * @param int $validuntil key valid only until given date
3371 * @return string access key value
3373 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3374 global $DB;
3376 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3377 'instance' => $instance, 'iprestriction' => $iprestriction,
3378 'validuntil' => $validuntil))) {
3379 return $key->value;
3380 } else {
3381 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3387 * Modify the user table by setting the currently logged in user's last login to now.
3389 * @return bool Always returns true
3391 function update_user_login_times() {
3392 global $USER, $DB, $SESSION;
3394 if (isguestuser()) {
3395 // Do not update guest access times/ips for performance.
3396 return true;
3399 if (defined('USER_KEY_LOGIN') && USER_KEY_LOGIN === true) {
3400 // Do not update user login time when using user key login.
3401 return true;
3404 $now = time();
3406 $user = new stdClass();
3407 $user->id = $USER->id;
3409 // Make sure all users that logged in have some firstaccess.
3410 if ($USER->firstaccess == 0) {
3411 $USER->firstaccess = $user->firstaccess = $now;
3414 // Store the previous current as lastlogin.
3415 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3417 $USER->currentlogin = $user->currentlogin = $now;
3419 // Function user_accesstime_log() may not update immediately, better do it here.
3420 $USER->lastaccess = $user->lastaccess = $now;
3421 $SESSION->userpreviousip = $USER->lastip;
3422 $USER->lastip = $user->lastip = getremoteaddr();
3424 // Note: do not call user_update_user() here because this is part of the login process,
3425 // the login event means that these fields were updated.
3426 $DB->update_record('user', $user);
3427 return true;
3431 * Determines if a user has completed setting up their account.
3433 * The lax mode (with $strict = false) has been introduced for special cases
3434 * only where we want to skip certain checks intentionally. This is valid in
3435 * certain mnet or ajax scenarios when the user cannot / should not be
3436 * redirected to edit their profile. In most cases, you should perform the
3437 * strict check.
3439 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3440 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3441 * @return bool
3443 function user_not_fully_set_up($user, $strict = true) {
3444 global $CFG;
3445 require_once($CFG->dirroot.'/user/profile/lib.php');
3447 if (isguestuser($user)) {
3448 return false;
3451 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3452 return true;
3455 if ($strict) {
3456 if (empty($user->id)) {
3457 // Strict mode can be used with existing accounts only.
3458 return true;
3460 if (!profile_has_required_custom_fields_set($user->id)) {
3461 return true;
3465 return false;
3469 * Check whether the user has exceeded the bounce threshold
3471 * @param stdClass $user A {@link $USER} object
3472 * @return bool true => User has exceeded bounce threshold
3474 function over_bounce_threshold($user) {
3475 global $CFG, $DB;
3477 if (empty($CFG->handlebounces)) {
3478 return false;
3481 if (empty($user->id)) {
3482 // No real (DB) user, nothing to do here.
3483 return false;
3486 // Set sensible defaults.
3487 if (empty($CFG->minbounces)) {
3488 $CFG->minbounces = 10;
3490 if (empty($CFG->bounceratio)) {
3491 $CFG->bounceratio = .20;
3493 $bouncecount = 0;
3494 $sendcount = 0;
3495 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3496 $bouncecount = $bounce->value;
3498 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3499 $sendcount = $send->value;
3501 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3505 * Used to increment or reset email sent count
3507 * @param stdClass $user object containing an id
3508 * @param bool $reset will reset the count to 0
3509 * @return void
3511 function set_send_count($user, $reset=false) {
3512 global $DB;
3514 if (empty($user->id)) {
3515 // No real (DB) user, nothing to do here.
3516 return;
3519 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3520 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3521 $DB->update_record('user_preferences', $pref);
3522 } else if (!empty($reset)) {
3523 // If it's not there and we're resetting, don't bother. Make a new one.
3524 $pref = new stdClass();
3525 $pref->name = 'email_send_count';
3526 $pref->value = 1;
3527 $pref->userid = $user->id;
3528 $DB->insert_record('user_preferences', $pref, false);
3533 * Increment or reset user's email bounce count
3535 * @param stdClass $user object containing an id
3536 * @param bool $reset will reset the count to 0
3538 function set_bounce_count($user, $reset=false) {
3539 global $DB;
3541 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3542 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3543 $DB->update_record('user_preferences', $pref);
3544 } else if (!empty($reset)) {
3545 // If it's not there and we're resetting, don't bother. Make a new one.
3546 $pref = new stdClass();
3547 $pref->name = 'email_bounce_count';
3548 $pref->value = 1;
3549 $pref->userid = $user->id;
3550 $DB->insert_record('user_preferences', $pref, false);
3555 * Determines if the logged in user is currently moving an activity
3557 * @param int $courseid The id of the course being tested
3558 * @return bool
3560 function ismoving($courseid) {
3561 global $USER;
3563 if (!empty($USER->activitycopy)) {
3564 return ($USER->activitycopycourse == $courseid);
3566 return false;
3570 * Returns a persons full name
3572 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3573 * The result may depend on system settings or language. 'override' will force the alternativefullnameformat to be used. In
3574 * English, fullname as well as alternativefullnameformat is set to 'firstname lastname' by default. But you could have
3575 * fullname set to 'firstname lastname' and alternativefullnameformat set to 'firstname middlename alternatename lastname'.
3577 * @param stdClass $user A {@link $USER} object to get full name of.
3578 * @param bool $override If true then the alternativefullnameformat format rather than fullnamedisplay format will be used.
3579 * @return string
3581 function fullname($user, $override=false) {
3582 global $CFG, $SESSION;
3584 if (!isset($user->firstname) and !isset($user->lastname)) {
3585 return '';
3588 // Get all of the name fields.
3589 $allnames = \core_user\fields::get_name_fields();
3590 if ($CFG->debugdeveloper) {
3591 foreach ($allnames as $allname) {
3592 if (!property_exists($user, $allname)) {
3593 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3594 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3595 // Message has been sent, no point in sending the message multiple times.
3596 break;
3601 if (!$override) {
3602 if (!empty($CFG->forcefirstname)) {
3603 $user->firstname = $CFG->forcefirstname;
3605 if (!empty($CFG->forcelastname)) {
3606 $user->lastname = $CFG->forcelastname;
3610 if (!empty($SESSION->fullnamedisplay)) {
3611 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3614 $template = null;
3615 // If the fullnamedisplay setting is available, set the template to that.
3616 if (isset($CFG->fullnamedisplay)) {
3617 $template = $CFG->fullnamedisplay;
3619 // If the template is empty, or set to language, return the language string.
3620 if ((empty($template) || $template == 'language') && !$override) {
3621 return get_string('fullnamedisplay', null, $user);
3624 // Check to see if we are displaying according to the alternative full name format.
3625 if ($override) {
3626 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3627 // Default to show just the user names according to the fullnamedisplay string.
3628 return get_string('fullnamedisplay', null, $user);
3629 } else {
3630 // If the override is true, then change the template to use the complete name.
3631 $template = $CFG->alternativefullnameformat;
3635 $requirednames = array();
3636 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3637 foreach ($allnames as $allname) {
3638 if (strpos($template, $allname) !== false) {
3639 $requirednames[] = $allname;
3643 $displayname = $template;
3644 // Switch in the actual data into the template.
3645 foreach ($requirednames as $altname) {
3646 if (isset($user->$altname)) {
3647 // Using empty() on the below if statement causes breakages.
3648 if ((string)$user->$altname == '') {
3649 $displayname = str_replace($altname, 'EMPTY', $displayname);
3650 } else {
3651 $displayname = str_replace($altname, $user->$altname, $displayname);
3653 } else {
3654 $displayname = str_replace($altname, 'EMPTY', $displayname);
3657 // Tidy up any misc. characters (Not perfect, but gets most characters).
3658 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3659 // katakana and parenthesis.
3660 $patterns = array();
3661 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3662 // filled in by a user.
3663 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3664 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3665 // This regular expression is to remove any double spaces in the display name.
3666 $patterns[] = '/\s{2,}/u';
3667 foreach ($patterns as $pattern) {
3668 $displayname = preg_replace($pattern, ' ', $displayname);
3671 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3672 $displayname = trim($displayname);
3673 if (empty($displayname)) {
3674 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3675 // people in general feel is a good setting to fall back on.
3676 $displayname = $user->firstname;
3678 return $displayname;
3682 * Reduces lines of duplicated code for getting user name fields.
3684 * See also {@link user_picture::unalias()}
3686 * @param object $addtoobject Object to add user name fields to.
3687 * @param object $secondobject Object that contains user name field information.
3688 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3689 * @param array $additionalfields Additional fields to be matched with data in the second object.
3690 * The key can be set to the user table field name.
3691 * @return object User name fields.
3693 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3694 $fields = [];
3695 foreach (\core_user\fields::get_name_fields() as $field) {
3696 $fields[$field] = $prefix . $field;
3698 if ($additionalfields) {
3699 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3700 // the key is a number and then sets the key to the array value.
3701 foreach ($additionalfields as $key => $value) {
3702 if (is_numeric($key)) {
3703 $additionalfields[$value] = $prefix . $value;
3704 unset($additionalfields[$key]);
3705 } else {
3706 $additionalfields[$key] = $prefix . $value;
3709 $fields = array_merge($fields, $additionalfields);
3711 foreach ($fields as $key => $field) {
3712 // Important that we have all of the user name fields present in the object that we are sending back.
3713 $addtoobject->$key = '';
3714 if (isset($secondobject->$field)) {
3715 $addtoobject->$key = $secondobject->$field;
3718 return $addtoobject;
3722 * Returns an array of values in order of occurance in a provided string.
3723 * The key in the result is the character postion in the string.
3725 * @param array $values Values to be found in the string format
3726 * @param string $stringformat The string which may contain values being searched for.
3727 * @return array An array of values in order according to placement in the string format.
3729 function order_in_string($values, $stringformat) {
3730 $valuearray = array();
3731 foreach ($values as $value) {
3732 $pattern = "/$value\b/";
3733 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3734 if (preg_match($pattern, $stringformat)) {
3735 $replacement = "thing";
3736 // Replace the value with something more unique to ensure we get the right position when using strpos().
3737 $newformat = preg_replace($pattern, $replacement, $stringformat);
3738 $position = strpos($newformat, $replacement);
3739 $valuearray[$position] = $value;
3742 ksort($valuearray);
3743 return $valuearray;
3747 * Returns whether a given authentication plugin exists.
3749 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3750 * @return boolean Whether the plugin is available.
3752 function exists_auth_plugin($auth) {
3753 global $CFG;
3755 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3756 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3758 return false;
3762 * Checks if a given plugin is in the list of enabled authentication plugins.
3764 * @param string $auth Authentication plugin.
3765 * @return boolean Whether the plugin is enabled.
3767 function is_enabled_auth($auth) {
3768 if (empty($auth)) {
3769 return false;
3772 $enabled = get_enabled_auth_plugins();
3774 return in_array($auth, $enabled);
3778 * Returns an authentication plugin instance.
3780 * @param string $auth name of authentication plugin
3781 * @return auth_plugin_base An instance of the required authentication plugin.
3783 function get_auth_plugin($auth) {
3784 global $CFG;
3786 // Check the plugin exists first.
3787 if (! exists_auth_plugin($auth)) {
3788 print_error('authpluginnotfound', 'debug', '', $auth);
3791 // Return auth plugin instance.
3792 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3793 $class = "auth_plugin_$auth";
3794 return new $class;
3798 * Returns array of active auth plugins.
3800 * @param bool $fix fix $CFG->auth if needed. Only set if logged in as admin.
3801 * @return array
3803 function get_enabled_auth_plugins($fix=false) {
3804 global $CFG;
3806 $default = array('manual', 'nologin');
3808 if (empty($CFG->auth)) {
3809 $auths = array();
3810 } else {
3811 $auths = explode(',', $CFG->auth);
3814 $auths = array_unique($auths);
3815 $oldauthconfig = implode(',', $auths);
3816 foreach ($auths as $k => $authname) {
3817 if (in_array($authname, $default)) {
3818 // The manual and nologin plugin never need to be stored.
3819 unset($auths[$k]);
3820 } else if (!exists_auth_plugin($authname)) {
3821 debugging(get_string('authpluginnotfound', 'debug', $authname));
3822 unset($auths[$k]);
3826 // Ideally only explicit interaction from a human admin should trigger a
3827 // change in auth config, see MDL-70424 for details.
3828 if ($fix) {
3829 $newconfig = implode(',', $auths);
3830 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3831 add_to_config_log('auth', $oldauthconfig, $newconfig, 'core');
3832 set_config('auth', $newconfig);
3836 return (array_merge($default, $auths));
3840 * Returns true if an internal authentication method is being used.
3841 * if method not specified then, global default is assumed
3843 * @param string $auth Form of authentication required
3844 * @return bool
3846 function is_internal_auth($auth) {
3847 // Throws error if bad $auth.
3848 $authplugin = get_auth_plugin($auth);
3849 return $authplugin->is_internal();
3853 * Returns true if the user is a 'restored' one.
3855 * Used in the login process to inform the user and allow him/her to reset the password
3857 * @param string $username username to be checked
3858 * @return bool
3860 function is_restored_user($username) {
3861 global $CFG, $DB;
3863 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3867 * Returns an array of user fields
3869 * @return array User field/column names
3871 function get_user_fieldnames() {
3872 global $DB;
3874 $fieldarray = $DB->get_columns('user');
3875 unset($fieldarray['id']);
3876 $fieldarray = array_keys($fieldarray);
3878 return $fieldarray;
3882 * Returns the string of the language for the new user.
3884 * @return string language for the new user
3886 function get_newuser_language() {
3887 global $CFG, $SESSION;
3888 return (!empty($CFG->autolangusercreation) && !empty($SESSION->lang)) ? $SESSION->lang : $CFG->lang;
3892 * Creates a bare-bones user record
3894 * @todo Outline auth types and provide code example
3896 * @param string $username New user's username to add to record
3897 * @param string $password New user's password to add to record
3898 * @param string $auth Form of authentication required
3899 * @return stdClass A complete user object
3901 function create_user_record($username, $password, $auth = 'manual') {
3902 global $CFG, $DB, $SESSION;
3903 require_once($CFG->dirroot.'/user/profile/lib.php');
3904 require_once($CFG->dirroot.'/user/lib.php');
3906 // Just in case check text case.
3907 $username = trim(core_text::strtolower($username));
3909 $authplugin = get_auth_plugin($auth);
3910 $customfields = $authplugin->get_custom_user_profile_fields();
3911 $newuser = new stdClass();
3912 if ($newinfo = $authplugin->get_userinfo($username)) {
3913 $newinfo = truncate_userinfo($newinfo);
3914 foreach ($newinfo as $key => $value) {
3915 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3916 $newuser->$key = $value;
3921 if (!empty($newuser->email)) {
3922 if (email_is_not_allowed($newuser->email)) {
3923 unset($newuser->email);
3927 $newuser->auth = $auth;
3928 $newuser->username = $username;
3930 // Fix for MDL-8480
3931 // user CFG lang for user if $newuser->lang is empty
3932 // or $user->lang is not an installed language.
3933 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3934 $newuser->lang = get_newuser_language();
3936 $newuser->confirmed = 1;
3937 $newuser->lastip = getremoteaddr();
3938 $newuser->timecreated = time();
3939 $newuser->timemodified = $newuser->timecreated;
3940 $newuser->mnethostid = $CFG->mnet_localhost_id;
3942 $newuser->id = user_create_user($newuser, false, false);
3944 // Save user profile data.
3945 profile_save_data($newuser);
3947 $user = get_complete_user_data('id', $newuser->id);
3948 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3949 set_user_preference('auth_forcepasswordchange', 1, $user);
3951 // Set the password.
3952 update_internal_user_password($user, $password);
3954 // Trigger event.
3955 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3957 return $user;
3961 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3963 * @param string $username user's username to update the record
3964 * @return stdClass A complete user object
3966 function update_user_record($username) {
3967 global $DB, $CFG;
3968 // Just in case check text case.
3969 $username = trim(core_text::strtolower($username));
3971 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3972 return update_user_record_by_id($oldinfo->id);
3976 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3978 * @param int $id user id
3979 * @return stdClass A complete user object
3981 function update_user_record_by_id($id) {
3982 global $DB, $CFG;
3983 require_once($CFG->dirroot."/user/profile/lib.php");
3984 require_once($CFG->dirroot.'/user/lib.php');
3986 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3987 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3989 $newuser = array();
3990 $userauth = get_auth_plugin($oldinfo->auth);
3992 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3993 $newinfo = truncate_userinfo($newinfo);
3994 $customfields = $userauth->get_custom_user_profile_fields();
3996 foreach ($newinfo as $key => $value) {
3997 $iscustom = in_array($key, $customfields);
3998 if (!$iscustom) {
3999 $key = strtolower($key);
4001 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4002 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4003 // Unknown or must not be changed.
4004 continue;
4006 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
4007 continue;
4009 $confval = $userauth->config->{'field_updatelocal_' . $key};
4010 $lockval = $userauth->config->{'field_lock_' . $key};
4011 if ($confval === 'onlogin') {
4012 // MDL-4207 Don't overwrite modified user profile values with
4013 // empty LDAP values when 'unlocked if empty' is set. The purpose
4014 // of the setting 'unlocked if empty' is to allow the user to fill
4015 // in a value for the selected field _if LDAP is giving
4016 // nothing_ for this field. Thus it makes sense to let this value
4017 // stand in until LDAP is giving a value for this field.
4018 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4019 if ($iscustom || (in_array($key, $userauth->userfields) &&
4020 ((string)$oldinfo->$key !== (string)$value))) {
4021 $newuser[$key] = (string)$value;
4026 if ($newuser) {
4027 $newuser['id'] = $oldinfo->id;
4028 $newuser['timemodified'] = time();
4029 user_update_user((object) $newuser, false, false);
4031 // Save user profile data.
4032 profile_save_data((object) $newuser);
4034 // Trigger event.
4035 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4039 return get_complete_user_data('id', $oldinfo->id);
4043 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4045 * @param array $info Array of user properties to truncate if needed
4046 * @return array The now truncated information that was passed in
4048 function truncate_userinfo(array $info) {
4049 // Define the limits.
4050 $limit = array(
4051 'username' => 100,
4052 'idnumber' => 255,
4053 'firstname' => 100,
4054 'lastname' => 100,
4055 'email' => 100,
4056 'phone1' => 20,
4057 'phone2' => 20,
4058 'institution' => 255,
4059 'department' => 255,
4060 'address' => 255,
4061 'city' => 120,
4062 'country' => 2,
4065 // Apply where needed.
4066 foreach (array_keys($info) as $key) {
4067 if (!empty($limit[$key])) {
4068 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4072 return $info;
4076 * Marks user deleted in internal user database and notifies the auth plugin.
4077 * Also unenrols user from all roles and does other cleanup.
4079 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4081 * @param stdClass $user full user object before delete
4082 * @return boolean success
4083 * @throws coding_exception if invalid $user parameter detected
4085 function delete_user(stdClass $user) {
4086 global $CFG, $DB, $SESSION;
4087 require_once($CFG->libdir.'/grouplib.php');
4088 require_once($CFG->libdir.'/gradelib.php');
4089 require_once($CFG->dirroot.'/message/lib.php');
4090 require_once($CFG->dirroot.'/user/lib.php');
4092 // Make sure nobody sends bogus record type as parameter.
4093 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4094 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4097 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4098 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4099 debugging('Attempt to delete unknown user account.');
4100 return false;
4103 // There must be always exactly one guest record, originally the guest account was identified by username only,
4104 // now we use $CFG->siteguest for performance reasons.
4105 if ($user->username === 'guest' or isguestuser($user)) {
4106 debugging('Guest user account can not be deleted.');
4107 return false;
4110 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4111 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4112 if ($user->auth === 'manual' and is_siteadmin($user)) {
4113 debugging('Local administrator accounts can not be deleted.');
4114 return false;
4117 // Allow plugins to use this user object before we completely delete it.
4118 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4119 foreach ($pluginsfunction as $plugintype => $plugins) {
4120 foreach ($plugins as $pluginfunction) {
4121 $pluginfunction($user);
4126 // Keep user record before updating it, as we have to pass this to user_deleted event.
4127 $olduser = clone $user;
4129 // Keep a copy of user context, we need it for event.
4130 $usercontext = context_user::instance($user->id);
4132 // Delete all grades - backup is kept in grade_grades_history table.
4133 grade_user_delete($user->id);
4135 // TODO: remove from cohorts using standard API here.
4137 // Remove user tags.
4138 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4140 // Unconditionally unenrol from all courses.
4141 enrol_user_delete($user);
4143 // Unenrol from all roles in all contexts.
4144 // This might be slow but it is really needed - modules might do some extra cleanup!
4145 role_unassign_all(array('userid' => $user->id));
4147 // Notify the competency subsystem.
4148 \core_competency\api::hook_user_deleted($user->id);
4150 // Now do a brute force cleanup.
4152 // Delete all user events and subscription events.
4153 $DB->delete_records_select('event', 'userid = :userid AND subscriptionid IS NOT NULL', ['userid' => $user->id]);
4155 // Now, delete all calendar subscription from the user.
4156 $DB->delete_records('event_subscriptions', ['userid' => $user->id]);
4158 // Remove from all cohorts.
4159 $DB->delete_records('cohort_members', array('userid' => $user->id));
4161 // Remove from all groups.
4162 $DB->delete_records('groups_members', array('userid' => $user->id));
4164 // Brute force unenrol from all courses.
4165 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4167 // Purge user preferences.
4168 $DB->delete_records('user_preferences', array('userid' => $user->id));
4170 // Purge user extra profile info.
4171 $DB->delete_records('user_info_data', array('userid' => $user->id));
4173 // Purge log of previous password hashes.
4174 $DB->delete_records('user_password_history', array('userid' => $user->id));
4176 // Last course access not necessary either.
4177 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4178 // Remove all user tokens.
4179 $DB->delete_records('external_tokens', array('userid' => $user->id));
4181 // Unauthorise the user for all services.
4182 $DB->delete_records('external_services_users', array('userid' => $user->id));
4184 // Remove users private keys.
4185 $DB->delete_records('user_private_key', array('userid' => $user->id));
4187 // Remove users customised pages.
4188 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4190 // Remove user's oauth2 refresh tokens, if present.
4191 $DB->delete_records('oauth2_refresh_token', array('userid' => $user->id));
4193 // Delete user from $SESSION->bulk_users.
4194 if (isset($SESSION->bulk_users[$user->id])) {
4195 unset($SESSION->bulk_users[$user->id]);
4198 // Force logout - may fail if file based sessions used, sorry.
4199 \core\session\manager::kill_user_sessions($user->id);
4201 // Generate username from email address, or a fake email.
4202 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4204 $deltime = time();
4205 $deltimelength = core_text::strlen((string) $deltime);
4207 // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
4208 $delname = clean_param($delemail, PARAM_USERNAME);
4209 $delname = core_text::substr($delname, 0, 100 - ($deltimelength + 1)) . ".{$deltime}";
4211 // Workaround for bulk deletes of users with the same email address.
4212 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4213 $delname++;
4216 // Mark internal user record as "deleted".
4217 $updateuser = new stdClass();
4218 $updateuser->id = $user->id;
4219 $updateuser->deleted = 1;
4220 $updateuser->username = $delname; // Remember it just in case.
4221 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4222 $updateuser->idnumber = ''; // Clear this field to free it up.
4223 $updateuser->picture = 0;
4224 $updateuser->timemodified = $deltime;
4226 // Don't trigger update event, as user is being deleted.
4227 user_update_user($updateuser, false, false);
4229 // Delete all content associated with the user context, but not the context itself.
4230 $usercontext->delete_content();
4232 // Delete any search data.
4233 \core_search\manager::context_deleted($usercontext);
4235 // Any plugin that needs to cleanup should register this event.
4236 // Trigger event.
4237 $event = \core\event\user_deleted::create(
4238 array(
4239 'objectid' => $user->id,
4240 'relateduserid' => $user->id,
4241 'context' => $usercontext,
4242 'other' => array(
4243 'username' => $user->username,
4244 'email' => $user->email,
4245 'idnumber' => $user->idnumber,
4246 'picture' => $user->picture,
4247 'mnethostid' => $user->mnethostid
4251 $event->add_record_snapshot('user', $olduser);
4252 $event->trigger();
4254 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4255 // should know about this updated property persisted to the user's table.
4256 $user->timemodified = $updateuser->timemodified;
4258 // Notify auth plugin - do not block the delete even when plugin fails.
4259 $authplugin = get_auth_plugin($user->auth);
4260 $authplugin->user_delete($user);
4262 return true;
4266 * Retrieve the guest user object.
4268 * @return stdClass A {@link $USER} object
4270 function guest_user() {
4271 global $CFG, $DB;
4273 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4274 $newuser->confirmed = 1;
4275 $newuser->lang = get_newuser_language();
4276 $newuser->lastip = getremoteaddr();
4279 return $newuser;
4283 * Authenticates a user against the chosen authentication mechanism
4285 * Given a username and password, this function looks them
4286 * up using the currently selected authentication mechanism,
4287 * and if the authentication is successful, it returns a
4288 * valid $user object from the 'user' table.
4290 * Uses auth_ functions from the currently active auth module
4292 * After authenticate_user_login() returns success, you will need to
4293 * log that the user has logged in, and call complete_user_login() to set
4294 * the session up.
4296 * Note: this function works only with non-mnet accounts!
4298 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4299 * @param string $password User's password
4300 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4301 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4302 * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4303 * @return stdClass|false A {@link $USER} object or false if error
4305 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4306 global $CFG, $DB, $PAGE;
4307 require_once("$CFG->libdir/authlib.php");
4309 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4310 // we have found the user
4312 } else if (!empty($CFG->authloginviaemail)) {
4313 if ($email = clean_param($username, PARAM_EMAIL)) {
4314 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4315 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4316 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4317 if (count($users) === 1) {
4318 // Use email for login only if unique.
4319 $user = reset($users);
4320 $user = get_complete_user_data('id', $user->id);
4321 $username = $user->username;
4323 unset($users);
4327 // Make sure this request came from the login form.
4328 if (!\core\session\manager::validate_login_token($logintoken)) {
4329 $failurereason = AUTH_LOGIN_FAILED;
4331 // Trigger login failed event (specifying the ID of the found user, if available).
4332 \core\event\user_login_failed::create([
4333 'userid' => ($user->id ?? 0),
4334 'other' => [
4335 'username' => $username,
4336 'reason' => $failurereason,
4338 ])->trigger();
4340 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4341 return false;
4344 $authsenabled = get_enabled_auth_plugins();
4346 if ($user) {
4347 // Use manual if auth not set.
4348 $auth = empty($user->auth) ? 'manual' : $user->auth;
4350 if (in_array($user->auth, $authsenabled)) {
4351 $authplugin = get_auth_plugin($user->auth);
4352 $authplugin->pre_user_login_hook($user);
4355 if (!empty($user->suspended)) {
4356 $failurereason = AUTH_LOGIN_SUSPENDED;
4358 // Trigger login failed event.
4359 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4360 'other' => array('username' => $username, 'reason' => $failurereason)));
4361 $event->trigger();
4362 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4363 return false;
4365 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4366 // Legacy way to suspend user.
4367 $failurereason = AUTH_LOGIN_SUSPENDED;
4369 // Trigger login failed event.
4370 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4371 'other' => array('username' => $username, 'reason' => $failurereason)));
4372 $event->trigger();
4373 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4374 return false;
4376 $auths = array($auth);
4378 } else {
4379 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4380 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4381 $failurereason = AUTH_LOGIN_NOUSER;
4383 // Trigger login failed event.
4384 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4385 'reason' => $failurereason)));
4386 $event->trigger();
4387 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4388 return false;
4391 // User does not exist.
4392 $auths = $authsenabled;
4393 $user = new stdClass();
4394 $user->id = 0;
4397 if ($ignorelockout) {
4398 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4399 // or this function is called from a SSO script.
4400 } else if ($user->id) {
4401 // Verify login lockout after other ways that may prevent user login.
4402 if (login_is_lockedout($user)) {
4403 $failurereason = AUTH_LOGIN_LOCKOUT;
4405 // Trigger login failed event.
4406 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4407 'other' => array('username' => $username, 'reason' => $failurereason)));
4408 $event->trigger();
4410 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4411 return false;
4413 } else {
4414 // We can not lockout non-existing accounts.
4417 foreach ($auths as $auth) {
4418 $authplugin = get_auth_plugin($auth);
4420 // On auth fail fall through to the next plugin.
4421 if (!$authplugin->user_login($username, $password)) {
4422 continue;
4425 // Before performing login actions, check if user still passes password policy, if admin setting is enabled.
4426 if (!empty($CFG->passwordpolicycheckonlogin)) {
4427 $errmsg = '';
4428 $passed = check_password_policy($password, $errmsg, $user);
4429 if (!$passed) {
4430 // First trigger event for failure.
4431 $failedevent = \core\event\user_password_policy_failed::create_from_user($user);
4432 $failedevent->trigger();
4434 // If able to change password, set flag and move on.
4435 if ($authplugin->can_change_password()) {
4436 // Check if we are on internal change password page, or service is external, don't show notification.
4437 $internalchangeurl = new moodle_url('/login/change_password.php');
4438 if (!($PAGE->has_set_url() && $internalchangeurl->compare($PAGE->url)) && $authplugin->is_internal()) {
4439 \core\notification::error(get_string('passwordpolicynomatch', '', $errmsg));
4441 set_user_preference('auth_forcepasswordchange', 1, $user);
4442 } else if ($authplugin->can_reset_password()) {
4443 // Else force a reset if possible.
4444 \core\notification::error(get_string('forcepasswordresetnotice', '', $errmsg));
4445 redirect(new moodle_url('/login/forgot_password.php'));
4446 } else {
4447 $notifymsg = get_string('forcepasswordresetfailurenotice', '', $errmsg);
4448 // If support page is set, add link for help.
4449 if (!empty($CFG->supportpage)) {
4450 $link = \html_writer::link($CFG->supportpage, $CFG->supportpage);
4451 $link = \html_writer::tag('p', $link);
4452 $notifymsg .= $link;
4455 // If no change or reset is possible, add a notification for user.
4456 \core\notification::error($notifymsg);
4461 // Successful authentication.
4462 if ($user->id) {
4463 // User already exists in database.
4464 if (empty($user->auth)) {
4465 // For some reason auth isn't set yet.
4466 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4467 $user->auth = $auth;
4470 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4471 // the current hash algorithm while we have access to the user's password.
4472 update_internal_user_password($user, $password);
4474 if ($authplugin->is_synchronised_with_external()) {
4475 // Update user record from external DB.
4476 $user = update_user_record_by_id($user->id);
4478 } else {
4479 // The user is authenticated but user creation may be disabled.
4480 if (!empty($CFG->authpreventaccountcreation)) {
4481 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4483 // Trigger login failed event.
4484 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4485 'reason' => $failurereason)));
4486 $event->trigger();
4488 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4489 $_SERVER['HTTP_USER_AGENT']);
4490 return false;
4491 } else {
4492 $user = create_user_record($username, $password, $auth);
4496 $authplugin->sync_roles($user);
4498 foreach ($authsenabled as $hau) {
4499 $hauth = get_auth_plugin($hau);
4500 $hauth->user_authenticated_hook($user, $username, $password);
4503 if (empty($user->id)) {
4504 $failurereason = AUTH_LOGIN_NOUSER;
4505 // Trigger login failed event.
4506 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4507 'reason' => $failurereason)));
4508 $event->trigger();
4509 return false;
4512 if (!empty($user->suspended)) {
4513 // Just in case some auth plugin suspended account.
4514 $failurereason = AUTH_LOGIN_SUSPENDED;
4515 // Trigger login failed event.
4516 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4517 'other' => array('username' => $username, 'reason' => $failurereason)));
4518 $event->trigger();
4519 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4520 return false;
4523 login_attempt_valid($user);
4524 $failurereason = AUTH_LOGIN_OK;
4525 return $user;
4528 // Failed if all the plugins have failed.
4529 if (debugging('', DEBUG_ALL)) {
4530 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4533 if ($user->id) {
4534 login_attempt_failed($user);
4535 $failurereason = AUTH_LOGIN_FAILED;
4536 // Trigger login failed event.
4537 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4538 'other' => array('username' => $username, 'reason' => $failurereason)));
4539 $event->trigger();
4540 } else {
4541 $failurereason = AUTH_LOGIN_NOUSER;
4542 // Trigger login failed event.
4543 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4544 'reason' => $failurereason)));
4545 $event->trigger();
4548 return false;
4552 * Call to complete the user login process after authenticate_user_login()
4553 * has succeeded. It will setup the $USER variable and other required bits
4554 * and pieces.
4556 * NOTE:
4557 * - It will NOT log anything -- up to the caller to decide what to log.
4558 * - this function does not set any cookies any more!
4560 * @param stdClass $user
4561 * @return stdClass A {@link $USER} object - BC only, do not use
4563 function complete_user_login($user) {
4564 global $CFG, $DB, $USER, $SESSION;
4566 \core\session\manager::login_user($user);
4568 // Reload preferences from DB.
4569 unset($USER->preference);
4570 check_user_preferences_loaded($USER);
4572 // Update login times.
4573 update_user_login_times();
4575 // Extra session prefs init.
4576 set_login_session_preferences();
4578 // Trigger login event.
4579 $event = \core\event\user_loggedin::create(
4580 array(
4581 'userid' => $USER->id,
4582 'objectid' => $USER->id,
4583 'other' => array('username' => $USER->username),
4586 $event->trigger();
4588 // Check if the user is using a new browser or session (a new MoodleSession cookie is set in that case).
4589 // If the user is accessing from the same IP, ignore everything (most of the time will be a new session in the same browser).
4590 // Skip Web Service requests, CLI scripts, AJAX scripts, and request from the mobile app itself.
4591 $loginip = getremoteaddr();
4592 $isnewip = isset($SESSION->userpreviousip) && $SESSION->userpreviousip != $loginip;
4593 $isvalidenv = (!WS_SERVER && !CLI_SCRIPT && !NO_MOODLE_COOKIES) || PHPUNIT_TEST;
4595 if (!empty($SESSION->isnewsessioncookie) && $isnewip && $isvalidenv && !\core_useragent::is_moodle_app()) {
4597 $logintime = time();
4598 $ismoodleapp = false;
4599 $useragent = \core_useragent::get_user_agent_string();
4601 // Schedule adhoc task to sent a login notification to the user.
4602 $task = new \core\task\send_login_notifications();
4603 $task->set_userid($USER->id);
4604 $task->set_custom_data(compact('ismoodleapp', 'useragent', 'loginip', 'logintime'));
4605 $task->set_component('core');
4606 \core\task\manager::queue_adhoc_task($task);
4609 // Queue migrating the messaging data, if we need to.
4610 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4611 // Check if there are any legacy messages to migrate.
4612 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4613 \core_message\task\migrate_message_data::queue_task($USER->id);
4614 } else {
4615 set_user_preference('core_message_migrate_data', true, $USER->id);
4619 if (isguestuser()) {
4620 // No need to continue when user is THE guest.
4621 return $USER;
4624 if (CLI_SCRIPT) {
4625 // We can redirect to password change URL only in browser.
4626 return $USER;
4629 // Select password change url.
4630 $userauth = get_auth_plugin($USER->auth);
4632 // Check whether the user should be changing password.
4633 if (get_user_preferences('auth_forcepasswordchange', false)) {
4634 if ($userauth->can_change_password()) {
4635 if ($changeurl = $userauth->change_password_url()) {
4636 redirect($changeurl);
4637 } else {
4638 require_once($CFG->dirroot . '/login/lib.php');
4639 $SESSION->wantsurl = core_login_get_return_url();
4640 redirect($CFG->wwwroot.'/login/change_password.php');
4642 } else {
4643 print_error('nopasswordchangeforced', 'auth');
4646 return $USER;
4650 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4652 * @param string $password String to check.
4653 * @return boolean True if the $password matches the format of an md5 sum.
4655 function password_is_legacy_hash($password) {
4656 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4660 * Compare password against hash stored in user object to determine if it is valid.
4662 * If necessary it also updates the stored hash to the current format.
4664 * @param stdClass $user (Password property may be updated).
4665 * @param string $password Plain text password.
4666 * @return bool True if password is valid.
4668 function validate_internal_user_password($user, $password) {
4669 global $CFG;
4671 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4672 // Internal password is not used at all, it can not validate.
4673 return false;
4676 // If hash isn't a legacy (md5) hash, validate using the library function.
4677 if (!password_is_legacy_hash($user->password)) {
4678 return password_verify($password, $user->password);
4681 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4682 // is valid we can then update it to the new algorithm.
4684 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4685 $validated = false;
4687 if ($user->password === md5($password.$sitesalt)
4688 or $user->password === md5($password)
4689 or $user->password === md5(addslashes($password).$sitesalt)
4690 or $user->password === md5(addslashes($password))) {
4691 // Note: we are intentionally using the addslashes() here because we
4692 // need to accept old password hashes of passwords with magic quotes.
4693 $validated = true;
4695 } else {
4696 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4697 $alt = 'passwordsaltalt'.$i;
4698 if (!empty($CFG->$alt)) {
4699 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4700 $validated = true;
4701 break;
4707 if ($validated) {
4708 // If the password matches the existing md5 hash, update to the
4709 // current hash algorithm while we have access to the user's password.
4710 update_internal_user_password($user, $password);
4713 return $validated;
4717 * Calculate hash for a plain text password.
4719 * @param string $password Plain text password to be hashed.
4720 * @param bool $fasthash If true, use a low cost factor when generating the hash
4721 * This is much faster to generate but makes the hash
4722 * less secure. It is used when lots of hashes need to
4723 * be generated quickly.
4724 * @return string The hashed password.
4726 * @throws moodle_exception If a problem occurs while generating the hash.
4728 function hash_internal_user_password($password, $fasthash = false) {
4729 global $CFG;
4731 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4732 $options = ($fasthash) ? array('cost' => 4) : array();
4734 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4736 if ($generatedhash === false || $generatedhash === null) {
4737 throw new moodle_exception('Failed to generate password hash.');
4740 return $generatedhash;
4744 * Update password hash in user object (if necessary).
4746 * The password is updated if:
4747 * 1. The password has changed (the hash of $user->password is different
4748 * to the hash of $password).
4749 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4750 * md5 algorithm).
4752 * Updating the password will modify the $user object and the database
4753 * record to use the current hashing algorithm.
4754 * It will remove Web Services user tokens too.
4756 * @param stdClass $user User object (password property may be updated).
4757 * @param string $password Plain text password.
4758 * @param bool $fasthash If true, use a low cost factor when generating the hash
4759 * This is much faster to generate but makes the hash
4760 * less secure. It is used when lots of hashes need to
4761 * be generated quickly.
4762 * @return bool Always returns true.
4764 function update_internal_user_password($user, $password, $fasthash = false) {
4765 global $CFG, $DB;
4767 // Figure out what the hashed password should be.
4768 if (!isset($user->auth)) {
4769 debugging('User record in update_internal_user_password() must include field auth',
4770 DEBUG_DEVELOPER);
4771 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4773 $authplugin = get_auth_plugin($user->auth);
4774 if ($authplugin->prevent_local_passwords()) {
4775 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4776 } else {
4777 $hashedpassword = hash_internal_user_password($password, $fasthash);
4780 $algorithmchanged = false;
4782 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4783 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4784 $passwordchanged = ($user->password !== $hashedpassword);
4786 } else if (isset($user->password)) {
4787 // If verification fails then it means the password has changed.
4788 $passwordchanged = !password_verify($password, $user->password);
4789 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4790 } else {
4791 // While creating new user, password in unset in $user object, to avoid
4792 // saving it with user_create()
4793 $passwordchanged = true;
4796 if ($passwordchanged || $algorithmchanged) {
4797 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4798 $user->password = $hashedpassword;
4800 // Trigger event.
4801 $user = $DB->get_record('user', array('id' => $user->id));
4802 \core\event\user_password_updated::create_from_user($user)->trigger();
4804 // Remove WS user tokens.
4805 if (!empty($CFG->passwordchangetokendeletion)) {
4806 require_once($CFG->dirroot.'/webservice/lib.php');
4807 webservice::delete_user_ws_tokens($user->id);
4811 return true;
4815 * Get a complete user record, which includes all the info in the user record.
4817 * Intended for setting as $USER session variable
4819 * @param string $field The user field to be checked for a given value.
4820 * @param string $value The value to match for $field.
4821 * @param int $mnethostid
4822 * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4823 * found. Otherwise, it will just return false.
4824 * @return mixed False, or A {@link $USER} object.
4826 function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4827 global $CFG, $DB;
4829 if (!$field || !$value) {
4830 return false;
4833 // Change the field to lowercase.
4834 $field = core_text::strtolower($field);
4836 // List of case insensitive fields.
4837 $caseinsensitivefields = ['email'];
4839 // Username input is forced to lowercase and should be case sensitive.
4840 if ($field == 'username') {
4841 $value = core_text::strtolower($value);
4844 // Build the WHERE clause for an SQL query.
4845 $params = array('fieldval' => $value);
4847 // Do a case-insensitive query, if necessary. These are generally very expensive. The performance can be improved on some DBs
4848 // such as MySQL by pre-filtering users with accent-insensitive subselect.
4849 if (in_array($field, $caseinsensitivefields)) {
4850 $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4851 $idsubselect = $DB->sql_equal($field, ':fieldval2', false, false);
4852 $params['fieldval2'] = $value;
4853 } else {
4854 $fieldselect = "$field = :fieldval";
4855 $idsubselect = '';
4857 $constraints = "$fieldselect AND deleted <> 1";
4859 // If we are loading user data based on anything other than id,
4860 // we must also restrict our search based on mnet host.
4861 if ($field != 'id') {
4862 if (empty($mnethostid)) {
4863 // If empty, we restrict to local users.
4864 $mnethostid = $CFG->mnet_localhost_id;
4867 if (!empty($mnethostid)) {
4868 $params['mnethostid'] = $mnethostid;
4869 $constraints .= " AND mnethostid = :mnethostid";
4872 if ($idsubselect) {
4873 $constraints .= " AND id IN (SELECT id FROM {user} WHERE {$idsubselect})";
4876 // Get all the basic user data.
4877 try {
4878 // Make sure that there's only a single record that matches our query.
4879 // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4880 // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4881 $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST);
4882 } catch (dml_exception $exception) {
4883 if ($throwexception) {
4884 throw $exception;
4885 } else {
4886 // Return false when no records or multiple records were found.
4887 return false;
4891 // Get various settings and preferences.
4893 // Preload preference cache.
4894 check_user_preferences_loaded($user);
4896 // Load course enrolment related stuff.
4897 $user->lastcourseaccess = array(); // During last session.
4898 $user->currentcourseaccess = array(); // During current session.
4899 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4900 foreach ($lastaccesses as $lastaccess) {
4901 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4905 $sql = "SELECT g.id, g.courseid
4906 FROM {groups} g, {groups_members} gm
4907 WHERE gm.groupid=g.id AND gm.userid=?";
4909 // This is a special hack to speedup calendar display.
4910 $user->groupmember = array();
4911 if (!isguestuser($user)) {
4912 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4913 foreach ($groups as $group) {
4914 if (!array_key_exists($group->courseid, $user->groupmember)) {
4915 $user->groupmember[$group->courseid] = array();
4917 $user->groupmember[$group->courseid][$group->id] = $group->id;
4922 // Add cohort theme.
4923 if (!empty($CFG->allowcohortthemes)) {
4924 require_once($CFG->dirroot . '/cohort/lib.php');
4925 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4926 $user->cohorttheme = $cohorttheme;
4930 // Add the custom profile fields to the user record.
4931 $user->profile = array();
4932 if (!isguestuser($user)) {
4933 require_once($CFG->dirroot.'/user/profile/lib.php');
4934 profile_load_custom_fields($user);
4937 // Rewrite some variables if necessary.
4938 if (!empty($user->description)) {
4939 // No need to cart all of it around.
4940 $user->description = true;
4942 if (isguestuser($user)) {
4943 // Guest language always same as site.
4944 $user->lang = get_newuser_language();
4945 // Name always in current language.
4946 $user->firstname = get_string('guestuser');
4947 $user->lastname = ' ';
4950 return $user;
4954 * Validate a password against the configured password policy
4956 * @param string $password the password to be checked against the password policy
4957 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4958 * @param stdClass $user the user object to perform password validation against. Defaults to null if not provided.
4960 * @return bool true if the password is valid according to the policy. false otherwise.
4962 function check_password_policy($password, &$errmsg, $user = null) {
4963 global $CFG;
4965 if (!empty($CFG->passwordpolicy)) {
4966 $errmsg = '';
4967 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4968 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4970 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4971 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4973 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4974 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4976 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4977 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4979 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4980 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4982 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4983 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4986 // Fire any additional password policy functions from plugins.
4987 // Plugin functions should output an error message string or empty string for success.
4988 $pluginsfunction = get_plugins_with_function('check_password_policy');
4989 foreach ($pluginsfunction as $plugintype => $plugins) {
4990 foreach ($plugins as $pluginfunction) {
4991 $pluginerr = $pluginfunction($password, $user);
4992 if ($pluginerr) {
4993 $errmsg .= '<div>'. $pluginerr .'</div>';
4999 if ($errmsg == '') {
5000 return true;
5001 } else {
5002 return false;
5008 * When logging in, this function is run to set certain preferences for the current SESSION.
5010 function set_login_session_preferences() {
5011 global $SESSION;
5013 $SESSION->justloggedin = true;
5015 unset($SESSION->lang);
5016 unset($SESSION->forcelang);
5017 unset($SESSION->load_navigation_admin);
5022 * Delete a course, including all related data from the database, and any associated files.
5024 * @param mixed $courseorid The id of the course or course object to delete.
5025 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5026 * @return bool true if all the removals succeeded. false if there were any failures. If this
5027 * method returns false, some of the removals will probably have succeeded, and others
5028 * failed, but you have no way of knowing which.
5030 function delete_course($courseorid, $showfeedback = true) {
5031 global $DB;
5033 if (is_object($courseorid)) {
5034 $courseid = $courseorid->id;
5035 $course = $courseorid;
5036 } else {
5037 $courseid = $courseorid;
5038 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
5039 return false;
5042 $context = context_course::instance($courseid);
5044 // Frontpage course can not be deleted!!
5045 if ($courseid == SITEID) {
5046 return false;
5049 // Allow plugins to use this course before we completely delete it.
5050 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
5051 foreach ($pluginsfunction as $plugintype => $plugins) {
5052 foreach ($plugins as $pluginfunction) {
5053 $pluginfunction($course);
5058 // Tell the search manager we are about to delete a course. This prevents us sending updates
5059 // for each individual context being deleted.
5060 \core_search\manager::course_deleting_start($courseid);
5062 $handler = core_course\customfield\course_handler::create();
5063 $handler->delete_instance($courseid);
5065 // Make the course completely empty.
5066 remove_course_contents($courseid, $showfeedback);
5068 // Delete the course and related context instance.
5069 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
5071 $DB->delete_records("course", array("id" => $courseid));
5072 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5074 // Reset all course related caches here.
5075 core_courseformat\base::reset_course_cache($courseid);
5077 // Tell search that we have deleted the course so it can delete course data from the index.
5078 \core_search\manager::course_deleting_finish($courseid);
5080 // Trigger a course deleted event.
5081 $event = \core\event\course_deleted::create(array(
5082 'objectid' => $course->id,
5083 'context' => $context,
5084 'other' => array(
5085 'shortname' => $course->shortname,
5086 'fullname' => $course->fullname,
5087 'idnumber' => $course->idnumber
5090 $event->add_record_snapshot('course', $course);
5091 $event->trigger();
5093 return true;
5097 * Clear a course out completely, deleting all content but don't delete the course itself.
5099 * This function does not verify any permissions.
5101 * Please note this function also deletes all user enrolments,
5102 * enrolment instances and role assignments by default.
5104 * $options:
5105 * - 'keep_roles_and_enrolments' - false by default
5106 * - 'keep_groups_and_groupings' - false by default
5108 * @param int $courseid The id of the course that is being deleted
5109 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5110 * @param array $options extra options
5111 * @return bool true if all the removals succeeded. false if there were any failures. If this
5112 * method returns false, some of the removals will probably have succeeded, and others
5113 * failed, but you have no way of knowing which.
5115 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5116 global $CFG, $DB, $OUTPUT;
5118 require_once($CFG->libdir.'/badgeslib.php');
5119 require_once($CFG->libdir.'/completionlib.php');
5120 require_once($CFG->libdir.'/questionlib.php');
5121 require_once($CFG->libdir.'/gradelib.php');
5122 require_once($CFG->dirroot.'/group/lib.php');
5123 require_once($CFG->dirroot.'/comment/lib.php');
5124 require_once($CFG->dirroot.'/rating/lib.php');
5125 require_once($CFG->dirroot.'/notes/lib.php');
5127 // Handle course badges.
5128 badges_handle_course_deletion($courseid);
5130 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5131 $strdeleted = get_string('deleted').' - ';
5133 // Some crazy wishlist of stuff we should skip during purging of course content.
5134 $options = (array)$options;
5136 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5137 $coursecontext = context_course::instance($courseid);
5138 $fs = get_file_storage();
5140 // Delete course completion information, this has to be done before grades and enrols.
5141 $cc = new completion_info($course);
5142 $cc->clear_criteria();
5143 if ($showfeedback) {
5144 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5147 // Remove all data from gradebook - this needs to be done before course modules
5148 // because while deleting this information, the system may need to reference
5149 // the course modules that own the grades.
5150 remove_course_grades($courseid, $showfeedback);
5151 remove_grade_letters($coursecontext, $showfeedback);
5153 // Delete course blocks in any all child contexts,
5154 // they may depend on modules so delete them first.
5155 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5156 foreach ($childcontexts as $childcontext) {
5157 blocks_delete_all_for_context($childcontext->id);
5159 unset($childcontexts);
5160 blocks_delete_all_for_context($coursecontext->id);
5161 if ($showfeedback) {
5162 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5165 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $courseid]);
5166 rebuild_course_cache($courseid, true);
5168 // Get the list of all modules that are properly installed.
5169 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5171 // Delete every instance of every module,
5172 // this has to be done before deleting of course level stuff.
5173 $locations = core_component::get_plugin_list('mod');
5174 foreach ($locations as $modname => $moddir) {
5175 if ($modname === 'NEWMODULE') {
5176 continue;
5178 if (array_key_exists($modname, $allmodules)) {
5179 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5180 FROM {".$modname."} m
5181 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5182 WHERE m.course = :courseid";
5183 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5184 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5186 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5187 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5189 if ($instances) {
5190 foreach ($instances as $cm) {
5191 if ($cm->id) {
5192 // Delete activity context questions and question categories.
5193 question_delete_activity($cm);
5194 // Notify the competency subsystem.
5195 \core_competency\api::hook_course_module_deleted($cm);
5197 // Delete all tag instances associated with the instance of this module.
5198 core_tag_tag::delete_instances("mod_{$modname}", null, context_module::instance($cm->id)->id);
5199 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
5201 if (function_exists($moddelete)) {
5202 // This purges all module data in related tables, extra user prefs, settings, etc.
5203 $moddelete($cm->modinstance);
5204 } else {
5205 // NOTE: we should not allow installation of modules with missing delete support!
5206 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5207 $DB->delete_records($modname, array('id' => $cm->modinstance));
5210 if ($cm->id) {
5211 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5212 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5213 $DB->delete_records('course_modules_completion', ['coursemoduleid' => $cm->id]);
5214 $DB->delete_records('course_modules', array('id' => $cm->id));
5215 rebuild_course_cache($cm->course, true);
5219 if ($instances and $showfeedback) {
5220 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5222 } else {
5223 // Ooops, this module is not properly installed, force-delete it in the next block.
5227 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5229 // Delete completion defaults.
5230 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5232 // Remove all data from availability and completion tables that is associated
5233 // with course-modules belonging to this course. Note this is done even if the
5234 // features are not enabled now, in case they were enabled previously.
5235 $DB->delete_records_subquery('course_modules_completion', 'coursemoduleid', 'id',
5236 'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
5238 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5239 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5240 $allmodulesbyid = array_flip($allmodules);
5241 foreach ($cms as $cm) {
5242 if (array_key_exists($cm->module, $allmodulesbyid)) {
5243 try {
5244 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5245 } catch (Exception $e) {
5246 // Ignore weird or missing table problems.
5249 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5250 $DB->delete_records('course_modules', array('id' => $cm->id));
5251 rebuild_course_cache($cm->course, true);
5254 if ($showfeedback) {
5255 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5258 // Delete questions and question categories.
5259 question_delete_course($course);
5260 if ($showfeedback) {
5261 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5264 // Delete content bank contents.
5265 $cb = new \core_contentbank\contentbank();
5266 $cbdeleted = $cb->delete_contents($coursecontext);
5267 if ($showfeedback && $cbdeleted) {
5268 echo $OUTPUT->notification($strdeleted.get_string('contentbank', 'contentbank'), 'notifysuccess');
5271 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5272 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5273 foreach ($childcontexts as $childcontext) {
5274 $childcontext->delete();
5276 unset($childcontexts);
5278 // Remove roles and enrolments by default.
5279 if (empty($options['keep_roles_and_enrolments'])) {
5280 // This hack is used in restore when deleting contents of existing course.
5281 // During restore, we should remove only enrolment related data that the user performing the restore has a
5282 // permission to remove.
5283 $userid = $options['userid'] ?? null;
5284 enrol_course_delete($course, $userid);
5285 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5286 if ($showfeedback) {
5287 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5291 // Delete any groups, removing members and grouping/course links first.
5292 if (empty($options['keep_groups_and_groupings'])) {
5293 groups_delete_groupings($course->id, $showfeedback);
5294 groups_delete_groups($course->id, $showfeedback);
5297 // Filters be gone!
5298 filter_delete_all_for_context($coursecontext->id);
5300 // Notes, you shall not pass!
5301 note_delete_all($course->id);
5303 // Die comments!
5304 comment::delete_comments($coursecontext->id);
5306 // Ratings are history too.
5307 $delopt = new stdclass();
5308 $delopt->contextid = $coursecontext->id;
5309 $rm = new rating_manager();
5310 $rm->delete_ratings($delopt);
5312 // Delete course tags.
5313 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5315 // Give the course format the opportunity to remove its obscure data.
5316 $format = course_get_format($course);
5317 $format->delete_format_data();
5319 // Notify the competency subsystem.
5320 \core_competency\api::hook_course_deleted($course);
5322 // Delete calendar events.
5323 $DB->delete_records('event', array('courseid' => $course->id));
5324 $fs->delete_area_files($coursecontext->id, 'calendar');
5326 // Delete all related records in other core tables that may have a courseid
5327 // This array stores the tables that need to be cleared, as
5328 // table_name => column_name that contains the course id.
5329 $tablestoclear = array(
5330 'backup_courses' => 'courseid', // Scheduled backup stuff.
5331 'user_lastaccess' => 'courseid', // User access info.
5333 foreach ($tablestoclear as $table => $col) {
5334 $DB->delete_records($table, array($col => $course->id));
5337 // Delete all course backup files.
5338 $fs->delete_area_files($coursecontext->id, 'backup');
5340 // Cleanup course record - remove links to deleted stuff.
5341 $oldcourse = new stdClass();
5342 $oldcourse->id = $course->id;
5343 $oldcourse->summary = '';
5344 $oldcourse->cacherev = 0;
5345 $oldcourse->legacyfiles = 0;
5346 if (!empty($options['keep_groups_and_groupings'])) {
5347 $oldcourse->defaultgroupingid = 0;
5349 $DB->update_record('course', $oldcourse);
5351 // Delete course sections.
5352 $DB->delete_records('course_sections', array('course' => $course->id));
5354 // Delete legacy, section and any other course files.
5355 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5357 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5358 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5359 // Easy, do not delete the context itself...
5360 $coursecontext->delete_content();
5361 } else {
5362 // Hack alert!!!!
5363 // We can not drop all context stuff because it would bork enrolments and roles,
5364 // there might be also files used by enrol plugins...
5367 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5368 // also some non-standard unsupported plugins may try to store something there.
5369 fulldelete($CFG->dataroot.'/'.$course->id);
5371 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5372 course_modinfo::purge_course_cache($courseid);
5374 // Trigger a course content deleted event.
5375 $event = \core\event\course_content_deleted::create(array(
5376 'objectid' => $course->id,
5377 'context' => $coursecontext,
5378 'other' => array('shortname' => $course->shortname,
5379 'fullname' => $course->fullname,
5380 'options' => $options) // Passing this for legacy reasons.
5382 $event->add_record_snapshot('course', $course);
5383 $event->trigger();
5385 return true;
5389 * Change dates in module - used from course reset.
5391 * @param string $modname forum, assignment, etc
5392 * @param array $fields array of date fields from mod table
5393 * @param int $timeshift time difference
5394 * @param int $courseid
5395 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5396 * @return bool success
5398 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5399 global $CFG, $DB;
5400 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5402 $return = true;
5403 $params = array($timeshift, $courseid);
5404 foreach ($fields as $field) {
5405 $updatesql = "UPDATE {".$modname."}
5406 SET $field = $field + ?
5407 WHERE course=? AND $field<>0";
5408 if ($modid) {
5409 $updatesql .= ' AND id=?';
5410 $params[] = $modid;
5412 $return = $DB->execute($updatesql, $params) && $return;
5415 return $return;
5419 * This function will empty a course of user data.
5420 * It will retain the activities and the structure of the course.
5422 * @param object $data an object containing all the settings including courseid (without magic quotes)
5423 * @return array status array of array component, item, error
5425 function reset_course_userdata($data) {
5426 global $CFG, $DB;
5427 require_once($CFG->libdir.'/gradelib.php');
5428 require_once($CFG->libdir.'/completionlib.php');
5429 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5430 require_once($CFG->dirroot.'/group/lib.php');
5432 $data->courseid = $data->id;
5433 $context = context_course::instance($data->courseid);
5435 $eventparams = array(
5436 'context' => $context,
5437 'courseid' => $data->id,
5438 'other' => array(
5439 'reset_options' => (array) $data
5442 $event = \core\event\course_reset_started::create($eventparams);
5443 $event->trigger();
5445 // Calculate the time shift of dates.
5446 if (!empty($data->reset_start_date)) {
5447 // Time part of course startdate should be zero.
5448 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5449 } else {
5450 $data->timeshift = 0;
5453 // Result array: component, item, error.
5454 $status = array();
5456 // Start the resetting.
5457 $componentstr = get_string('general');
5459 // Move the course start time.
5460 if (!empty($data->reset_start_date) and $data->timeshift) {
5461 // Change course start data.
5462 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5463 // Update all course and group events - do not move activity events.
5464 $updatesql = "UPDATE {event}
5465 SET timestart = timestart + ?
5466 WHERE courseid=? AND instance=0";
5467 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5469 // Update any date activity restrictions.
5470 if ($CFG->enableavailability) {
5471 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5474 // Update completion expected dates.
5475 if ($CFG->enablecompletion) {
5476 $modinfo = get_fast_modinfo($data->courseid);
5477 $changed = false;
5478 foreach ($modinfo->get_cms() as $cm) {
5479 if ($cm->completion && !empty($cm->completionexpected)) {
5480 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5481 array('id' => $cm->id));
5482 $changed = true;
5486 // Clear course cache if changes made.
5487 if ($changed) {
5488 rebuild_course_cache($data->courseid, true);
5491 // Update course date completion criteria.
5492 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5495 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5498 if (!empty($data->reset_end_date)) {
5499 // If the user set a end date value respect it.
5500 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5501 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5502 // If there is a time shift apply it to the end date as well.
5503 $enddate = $data->reset_end_date_old + $data->timeshift;
5504 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5507 if (!empty($data->reset_events)) {
5508 $DB->delete_records('event', array('courseid' => $data->courseid));
5509 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5512 if (!empty($data->reset_notes)) {
5513 require_once($CFG->dirroot.'/notes/lib.php');
5514 note_delete_all($data->courseid);
5515 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5518 if (!empty($data->delete_blog_associations)) {
5519 require_once($CFG->dirroot.'/blog/lib.php');
5520 blog_remove_associations_for_course($data->courseid);
5521 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5524 if (!empty($data->reset_completion)) {
5525 // Delete course and activity completion information.
5526 $course = $DB->get_record('course', array('id' => $data->courseid));
5527 $cc = new completion_info($course);
5528 $cc->delete_all_completion_data();
5529 $status[] = array('component' => $componentstr,
5530 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5533 if (!empty($data->reset_competency_ratings)) {
5534 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5535 $status[] = array('component' => $componentstr,
5536 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5539 $componentstr = get_string('roles');
5541 if (!empty($data->reset_roles_overrides)) {
5542 $children = $context->get_child_contexts();
5543 foreach ($children as $child) {
5544 $child->delete_capabilities();
5546 $context->delete_capabilities();
5547 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5550 if (!empty($data->reset_roles_local)) {
5551 $children = $context->get_child_contexts();
5552 foreach ($children as $child) {
5553 role_unassign_all(array('contextid' => $child->id));
5555 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5558 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5559 $data->unenrolled = array();
5560 if (!empty($data->unenrol_users)) {
5561 $plugins = enrol_get_plugins(true);
5562 $instances = enrol_get_instances($data->courseid, true);
5563 foreach ($instances as $key => $instance) {
5564 if (!isset($plugins[$instance->enrol])) {
5565 unset($instances[$key]);
5566 continue;
5570 $usersroles = enrol_get_course_users_roles($data->courseid);
5571 foreach ($data->unenrol_users as $withroleid) {
5572 if ($withroleid) {
5573 $sql = "SELECT ue.*
5574 FROM {user_enrolments} ue
5575 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5576 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5577 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5578 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5580 } else {
5581 // Without any role assigned at course context.
5582 $sql = "SELECT ue.*
5583 FROM {user_enrolments} ue
5584 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5585 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5586 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5587 WHERE ra.id IS null";
5588 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5591 $rs = $DB->get_recordset_sql($sql, $params);
5592 foreach ($rs as $ue) {
5593 if (!isset($instances[$ue->enrolid])) {
5594 continue;
5596 $instance = $instances[$ue->enrolid];
5597 $plugin = $plugins[$instance->enrol];
5598 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5599 continue;
5602 if ($withroleid && count($usersroles[$ue->userid]) > 1) {
5603 // If we don't remove all roles and user has more than one role, just remove this role.
5604 role_unassign($withroleid, $ue->userid, $context->id);
5606 unset($usersroles[$ue->userid][$withroleid]);
5607 } else {
5608 // If we remove all roles or user has only one role, unenrol user from course.
5609 $plugin->unenrol_user($instance, $ue->userid);
5611 $data->unenrolled[$ue->userid] = $ue->userid;
5613 $rs->close();
5616 if (!empty($data->unenrolled)) {
5617 $status[] = array(
5618 'component' => $componentstr,
5619 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5620 'error' => false
5624 $componentstr = get_string('groups');
5626 // Remove all group members.
5627 if (!empty($data->reset_groups_members)) {
5628 groups_delete_group_members($data->courseid);
5629 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5632 // Remove all groups.
5633 if (!empty($data->reset_groups_remove)) {
5634 groups_delete_groups($data->courseid, false);
5635 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5638 // Remove all grouping members.
5639 if (!empty($data->reset_groupings_members)) {
5640 groups_delete_groupings_groups($data->courseid, false);
5641 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5644 // Remove all groupings.
5645 if (!empty($data->reset_groupings_remove)) {
5646 groups_delete_groupings($data->courseid, false);
5647 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5650 // Look in every instance of every module for data to delete.
5651 $unsupportedmods = array();
5652 if ($allmods = $DB->get_records('modules') ) {
5653 foreach ($allmods as $mod) {
5654 $modname = $mod->name;
5655 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5656 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5657 if (file_exists($modfile)) {
5658 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5659 continue; // Skip mods with no instances.
5661 include_once($modfile);
5662 if (function_exists($moddeleteuserdata)) {
5663 $modstatus = $moddeleteuserdata($data);
5664 if (is_array($modstatus)) {
5665 $status = array_merge($status, $modstatus);
5666 } else {
5667 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5669 } else {
5670 $unsupportedmods[] = $mod;
5672 } else {
5673 debugging('Missing lib.php in '.$modname.' module!');
5675 // Update calendar events for all modules.
5676 course_module_bulk_update_calendar_events($modname, $data->courseid);
5680 // Mention unsupported mods.
5681 if (!empty($unsupportedmods)) {
5682 foreach ($unsupportedmods as $mod) {
5683 $status[] = array(
5684 'component' => get_string('modulenameplural', $mod->name),
5685 'item' => '',
5686 'error' => get_string('resetnotimplemented')
5691 $componentstr = get_string('gradebook', 'grades');
5692 // Reset gradebook,.
5693 if (!empty($data->reset_gradebook_items)) {
5694 remove_course_grades($data->courseid, false);
5695 grade_grab_course_grades($data->courseid);
5696 grade_regrade_final_grades($data->courseid);
5697 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5699 } else if (!empty($data->reset_gradebook_grades)) {
5700 grade_course_reset($data->courseid);
5701 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5703 // Reset comments.
5704 if (!empty($data->reset_comments)) {
5705 require_once($CFG->dirroot.'/comment/lib.php');
5706 comment::reset_course_page_comments($context);
5709 $event = \core\event\course_reset_ended::create($eventparams);
5710 $event->trigger();
5712 return $status;
5716 * Generate an email processing address.
5718 * @param int $modid
5719 * @param string $modargs
5720 * @return string Returns email processing address
5722 function generate_email_processing_address($modid, $modargs) {
5723 global $CFG;
5725 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5726 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5732 * @todo Finish documenting this function
5734 * @param string $modargs
5735 * @param string $body Currently unused
5737 function moodle_process_email($modargs, $body) {
5738 global $DB;
5740 // The first char should be an unencoded letter. We'll take this as an action.
5741 switch ($modargs[0]) {
5742 case 'B': { // Bounce.
5743 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5744 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5745 // Check the half md5 of their email.
5746 $md5check = substr(md5($user->email), 0, 16);
5747 if ($md5check == substr($modargs, -16)) {
5748 set_bounce_count($user);
5750 // Else maybe they've already changed it?
5753 break;
5754 // Maybe more later?
5758 // CORRESPONDENCE.
5761 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5763 * @param string $action 'get', 'buffer', 'close' or 'flush'
5764 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5766 function get_mailer($action='get') {
5767 global $CFG;
5769 /** @var moodle_phpmailer $mailer */
5770 static $mailer = null;
5771 static $counter = 0;
5773 if (!isset($CFG->smtpmaxbulk)) {
5774 $CFG->smtpmaxbulk = 1;
5777 if ($action == 'get') {
5778 $prevkeepalive = false;
5780 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5781 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5782 $counter++;
5783 // Reset the mailer.
5784 $mailer->Priority = 3;
5785 $mailer->CharSet = 'UTF-8'; // Our default.
5786 $mailer->ContentType = "text/plain";
5787 $mailer->Encoding = "8bit";
5788 $mailer->From = "root@localhost";
5789 $mailer->FromName = "Root User";
5790 $mailer->Sender = "";
5791 $mailer->Subject = "";
5792 $mailer->Body = "";
5793 $mailer->AltBody = "";
5794 $mailer->ConfirmReadingTo = "";
5796 $mailer->clearAllRecipients();
5797 $mailer->clearReplyTos();
5798 $mailer->clearAttachments();
5799 $mailer->clearCustomHeaders();
5800 return $mailer;
5803 $prevkeepalive = $mailer->SMTPKeepAlive;
5804 get_mailer('flush');
5807 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5808 $mailer = new moodle_phpmailer();
5810 $counter = 1;
5812 if ($CFG->smtphosts == 'qmail') {
5813 // Use Qmail system.
5814 $mailer->isQmail();
5816 } else if (empty($CFG->smtphosts)) {
5817 // Use PHP mail() = sendmail.
5818 $mailer->isMail();
5820 } else {
5821 // Use SMTP directly.
5822 $mailer->isSMTP();
5823 if (!empty($CFG->debugsmtp) && (!empty($CFG->debugdeveloper))) {
5824 $mailer->SMTPDebug = 3;
5826 // Specify main and backup servers.
5827 $mailer->Host = $CFG->smtphosts;
5828 // Specify secure connection protocol.
5829 $mailer->SMTPSecure = $CFG->smtpsecure;
5830 // Use previous keepalive.
5831 $mailer->SMTPKeepAlive = $prevkeepalive;
5833 if ($CFG->smtpuser) {
5834 // Use SMTP authentication.
5835 $mailer->SMTPAuth = true;
5836 $mailer->Username = $CFG->smtpuser;
5837 $mailer->Password = $CFG->smtppass;
5841 return $mailer;
5844 $nothing = null;
5846 // Keep smtp session open after sending.
5847 if ($action == 'buffer') {
5848 if (!empty($CFG->smtpmaxbulk)) {
5849 get_mailer('flush');
5850 $m = get_mailer();
5851 if ($m->Mailer == 'smtp') {
5852 $m->SMTPKeepAlive = true;
5855 return $nothing;
5858 // Close smtp session, but continue buffering.
5859 if ($action == 'flush') {
5860 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5861 if (!empty($mailer->SMTPDebug)) {
5862 echo '<pre>'."\n";
5864 $mailer->SmtpClose();
5865 if (!empty($mailer->SMTPDebug)) {
5866 echo '</pre>';
5869 return $nothing;
5872 // Close smtp session, do not buffer anymore.
5873 if ($action == 'close') {
5874 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5875 get_mailer('flush');
5876 $mailer->SMTPKeepAlive = false;
5878 $mailer = null; // Better force new instance.
5879 return $nothing;
5884 * A helper function to test for email diversion
5886 * @param string $email
5887 * @return bool Returns true if the email should be diverted
5889 function email_should_be_diverted($email) {
5890 global $CFG;
5892 if (empty($CFG->divertallemailsto)) {
5893 return false;
5896 if (empty($CFG->divertallemailsexcept)) {
5897 return true;
5900 $patterns = array_map('trim', preg_split("/[\s,]+/", $CFG->divertallemailsexcept, -1, PREG_SPLIT_NO_EMPTY));
5901 foreach ($patterns as $pattern) {
5902 if (preg_match("/$pattern/", $email)) {
5903 return false;
5907 return true;
5911 * Generate a unique email Message-ID using the moodle domain and install path
5913 * @param string $localpart An optional unique message id prefix.
5914 * @return string The formatted ID ready for appending to the email headers.
5916 function generate_email_messageid($localpart = null) {
5917 global $CFG;
5919 $urlinfo = parse_url($CFG->wwwroot);
5920 $base = '@' . $urlinfo['host'];
5922 // If multiple moodles are on the same domain we want to tell them
5923 // apart so we add the install path to the local part. This means
5924 // that the id local part should never contain a / character so
5925 // we can correctly parse the id to reassemble the wwwroot.
5926 if (isset($urlinfo['path'])) {
5927 $base = $urlinfo['path'] . $base;
5930 if (empty($localpart)) {
5931 $localpart = uniqid('', true);
5934 // Because we may have an option /installpath suffix to the local part
5935 // of the id we need to escape any / chars which are in the $localpart.
5936 $localpart = str_replace('/', '%2F', $localpart);
5938 return '<' . $localpart . $base . '>';
5942 * Send an email to a specified user
5944 * @param stdClass $user A {@link $USER} object
5945 * @param stdClass $from A {@link $USER} object
5946 * @param string $subject plain text subject line of the email
5947 * @param string $messagetext plain text version of the message
5948 * @param string $messagehtml complete html version of the message (optional)
5949 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in one of
5950 * the following directories: $CFG->cachedir, $CFG->dataroot, $CFG->dirroot, $CFG->localcachedir, $CFG->tempdir
5951 * @param string $attachname the name of the file (extension indicates MIME)
5952 * @param bool $usetrueaddress determines whether $from email address should
5953 * be sent out. Will be overruled by user profile setting for maildisplay
5954 * @param string $replyto Email address to reply to
5955 * @param string $replytoname Name of reply to recipient
5956 * @param int $wordwrapwidth custom word wrap width, default 79
5957 * @return bool Returns true if mail was sent OK and false if there was an error.
5959 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5960 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5962 global $CFG, $PAGE, $SITE;
5964 if (empty($user) or empty($user->id)) {
5965 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5966 return false;
5969 if (empty($user->email)) {
5970 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5971 return false;
5974 if (!empty($user->deleted)) {
5975 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5976 return false;
5979 if (defined('BEHAT_SITE_RUNNING')) {
5980 // Fake email sending in behat.
5981 return true;
5984 if (!empty($CFG->noemailever)) {
5985 // Hidden setting for development sites, set in config.php if needed.
5986 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5987 return true;
5990 if (email_should_be_diverted($user->email)) {
5991 $subject = "[DIVERTED {$user->email}] $subject";
5992 $user = clone($user);
5993 $user->email = $CFG->divertallemailsto;
5996 // Skip mail to suspended users.
5997 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5998 return true;
6001 if (!validate_email($user->email)) {
6002 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
6003 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
6004 return false;
6007 if (over_bounce_threshold($user)) {
6008 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
6009 return false;
6012 // TLD .invalid is specifically reserved for invalid domain names.
6013 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
6014 if (substr($user->email, -8) == '.invalid') {
6015 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
6016 return true; // This is not an error.
6019 // If the user is a remote mnet user, parse the email text for URL to the
6020 // wwwroot and modify the url to direct the user's browser to login at their
6021 // home site (identity provider - idp) before hitting the link itself.
6022 if (is_mnet_remote_user($user)) {
6023 require_once($CFG->dirroot.'/mnet/lib.php');
6025 $jumpurl = mnet_get_idp_jump_url($user);
6026 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
6028 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
6029 $callback,
6030 $messagetext);
6031 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
6032 $callback,
6033 $messagehtml);
6035 $mail = get_mailer();
6037 if (!empty($mail->SMTPDebug)) {
6038 echo '<pre>' . "\n";
6041 $temprecipients = array();
6042 $tempreplyto = array();
6044 // Make sure that we fall back onto some reasonable no-reply address.
6045 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
6046 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
6048 if (!validate_email($noreplyaddress)) {
6049 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
6050 $noreplyaddress = $noreplyaddressdefault;
6053 // Make up an email address for handling bounces.
6054 if (!empty($CFG->handlebounces)) {
6055 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
6056 $mail->Sender = generate_email_processing_address(0, $modargs);
6057 } else {
6058 $mail->Sender = $noreplyaddress;
6061 // Make sure that the explicit replyto is valid, fall back to the implicit one.
6062 if (!empty($replyto) && !validate_email($replyto)) {
6063 debugging('email_to_user: Invalid replyto-email '.s($replyto));
6064 $replyto = $noreplyaddress;
6067 if (is_string($from)) { // So we can pass whatever we want if there is need.
6068 $mail->From = $noreplyaddress;
6069 $mail->FromName = $from;
6070 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
6071 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6072 // in a course with the sender.
6073 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
6074 if (!validate_email($from->email)) {
6075 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
6076 // Better not to use $noreplyaddress in this case.
6077 return false;
6079 $mail->From = $from->email;
6080 $fromdetails = new stdClass();
6081 $fromdetails->name = fullname($from);
6082 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6083 $fromdetails->siteshortname = format_string($SITE->shortname);
6084 $fromstring = $fromdetails->name;
6085 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
6086 $fromstring = get_string('emailvia', 'core', $fromdetails);
6088 $mail->FromName = $fromstring;
6089 if (empty($replyto)) {
6090 $tempreplyto[] = array($from->email, fullname($from));
6092 } else {
6093 $mail->From = $noreplyaddress;
6094 $fromdetails = new stdClass();
6095 $fromdetails->name = fullname($from);
6096 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6097 $fromdetails->siteshortname = format_string($SITE->shortname);
6098 $fromstring = $fromdetails->name;
6099 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
6100 $fromstring = get_string('emailvia', 'core', $fromdetails);
6102 $mail->FromName = $fromstring;
6103 if (empty($replyto)) {
6104 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
6108 if (!empty($replyto)) {
6109 $tempreplyto[] = array($replyto, $replytoname);
6112 $temprecipients[] = array($user->email, fullname($user));
6114 // Set word wrap.
6115 $mail->WordWrap = $wordwrapwidth;
6117 if (!empty($from->customheaders)) {
6118 // Add custom headers.
6119 if (is_array($from->customheaders)) {
6120 foreach ($from->customheaders as $customheader) {
6121 $mail->addCustomHeader($customheader);
6123 } else {
6124 $mail->addCustomHeader($from->customheaders);
6128 // If the X-PHP-Originating-Script email header is on then also add an additional
6129 // header with details of where exactly in moodle the email was triggered from,
6130 // either a call to message_send() or to email_to_user().
6131 if (ini_get('mail.add_x_header')) {
6133 $stack = debug_backtrace(false);
6134 $origin = $stack[0];
6136 foreach ($stack as $depth => $call) {
6137 if ($call['function'] == 'message_send') {
6138 $origin = $call;
6142 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
6143 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
6144 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
6147 if (!empty($CFG->emailheaders)) {
6148 $headers = array_map('trim', explode("\n", $CFG->emailheaders));
6149 foreach ($headers as $header) {
6150 if (!empty($header)) {
6151 $mail->addCustomHeader($header);
6156 if (!empty($from->priority)) {
6157 $mail->Priority = $from->priority;
6160 $renderer = $PAGE->get_renderer('core');
6161 $context = array(
6162 'sitefullname' => $SITE->fullname,
6163 'siteshortname' => $SITE->shortname,
6164 'sitewwwroot' => $CFG->wwwroot,
6165 'subject' => $subject,
6166 'prefix' => $CFG->emailsubjectprefix,
6167 'to' => $user->email,
6168 'toname' => fullname($user),
6169 'from' => $mail->From,
6170 'fromname' => $mail->FromName,
6172 if (!empty($tempreplyto[0])) {
6173 $context['replyto'] = $tempreplyto[0][0];
6174 $context['replytoname'] = $tempreplyto[0][1];
6176 if ($user->id > 0) {
6177 $context['touserid'] = $user->id;
6178 $context['tousername'] = $user->username;
6181 if (!empty($user->mailformat) && $user->mailformat == 1) {
6182 // Only process html templates if the user preferences allow html email.
6184 if (!$messagehtml) {
6185 // If no html has been given, BUT there is an html wrapping template then
6186 // auto convert the text to html and then wrap it.
6187 $messagehtml = trim(text_to_html($messagetext));
6189 $context['body'] = $messagehtml;
6190 $messagehtml = $renderer->render_from_template('core/email_html', $context);
6193 $context['body'] = html_to_text(nl2br($messagetext));
6194 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
6195 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
6196 $messagetext = $renderer->render_from_template('core/email_text', $context);
6198 // Autogenerate a MessageID if it's missing.
6199 if (empty($mail->MessageID)) {
6200 $mail->MessageID = generate_email_messageid();
6203 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6204 // Don't ever send HTML to users who don't want it.
6205 $mail->isHTML(true);
6206 $mail->Encoding = 'quoted-printable';
6207 $mail->Body = $messagehtml;
6208 $mail->AltBody = "\n$messagetext\n";
6209 } else {
6210 $mail->IsHTML(false);
6211 $mail->Body = "\n$messagetext\n";
6214 if ($attachment && $attachname) {
6215 if (preg_match( "~\\.\\.~" , $attachment )) {
6216 // Security check for ".." in dir path.
6217 $supportuser = core_user::get_support_user();
6218 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6219 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6220 } else {
6221 require_once($CFG->libdir.'/filelib.php');
6222 $mimetype = mimeinfo('type', $attachname);
6224 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6225 // The absolute (real) path is also fetched to ensure that comparisons to allowed paths are compared equally.
6226 $attachpath = str_replace('\\', '/', realpath($attachment));
6228 // Build an array of all filepaths from which attachments can be added (normalised slashes, absolute/real path).
6229 $allowedpaths = array_map(function(string $path): string {
6230 return str_replace('\\', '/', realpath($path));
6231 }, [
6232 $CFG->cachedir,
6233 $CFG->dataroot,
6234 $CFG->dirroot,
6235 $CFG->localcachedir,
6236 $CFG->tempdir,
6237 $CFG->localrequestdir,
6240 // Set addpath to true.
6241 $addpath = true;
6243 // Check if attachment includes one of the allowed paths.
6244 foreach (array_filter($allowedpaths) as $allowedpath) {
6245 // Set addpath to false if the attachment includes one of the allowed paths.
6246 if (strpos($attachpath, $allowedpath) === 0) {
6247 $addpath = false;
6248 break;
6252 // If the attachment is a full path to a file in the multiple allowed paths, use it as is,
6253 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6254 if ($addpath == true) {
6255 $attachment = $CFG->dataroot . '/' . $attachment;
6258 $mail->addAttachment($attachment, $attachname, 'base64', $mimetype);
6262 // Check if the email should be sent in an other charset then the default UTF-8.
6263 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6265 // Use the defined site mail charset or eventually the one preferred by the recipient.
6266 $charset = $CFG->sitemailcharset;
6267 if (!empty($CFG->allowusermailcharset)) {
6268 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6269 $charset = $useremailcharset;
6273 // Convert all the necessary strings if the charset is supported.
6274 $charsets = get_list_of_charsets();
6275 unset($charsets['UTF-8']);
6276 if (in_array($charset, $charsets)) {
6277 $mail->CharSet = $charset;
6278 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6279 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6280 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6281 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6283 foreach ($temprecipients as $key => $values) {
6284 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6286 foreach ($tempreplyto as $key => $values) {
6287 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6292 foreach ($temprecipients as $values) {
6293 $mail->addAddress($values[0], $values[1]);
6295 foreach ($tempreplyto as $values) {
6296 $mail->addReplyTo($values[0], $values[1]);
6299 if (!empty($CFG->emaildkimselector)) {
6300 $domain = substr(strrchr($mail->From, "@"), 1);
6301 $pempath = "{$CFG->dataroot}/dkim/{$domain}/{$CFG->emaildkimselector}.private";
6302 if (file_exists($pempath)) {
6303 $mail->DKIM_domain = $domain;
6304 $mail->DKIM_private = $pempath;
6305 $mail->DKIM_selector = $CFG->emaildkimselector;
6306 $mail->DKIM_identity = $mail->From;
6307 } else {
6308 debugging("Email DKIM selector chosen due to {$mail->From} but no certificate found at $pempath", DEBUG_DEVELOPER);
6312 if ($mail->send()) {
6313 set_send_count($user);
6314 if (!empty($mail->SMTPDebug)) {
6315 echo '</pre>';
6317 return true;
6318 } else {
6319 // Trigger event for failing to send email.
6320 $event = \core\event\email_failed::create(array(
6321 'context' => context_system::instance(),
6322 'userid' => $from->id,
6323 'relateduserid' => $user->id,
6324 'other' => array(
6325 'subject' => $subject,
6326 'message' => $messagetext,
6327 'errorinfo' => $mail->ErrorInfo
6330 $event->trigger();
6331 if (CLI_SCRIPT) {
6332 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6334 if (!empty($mail->SMTPDebug)) {
6335 echo '</pre>';
6337 return false;
6342 * Check to see if a user's real email address should be used for the "From" field.
6344 * @param object $from The user object for the user we are sending the email from.
6345 * @param object $user The user object that we are sending the email to.
6346 * @param array $unused No longer used.
6347 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6349 function can_send_from_real_email_address($from, $user, $unused = null) {
6350 global $CFG;
6351 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6352 return false;
6354 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6355 // Email is in the list of allowed domains for sending email,
6356 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6357 // in a course with the sender.
6358 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6359 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6360 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6361 && enrol_get_shared_courses($user, $from, false, true)))) {
6362 return true;
6364 return false;
6368 * Generate a signoff for emails based on support settings
6370 * @return string
6372 function generate_email_signoff() {
6373 global $CFG;
6375 $signoff = "\n";
6376 if (!empty($CFG->supportname)) {
6377 $signoff .= $CFG->supportname."\n";
6379 if (!empty($CFG->supportemail)) {
6380 $signoff .= $CFG->supportemail."\n";
6382 if (!empty($CFG->supportpage)) {
6383 $signoff .= $CFG->supportpage."\n";
6385 return $signoff;
6389 * Sets specified user's password and send the new password to the user via email.
6391 * @param stdClass $user A {@link $USER} object
6392 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6393 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6395 function setnew_password_and_mail($user, $fasthash = false) {
6396 global $CFG, $DB;
6398 // We try to send the mail in language the user understands,
6399 // unfortunately the filter_string() does not support alternative langs yet
6400 // so multilang will not work properly for site->fullname.
6401 $lang = empty($user->lang) ? get_newuser_language() : $user->lang;
6403 $site = get_site();
6405 $supportuser = core_user::get_support_user();
6407 $newpassword = generate_password();
6409 update_internal_user_password($user, $newpassword, $fasthash);
6411 $a = new stdClass();
6412 $a->firstname = fullname($user, true);
6413 $a->sitename = format_string($site->fullname);
6414 $a->username = $user->username;
6415 $a->newpassword = $newpassword;
6416 $a->link = $CFG->wwwroot .'/login/?lang='.$lang;
6417 $a->signoff = generate_email_signoff();
6419 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6421 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6423 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6424 return email_to_user($user, $supportuser, $subject, $message);
6429 * Resets specified user's password and send the new password to the user via email.
6431 * @param stdClass $user A {@link $USER} object
6432 * @return bool Returns true if mail was sent OK and false if there was an error.
6434 function reset_password_and_mail($user) {
6435 global $CFG;
6437 $site = get_site();
6438 $supportuser = core_user::get_support_user();
6440 $userauth = get_auth_plugin($user->auth);
6441 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6442 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6443 return false;
6446 $newpassword = generate_password();
6448 if (!$userauth->user_update_password($user, $newpassword)) {
6449 print_error("cannotsetpassword");
6452 $a = new stdClass();
6453 $a->firstname = $user->firstname;
6454 $a->lastname = $user->lastname;
6455 $a->sitename = format_string($site->fullname);
6456 $a->username = $user->username;
6457 $a->newpassword = $newpassword;
6458 $a->link = $CFG->wwwroot .'/login/change_password.php';
6459 $a->signoff = generate_email_signoff();
6461 $message = get_string('newpasswordtext', '', $a);
6463 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6465 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6467 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6468 return email_to_user($user, $supportuser, $subject, $message);
6472 * Send email to specified user with confirmation text and activation link.
6474 * @param stdClass $user A {@link $USER} object
6475 * @param string $confirmationurl user confirmation URL
6476 * @return bool Returns true if mail was sent OK and false if there was an error.
6478 function send_confirmation_email($user, $confirmationurl = null) {
6479 global $CFG;
6481 $site = get_site();
6482 $supportuser = core_user::get_support_user();
6484 $data = new stdClass();
6485 $data->sitename = format_string($site->fullname);
6486 $data->admin = generate_email_signoff();
6488 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6490 if (empty($confirmationurl)) {
6491 $confirmationurl = '/login/confirm.php';
6494 $confirmationurl = new moodle_url($confirmationurl);
6495 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6496 $confirmationurl->remove_params('data');
6497 $confirmationpath = $confirmationurl->out(false);
6499 // We need to custom encode the username to include trailing dots in the link.
6500 // Because of this custom encoding we can't use moodle_url directly.
6501 // Determine if a query string is present in the confirmation url.
6502 $hasquerystring = strpos($confirmationpath, '?') !== false;
6503 // Perform normal url encoding of the username first.
6504 $username = urlencode($user->username);
6505 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6506 $username = str_replace('.', '%2E', $username);
6508 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6510 $message = get_string('emailconfirmation', '', $data);
6511 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6513 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6514 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6518 * Sends a password change confirmation email.
6520 * @param stdClass $user A {@link $USER} object
6521 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6522 * @return bool Returns true if mail was sent OK and false if there was an error.
6524 function send_password_change_confirmation_email($user, $resetrecord) {
6525 global $CFG;
6527 $site = get_site();
6528 $supportuser = core_user::get_support_user();
6529 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6531 $data = new stdClass();
6532 $data->firstname = $user->firstname;
6533 $data->lastname = $user->lastname;
6534 $data->username = $user->username;
6535 $data->sitename = format_string($site->fullname);
6536 $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6537 $data->admin = generate_email_signoff();
6538 $data->resetminutes = $pwresetmins;
6540 $message = get_string('emailresetconfirmation', '', $data);
6541 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6543 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6544 return email_to_user($user, $supportuser, $subject, $message);
6549 * Sends an email containing information on how to change your password.
6551 * @param stdClass $user A {@link $USER} object
6552 * @return bool Returns true if mail was sent OK and false if there was an error.
6554 function send_password_change_info($user) {
6555 $site = get_site();
6556 $supportuser = core_user::get_support_user();
6558 $data = new stdClass();
6559 $data->firstname = $user->firstname;
6560 $data->lastname = $user->lastname;
6561 $data->username = $user->username;
6562 $data->sitename = format_string($site->fullname);
6563 $data->admin = generate_email_signoff();
6565 if (!is_enabled_auth($user->auth)) {
6566 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6567 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6568 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6569 return email_to_user($user, $supportuser, $subject, $message);
6572 $userauth = get_auth_plugin($user->auth);
6573 ['subject' => $subject, 'message' => $message] = $userauth->get_password_change_info($user);
6575 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6576 return email_to_user($user, $supportuser, $subject, $message);
6580 * Check that an email is allowed. It returns an error message if there was a problem.
6582 * @param string $email Content of email
6583 * @return string|false
6585 function email_is_not_allowed($email) {
6586 global $CFG;
6588 // Comparing lowercase domains.
6589 $email = strtolower($email);
6590 if (!empty($CFG->allowemailaddresses)) {
6591 $allowed = explode(' ', strtolower($CFG->allowemailaddresses));
6592 foreach ($allowed as $allowedpattern) {
6593 $allowedpattern = trim($allowedpattern);
6594 if (!$allowedpattern) {
6595 continue;
6597 if (strpos($allowedpattern, '.') === 0) {
6598 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6599 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6600 return false;
6603 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6604 return false;
6607 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6609 } else if (!empty($CFG->denyemailaddresses)) {
6610 $denied = explode(' ', strtolower($CFG->denyemailaddresses));
6611 foreach ($denied as $deniedpattern) {
6612 $deniedpattern = trim($deniedpattern);
6613 if (!$deniedpattern) {
6614 continue;
6616 if (strpos($deniedpattern, '.') === 0) {
6617 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6618 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6619 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6622 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6623 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6628 return false;
6631 // FILE HANDLING.
6634 * Returns local file storage instance
6636 * @return file_storage
6638 function get_file_storage($reset = false) {
6639 global $CFG;
6641 static $fs = null;
6643 if ($reset) {
6644 $fs = null;
6645 return;
6648 if ($fs) {
6649 return $fs;
6652 require_once("$CFG->libdir/filelib.php");
6654 $fs = new file_storage();
6656 return $fs;
6660 * Returns local file storage instance
6662 * @return file_browser
6664 function get_file_browser() {
6665 global $CFG;
6667 static $fb = null;
6669 if ($fb) {
6670 return $fb;
6673 require_once("$CFG->libdir/filelib.php");
6675 $fb = new file_browser();
6677 return $fb;
6681 * Returns file packer
6683 * @param string $mimetype default application/zip
6684 * @return file_packer
6686 function get_file_packer($mimetype='application/zip') {
6687 global $CFG;
6689 static $fp = array();
6691 if (isset($fp[$mimetype])) {
6692 return $fp[$mimetype];
6695 switch ($mimetype) {
6696 case 'application/zip':
6697 case 'application/vnd.moodle.profiling':
6698 $classname = 'zip_packer';
6699 break;
6701 case 'application/x-gzip' :
6702 $classname = 'tgz_packer';
6703 break;
6705 case 'application/vnd.moodle.backup':
6706 $classname = 'mbz_packer';
6707 break;
6709 default:
6710 return false;
6713 require_once("$CFG->libdir/filestorage/$classname.php");
6714 $fp[$mimetype] = new $classname();
6716 return $fp[$mimetype];
6720 * Returns current name of file on disk if it exists.
6722 * @param string $newfile File to be verified
6723 * @return string Current name of file on disk if true
6725 function valid_uploaded_file($newfile) {
6726 if (empty($newfile)) {
6727 return '';
6729 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6730 return $newfile['tmp_name'];
6731 } else {
6732 return '';
6737 * Returns the maximum size for uploading files.
6739 * There are seven possible upload limits:
6740 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6741 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6742 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6743 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6744 * 5. by the Moodle admin in $CFG->maxbytes
6745 * 6. by the teacher in the current course $course->maxbytes
6746 * 7. by the teacher for the current module, eg $assignment->maxbytes
6748 * These last two are passed to this function as arguments (in bytes).
6749 * Anything defined as 0 is ignored.
6750 * The smallest of all the non-zero numbers is returned.
6752 * @todo Finish documenting this function
6754 * @param int $sitebytes Set maximum size
6755 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6756 * @param int $modulebytes Current module ->maxbytes (in bytes)
6757 * @param bool $unused This parameter has been deprecated and is not used any more.
6758 * @return int The maximum size for uploading files.
6760 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6762 if (! $filesize = ini_get('upload_max_filesize')) {
6763 $filesize = '5M';
6765 $minimumsize = get_real_size($filesize);
6767 if ($postsize = ini_get('post_max_size')) {
6768 $postsize = get_real_size($postsize);
6769 if ($postsize < $minimumsize) {
6770 $minimumsize = $postsize;
6774 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6775 $minimumsize = $sitebytes;
6778 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6779 $minimumsize = $coursebytes;
6782 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6783 $minimumsize = $modulebytes;
6786 return $minimumsize;
6790 * Returns the maximum size for uploading files for the current user
6792 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6794 * @param context $context The context in which to check user capabilities
6795 * @param int $sitebytes Set maximum size
6796 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6797 * @param int $modulebytes Current module ->maxbytes (in bytes)
6798 * @param stdClass $user The user
6799 * @param bool $unused This parameter has been deprecated and is not used any more.
6800 * @return int The maximum size for uploading files.
6802 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6803 $unused = false) {
6804 global $USER;
6806 if (empty($user)) {
6807 $user = $USER;
6810 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6811 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6814 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6818 * Returns an array of possible sizes in local language
6820 * Related to {@link get_max_upload_file_size()} - this function returns an
6821 * array of possible sizes in an array, translated to the
6822 * local language.
6824 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6826 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6827 * with the value set to 0. This option will be the first in the list.
6829 * @uses SORT_NUMERIC
6830 * @param int $sitebytes Set maximum size
6831 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6832 * @param int $modulebytes Current module ->maxbytes (in bytes)
6833 * @param int|array $custombytes custom upload size/s which will be added to list,
6834 * Only value/s smaller then maxsize will be added to list.
6835 * @return array
6837 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6838 global $CFG;
6840 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6841 return array();
6844 if ($sitebytes == 0) {
6845 // Will get the minimum of upload_max_filesize or post_max_size.
6846 $sitebytes = get_max_upload_file_size();
6849 $filesize = array();
6850 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6851 5242880, 10485760, 20971520, 52428800, 104857600,
6852 262144000, 524288000, 786432000, 1073741824,
6853 2147483648, 4294967296, 8589934592);
6855 // If custombytes is given and is valid then add it to the list.
6856 if (is_number($custombytes) and $custombytes > 0) {
6857 $custombytes = (int)$custombytes;
6858 if (!in_array($custombytes, $sizelist)) {
6859 $sizelist[] = $custombytes;
6861 } else if (is_array($custombytes)) {
6862 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6865 // Allow maxbytes to be selected if it falls outside the above boundaries.
6866 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6867 // Note: get_real_size() is used in order to prevent problems with invalid values.
6868 $sizelist[] = get_real_size($CFG->maxbytes);
6871 foreach ($sizelist as $sizebytes) {
6872 if ($sizebytes < $maxsize && $sizebytes > 0) {
6873 $filesize[(string)intval($sizebytes)] = display_size($sizebytes, 0);
6877 $limitlevel = '';
6878 $displaysize = '';
6879 if ($modulebytes &&
6880 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6881 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6882 $limitlevel = get_string('activity', 'core');
6883 $displaysize = display_size($modulebytes, 0);
6884 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6886 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6887 $limitlevel = get_string('course', 'core');
6888 $displaysize = display_size($coursebytes, 0);
6889 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6891 } else if ($sitebytes) {
6892 $limitlevel = get_string('site', 'core');
6893 $displaysize = display_size($sitebytes, 0);
6894 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6897 krsort($filesize, SORT_NUMERIC);
6898 if ($limitlevel) {
6899 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6900 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6903 return $filesize;
6907 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6909 * If excludefiles is defined, then that file/directory is ignored
6910 * If getdirs is true, then (sub)directories are included in the output
6911 * If getfiles is true, then files are included in the output
6912 * (at least one of these must be true!)
6914 * @todo Finish documenting this function. Add examples of $excludefile usage.
6916 * @param string $rootdir A given root directory to start from
6917 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6918 * @param bool $descend If true then subdirectories are recursed as well
6919 * @param bool $getdirs If true then (sub)directories are included in the output
6920 * @param bool $getfiles If true then files are included in the output
6921 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6923 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6925 $dirs = array();
6927 if (!$getdirs and !$getfiles) { // Nothing to show.
6928 return $dirs;
6931 if (!is_dir($rootdir)) { // Must be a directory.
6932 return $dirs;
6935 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6936 return $dirs;
6939 if (!is_array($excludefiles)) {
6940 $excludefiles = array($excludefiles);
6943 while (false !== ($file = readdir($dir))) {
6944 $firstchar = substr($file, 0, 1);
6945 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6946 continue;
6948 $fullfile = $rootdir .'/'. $file;
6949 if (filetype($fullfile) == 'dir') {
6950 if ($getdirs) {
6951 $dirs[] = $file;
6953 if ($descend) {
6954 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6955 foreach ($subdirs as $subdir) {
6956 $dirs[] = $file .'/'. $subdir;
6959 } else if ($getfiles) {
6960 $dirs[] = $file;
6963 closedir($dir);
6965 asort($dirs);
6967 return $dirs;
6972 * Adds up all the files in a directory and works out the size.
6974 * @param string $rootdir The directory to start from
6975 * @param string $excludefile A file to exclude when summing directory size
6976 * @return int The summed size of all files and subfiles within the root directory
6978 function get_directory_size($rootdir, $excludefile='') {
6979 global $CFG;
6981 // Do it this way if we can, it's much faster.
6982 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6983 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6984 $output = null;
6985 $return = null;
6986 exec($command, $output, $return);
6987 if (is_array($output)) {
6988 // We told it to return k.
6989 return get_real_size(intval($output[0]).'k');
6993 if (!is_dir($rootdir)) {
6994 // Must be a directory.
6995 return 0;
6998 if (!$dir = @opendir($rootdir)) {
6999 // Can't open it for some reason.
7000 return 0;
7003 $size = 0;
7005 while (false !== ($file = readdir($dir))) {
7006 $firstchar = substr($file, 0, 1);
7007 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
7008 continue;
7010 $fullfile = $rootdir .'/'. $file;
7011 if (filetype($fullfile) == 'dir') {
7012 $size += get_directory_size($fullfile, $excludefile);
7013 } else {
7014 $size += filesize($fullfile);
7017 closedir($dir);
7019 return $size;
7023 * Converts bytes into display form
7025 * @param int $size The size to convert to human readable form
7026 * @param int $decimalplaces If specified, uses fixed number of decimal places
7027 * @param string $fixedunits If specified, uses fixed units (e.g. 'KB')
7028 * @return string Display version of size
7030 function display_size($size, int $decimalplaces = 1, string $fixedunits = ''): string {
7032 static $units;
7034 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
7035 return get_string('unlimited');
7038 if (empty($units)) {
7039 $units[] = get_string('sizeb');
7040 $units[] = get_string('sizekb');
7041 $units[] = get_string('sizemb');
7042 $units[] = get_string('sizegb');
7043 $units[] = get_string('sizetb');
7044 $units[] = get_string('sizepb');
7047 switch ($fixedunits) {
7048 case 'PB' :
7049 $magnitude = 5;
7050 break;
7051 case 'TB' :
7052 $magnitude = 4;
7053 break;
7054 case 'GB' :
7055 $magnitude = 3;
7056 break;
7057 case 'MB' :
7058 $magnitude = 2;
7059 break;
7060 case 'KB' :
7061 $magnitude = 1;
7062 break;
7063 case 'B' :
7064 $magnitude = 0;
7065 break;
7066 case '':
7067 $magnitude = floor(log($size, 1024));
7068 $magnitude = max(0, min(5, $magnitude));
7069 break;
7070 default:
7071 throw new coding_exception('Unknown fixed units value: ' . $fixedunits);
7074 // Special case for magnitude 0 (bytes) - never use decimal places.
7075 $nbsp = "\xc2\xa0";
7076 if ($magnitude === 0) {
7077 return round($size) . $nbsp . $units[$magnitude];
7080 // Convert to specified units.
7081 $sizeinunit = $size / 1024 ** $magnitude;
7083 // Fixed decimal places.
7084 return sprintf('%.' . $decimalplaces . 'f', $sizeinunit) . $nbsp . $units[$magnitude];
7088 * Cleans a given filename by removing suspicious or troublesome characters
7090 * @see clean_param()
7091 * @param string $string file name
7092 * @return string cleaned file name
7094 function clean_filename($string) {
7095 return clean_param($string, PARAM_FILE);
7098 // STRING TRANSLATION.
7101 * Returns the code for the current language
7103 * @category string
7104 * @return string
7106 function current_language() {
7107 global $CFG, $USER, $SESSION, $COURSE;
7109 if (!empty($SESSION->forcelang)) {
7110 // Allows overriding course-forced language (useful for admins to check
7111 // issues in courses whose language they don't understand).
7112 // Also used by some code to temporarily get language-related information in a
7113 // specific language (see force_current_language()).
7114 $return = $SESSION->forcelang;
7116 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
7117 // Course language can override all other settings for this page.
7118 $return = $COURSE->lang;
7120 } else if (!empty($SESSION->lang)) {
7121 // Session language can override other settings.
7122 $return = $SESSION->lang;
7124 } else if (!empty($USER->lang)) {
7125 $return = $USER->lang;
7127 } else if (isset($CFG->lang)) {
7128 $return = $CFG->lang;
7130 } else {
7131 $return = 'en';
7134 // Just in case this slipped in from somewhere by accident.
7135 $return = str_replace('_utf8', '', $return);
7137 return $return;
7141 * Fix the current language to the given language code.
7143 * @param string $lang The language code to use.
7144 * @return void
7146 function fix_current_language(string $lang): void {
7147 global $CFG, $COURSE, $SESSION, $USER;
7149 if (!get_string_manager()->translation_exists($lang)) {
7150 throw new coding_exception("The language pack for $lang is not available");
7153 $fixglobal = '';
7154 $fixlang = 'lang';
7155 if (!empty($SESSION->forcelang)) {
7156 $fixglobal = $SESSION;
7157 $fixlang = 'forcelang';
7158 } else if (!empty($COURSE->id) && $COURSE->id != SITEID && !empty($COURSE->lang)) {
7159 $fixglobal = $COURSE;
7160 } else if (!empty($SESSION->lang)) {
7161 $fixglobal = $SESSION;
7162 } else if (!empty($USER->lang)) {
7163 $fixglobal = $USER;
7164 } else if (isset($CFG->lang)) {
7165 set_config('lang', $lang);
7168 if ($fixglobal) {
7169 $fixglobal->$fixlang = $lang;
7174 * Returns parent language of current active language if defined
7176 * @category string
7177 * @param string $lang null means current language
7178 * @return string
7180 function get_parent_language($lang=null) {
7182 $parentlang = get_string_manager()->get_string('parentlanguage', 'langconfig', null, $lang);
7184 if ($parentlang === 'en') {
7185 $parentlang = '';
7188 return $parentlang;
7192 * Force the current language to get strings and dates localised in the given language.
7194 * After calling this function, all strings will be provided in the given language
7195 * until this function is called again, or equivalent code is run.
7197 * @param string $language
7198 * @return string previous $SESSION->forcelang value
7200 function force_current_language($language) {
7201 global $SESSION;
7202 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
7203 if ($language !== $sessionforcelang) {
7204 // Seting forcelang to null or an empty string disables it's effect.
7205 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
7206 $SESSION->forcelang = $language;
7207 moodle_setlocale();
7210 return $sessionforcelang;
7214 * Returns current string_manager instance.
7216 * The param $forcereload is needed for CLI installer only where the string_manager instance
7217 * must be replaced during the install.php script life time.
7219 * @category string
7220 * @param bool $forcereload shall the singleton be released and new instance created instead?
7221 * @return core_string_manager
7223 function get_string_manager($forcereload=false) {
7224 global $CFG;
7226 static $singleton = null;
7228 if ($forcereload) {
7229 $singleton = null;
7231 if ($singleton === null) {
7232 if (empty($CFG->early_install_lang)) {
7234 $transaliases = array();
7235 if (empty($CFG->langlist)) {
7236 $translist = array();
7237 } else {
7238 $translist = explode(',', $CFG->langlist);
7239 $translist = array_map('trim', $translist);
7240 // Each language in the $CFG->langlist can has an "alias" that would substitute the default language name.
7241 foreach ($translist as $i => $value) {
7242 $parts = preg_split('/\s*\|\s*/', $value, 2);
7243 if (count($parts) == 2) {
7244 $transaliases[$parts[0]] = $parts[1];
7245 $translist[$i] = $parts[0];
7250 if (!empty($CFG->config_php_settings['customstringmanager'])) {
7251 $classname = $CFG->config_php_settings['customstringmanager'];
7253 if (class_exists($classname)) {
7254 $implements = class_implements($classname);
7256 if (isset($implements['core_string_manager'])) {
7257 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7258 return $singleton;
7260 } else {
7261 debugging('Unable to instantiate custom string manager: class '.$classname.
7262 ' does not implement the core_string_manager interface.');
7265 } else {
7266 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7270 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7272 } else {
7273 $singleton = new core_string_manager_install();
7277 return $singleton;
7281 * Returns a localized string.
7283 * Returns the translated string specified by $identifier as
7284 * for $module. Uses the same format files as STphp.
7285 * $a is an object, string or number that can be used
7286 * within translation strings
7288 * eg 'hello {$a->firstname} {$a->lastname}'
7289 * or 'hello {$a}'
7291 * If you would like to directly echo the localized string use
7292 * the function {@link print_string()}
7294 * Example usage of this function involves finding the string you would
7295 * like a local equivalent of and using its identifier and module information
7296 * to retrieve it.<br/>
7297 * If you open moodle/lang/en/moodle.php and look near line 278
7298 * you will find a string to prompt a user for their word for 'course'
7299 * <code>
7300 * $string['course'] = 'Course';
7301 * </code>
7302 * So if you want to display the string 'Course'
7303 * in any language that supports it on your site
7304 * you just need to use the identifier 'course'
7305 * <code>
7306 * $mystring = '<strong>'. get_string('course') .'</strong>';
7307 * or
7308 * </code>
7309 * If the string you want is in another file you'd take a slightly
7310 * different approach. Looking in moodle/lang/en/calendar.php you find
7311 * around line 75:
7312 * <code>
7313 * $string['typecourse'] = 'Course event';
7314 * </code>
7315 * If you want to display the string "Course event" in any language
7316 * supported you would use the identifier 'typecourse' and the module 'calendar'
7317 * (because it is in the file calendar.php):
7318 * <code>
7319 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7320 * </code>
7322 * As a last resort, should the identifier fail to map to a string
7323 * the returned string will be [[ $identifier ]]
7325 * In Moodle 2.3 there is a new argument to this function $lazyload.
7326 * Setting $lazyload to true causes get_string to return a lang_string object
7327 * rather than the string itself. The fetching of the string is then put off until
7328 * the string object is first used. The object can be used by calling it's out
7329 * method or by casting the object to a string, either directly e.g.
7330 * (string)$stringobject
7331 * or indirectly by using the string within another string or echoing it out e.g.
7332 * echo $stringobject
7333 * return "<p>{$stringobject}</p>";
7334 * It is worth noting that using $lazyload and attempting to use the string as an
7335 * array key will cause a fatal error as objects cannot be used as array keys.
7336 * But you should never do that anyway!
7337 * For more information {@link lang_string}
7339 * @category string
7340 * @param string $identifier The key identifier for the localized string
7341 * @param string $component The module where the key identifier is stored,
7342 * usually expressed as the filename in the language pack without the
7343 * .php on the end but can also be written as mod/forum or grade/export/xls.
7344 * If none is specified then moodle.php is used.
7345 * @param string|object|array $a An object, string or number that can be used
7346 * within translation strings
7347 * @param bool $lazyload If set to true a string object is returned instead of
7348 * the string itself. The string then isn't calculated until it is first used.
7349 * @return string The localized string.
7350 * @throws coding_exception
7352 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7353 global $CFG;
7355 // If the lazy load argument has been supplied return a lang_string object
7356 // instead.
7357 // We need to make sure it is true (and a bool) as you will see below there
7358 // used to be a forth argument at one point.
7359 if ($lazyload === true) {
7360 return new lang_string($identifier, $component, $a);
7363 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7364 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7367 // There is now a forth argument again, this time it is a boolean however so
7368 // we can still check for the old extralocations parameter.
7369 if (!is_bool($lazyload) && !empty($lazyload)) {
7370 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7373 if (strpos($component, '/') !== false) {
7374 debugging('The module name you passed to get_string is the deprecated format ' .
7375 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7376 $componentpath = explode('/', $component);
7378 switch ($componentpath[0]) {
7379 case 'mod':
7380 $component = $componentpath[1];
7381 break;
7382 case 'blocks':
7383 case 'block':
7384 $component = 'block_'.$componentpath[1];
7385 break;
7386 case 'enrol':
7387 $component = 'enrol_'.$componentpath[1];
7388 break;
7389 case 'format':
7390 $component = 'format_'.$componentpath[1];
7391 break;
7392 case 'grade':
7393 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7394 break;
7398 $result = get_string_manager()->get_string($identifier, $component, $a);
7400 // Debugging feature lets you display string identifier and component.
7401 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7402 $result .= ' {' . $identifier . '/' . $component . '}';
7404 return $result;
7408 * Converts an array of strings to their localized value.
7410 * @param array $array An array of strings
7411 * @param string $component The language module that these strings can be found in.
7412 * @return stdClass translated strings.
7414 function get_strings($array, $component = '') {
7415 $string = new stdClass;
7416 foreach ($array as $item) {
7417 $string->$item = get_string($item, $component);
7419 return $string;
7423 * Prints out a translated string.
7425 * Prints out a translated string using the return value from the {@link get_string()} function.
7427 * Example usage of this function when the string is in the moodle.php file:<br/>
7428 * <code>
7429 * echo '<strong>';
7430 * print_string('course');
7431 * echo '</strong>';
7432 * </code>
7434 * Example usage of this function when the string is not in the moodle.php file:<br/>
7435 * <code>
7436 * echo '<h1>';
7437 * print_string('typecourse', 'calendar');
7438 * echo '</h1>';
7439 * </code>
7441 * @category string
7442 * @param string $identifier The key identifier for the localized string
7443 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7444 * @param string|object|array $a An object, string or number that can be used within translation strings
7446 function print_string($identifier, $component = '', $a = null) {
7447 echo get_string($identifier, $component, $a);
7451 * Returns a list of charset codes
7453 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7454 * (checking that such charset is supported by the texlib library!)
7456 * @return array And associative array with contents in the form of charset => charset
7458 function get_list_of_charsets() {
7460 $charsets = array(
7461 'EUC-JP' => 'EUC-JP',
7462 'ISO-2022-JP'=> 'ISO-2022-JP',
7463 'ISO-8859-1' => 'ISO-8859-1',
7464 'SHIFT-JIS' => 'SHIFT-JIS',
7465 'GB2312' => 'GB2312',
7466 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7467 'UTF-8' => 'UTF-8');
7469 asort($charsets);
7471 return $charsets;
7475 * Returns a list of valid and compatible themes
7477 * @return array
7479 function get_list_of_themes() {
7480 global $CFG;
7482 $themes = array();
7484 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7485 $themelist = explode(',', $CFG->themelist);
7486 } else {
7487 $themelist = array_keys(core_component::get_plugin_list("theme"));
7490 foreach ($themelist as $key => $themename) {
7491 $theme = theme_config::load($themename);
7492 $themes[$themename] = $theme;
7495 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7497 return $themes;
7501 * Factory function for emoticon_manager
7503 * @return emoticon_manager singleton
7505 function get_emoticon_manager() {
7506 static $singleton = null;
7508 if (is_null($singleton)) {
7509 $singleton = new emoticon_manager();
7512 return $singleton;
7516 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7518 * Whenever this manager mentiones 'emoticon object', the following data
7519 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7520 * altidentifier and altcomponent
7522 * @see admin_setting_emoticons
7524 * @copyright 2010 David Mudrak
7525 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7527 class emoticon_manager {
7530 * Returns the currently enabled emoticons
7532 * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
7533 * @return array of emoticon objects
7535 public function get_emoticons($selectable = false) {
7536 global $CFG;
7537 $notselectable = ['martin', 'egg'];
7539 if (empty($CFG->emoticons)) {
7540 return array();
7543 $emoticons = $this->decode_stored_config($CFG->emoticons);
7545 if (!is_array($emoticons)) {
7546 // Something is wrong with the format of stored setting.
7547 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7548 return array();
7550 if ($selectable) {
7551 foreach ($emoticons as $index => $emote) {
7552 if (in_array($emote->altidentifier, $notselectable)) {
7553 // Skip this one.
7554 unset($emoticons[$index]);
7559 return $emoticons;
7563 * Converts emoticon object into renderable pix_emoticon object
7565 * @param stdClass $emoticon emoticon object
7566 * @param array $attributes explicit HTML attributes to set
7567 * @return pix_emoticon
7569 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7570 $stringmanager = get_string_manager();
7571 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7572 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7573 } else {
7574 $alt = s($emoticon->text);
7576 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7580 * Encodes the array of emoticon objects into a string storable in config table
7582 * @see self::decode_stored_config()
7583 * @param array $emoticons array of emtocion objects
7584 * @return string
7586 public function encode_stored_config(array $emoticons) {
7587 return json_encode($emoticons);
7591 * Decodes the string into an array of emoticon objects
7593 * @see self::encode_stored_config()
7594 * @param string $encoded
7595 * @return string|null
7597 public function decode_stored_config($encoded) {
7598 $decoded = json_decode($encoded);
7599 if (!is_array($decoded)) {
7600 return null;
7602 return $decoded;
7606 * Returns default set of emoticons supported by Moodle
7608 * @return array of sdtClasses
7610 public function default_emoticons() {
7611 return array(
7612 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7613 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7614 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7615 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7616 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7617 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7618 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7619 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7620 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7621 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7622 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7623 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7624 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7625 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7626 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7627 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7628 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7629 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7630 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7631 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7632 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7633 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7634 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7635 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7636 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7637 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7638 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7639 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7640 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7641 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7646 * Helper method preparing the stdClass with the emoticon properties
7648 * @param string|array $text or array of strings
7649 * @param string $imagename to be used by {@link pix_emoticon}
7650 * @param string $altidentifier alternative string identifier, null for no alt
7651 * @param string $altcomponent where the alternative string is defined
7652 * @param string $imagecomponent to be used by {@link pix_emoticon}
7653 * @return stdClass
7655 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7656 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7657 return (object)array(
7658 'text' => $text,
7659 'imagename' => $imagename,
7660 'imagecomponent' => $imagecomponent,
7661 'altidentifier' => $altidentifier,
7662 'altcomponent' => $altcomponent,
7667 // ENCRYPTION.
7670 * rc4encrypt
7672 * @param string $data Data to encrypt.
7673 * @return string The now encrypted data.
7675 function rc4encrypt($data) {
7676 return endecrypt(get_site_identifier(), $data, '');
7680 * rc4decrypt
7682 * @param string $data Data to decrypt.
7683 * @return string The now decrypted data.
7685 function rc4decrypt($data) {
7686 return endecrypt(get_site_identifier(), $data, 'de');
7690 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7692 * @todo Finish documenting this function
7694 * @param string $pwd The password to use when encrypting or decrypting
7695 * @param string $data The data to be decrypted/encrypted
7696 * @param string $case Either 'de' for decrypt or '' for encrypt
7697 * @return string
7699 function endecrypt ($pwd, $data, $case) {
7701 if ($case == 'de') {
7702 $data = urldecode($data);
7705 $key[] = '';
7706 $box[] = '';
7707 $pwdlength = strlen($pwd);
7709 for ($i = 0; $i <= 255; $i++) {
7710 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7711 $box[$i] = $i;
7714 $x = 0;
7716 for ($i = 0; $i <= 255; $i++) {
7717 $x = ($x + $box[$i] + $key[$i]) % 256;
7718 $tempswap = $box[$i];
7719 $box[$i] = $box[$x];
7720 $box[$x] = $tempswap;
7723 $cipher = '';
7725 $a = 0;
7726 $j = 0;
7728 for ($i = 0; $i < strlen($data); $i++) {
7729 $a = ($a + 1) % 256;
7730 $j = ($j + $box[$a]) % 256;
7731 $temp = $box[$a];
7732 $box[$a] = $box[$j];
7733 $box[$j] = $temp;
7734 $k = $box[(($box[$a] + $box[$j]) % 256)];
7735 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7736 $cipher .= chr($cipherby);
7739 if ($case == 'de') {
7740 $cipher = urldecode(urlencode($cipher));
7741 } else {
7742 $cipher = urlencode($cipher);
7745 return $cipher;
7748 // ENVIRONMENT CHECKING.
7751 * This method validates a plug name. It is much faster than calling clean_param.
7753 * @param string $name a string that might be a plugin name.
7754 * @return bool if this string is a valid plugin name.
7756 function is_valid_plugin_name($name) {
7757 // This does not work for 'mod', bad luck, use any other type.
7758 return core_component::is_valid_plugin_name('tool', $name);
7762 * Get a list of all the plugins of a given type that define a certain API function
7763 * in a certain file. The plugin component names and function names are returned.
7765 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7766 * @param string $function the part of the name of the function after the
7767 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7768 * names like report_courselist_hook.
7769 * @param string $file the name of file within the plugin that defines the
7770 * function. Defaults to lib.php.
7771 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7772 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7774 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7775 global $CFG;
7777 // We don't include here as all plugin types files would be included.
7778 $plugins = get_plugins_with_function($function, $file, false);
7780 if (empty($plugins[$plugintype])) {
7781 return array();
7784 $allplugins = core_component::get_plugin_list($plugintype);
7786 // Reformat the array and include the files.
7787 $pluginfunctions = array();
7788 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7790 // Check that it has not been removed and the file is still available.
7791 if (!empty($allplugins[$pluginname])) {
7793 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7794 if (file_exists($filepath)) {
7795 include_once($filepath);
7797 // Now that the file is loaded, we must verify the function still exists.
7798 if (function_exists($functionname)) {
7799 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7800 } else {
7801 // Invalidate the cache for next run.
7802 \cache_helper::invalidate_by_definition('core', 'plugin_functions');
7808 return $pluginfunctions;
7812 * Get a list of all the plugins that define a certain API function in a certain file.
7814 * @param string $function the part of the name of the function after the
7815 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7816 * names like report_courselist_hook.
7817 * @param string $file the name of file within the plugin that defines the
7818 * function. Defaults to lib.php.
7819 * @param bool $include Whether to include the files that contain the functions or not.
7820 * @return array with [plugintype][plugin] = functionname
7822 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7823 global $CFG;
7825 if (during_initial_install() || isset($CFG->upgraderunning)) {
7826 // API functions _must not_ be called during an installation or upgrade.
7827 return [];
7830 $cache = \cache::make('core', 'plugin_functions');
7832 // Including both although I doubt that we will find two functions definitions with the same name.
7833 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7834 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7835 $pluginfunctions = $cache->get($key);
7836 $dirty = false;
7838 // Use the plugin manager to check that plugins are currently installed.
7839 $pluginmanager = \core_plugin_manager::instance();
7841 if ($pluginfunctions !== false) {
7843 // Checking that the files are still available.
7844 foreach ($pluginfunctions as $plugintype => $plugins) {
7846 $allplugins = \core_component::get_plugin_list($plugintype);
7847 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7848 foreach ($plugins as $plugin => $function) {
7849 if (!isset($installedplugins[$plugin])) {
7850 // Plugin code is still present on disk but it is not installed.
7851 $dirty = true;
7852 break 2;
7855 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7856 if (empty($allplugins[$plugin])) {
7857 $dirty = true;
7858 break 2;
7861 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7862 if ($include && $fileexists) {
7863 // Include the files if it was requested.
7864 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7865 } else if (!$fileexists) {
7866 // If the file is not available any more it should not be returned.
7867 $dirty = true;
7868 break 2;
7871 // Check if the function still exists in the file.
7872 if ($include && !function_exists($function)) {
7873 $dirty = true;
7874 break 2;
7879 // If the cache is dirty, we should fall through and let it rebuild.
7880 if (!$dirty) {
7881 return $pluginfunctions;
7885 $pluginfunctions = array();
7887 // To fill the cached. Also, everything should continue working with cache disabled.
7888 $plugintypes = \core_component::get_plugin_types();
7889 foreach ($plugintypes as $plugintype => $unused) {
7891 // We need to include files here.
7892 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7893 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7894 foreach ($pluginswithfile as $plugin => $notused) {
7896 if (!isset($installedplugins[$plugin])) {
7897 continue;
7900 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7902 $pluginfunction = false;
7903 if (function_exists($fullfunction)) {
7904 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7905 $pluginfunction = $fullfunction;
7907 } else if ($plugintype === 'mod') {
7908 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7909 $shortfunction = $plugin . '_' . $function;
7910 if (function_exists($shortfunction)) {
7911 $pluginfunction = $shortfunction;
7915 if ($pluginfunction) {
7916 if (empty($pluginfunctions[$plugintype])) {
7917 $pluginfunctions[$plugintype] = array();
7919 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7924 $cache->set($key, $pluginfunctions);
7926 return $pluginfunctions;
7931 * Lists plugin-like directories within specified directory
7933 * This function was originally used for standard Moodle plugins, please use
7934 * new core_component::get_plugin_list() now.
7936 * This function is used for general directory listing and backwards compatility.
7938 * @param string $directory relative directory from root
7939 * @param string $exclude dir name to exclude from the list (defaults to none)
7940 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7941 * @return array Sorted array of directory names found under the requested parameters
7943 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7944 global $CFG;
7946 $plugins = array();
7948 if (empty($basedir)) {
7949 $basedir = $CFG->dirroot .'/'. $directory;
7951 } else {
7952 $basedir = $basedir .'/'. $directory;
7955 if ($CFG->debugdeveloper and empty($exclude)) {
7956 // Make sure devs do not use this to list normal plugins,
7957 // this is intended for general directories that are not plugins!
7959 $subtypes = core_component::get_plugin_types();
7960 if (in_array($basedir, $subtypes)) {
7961 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7963 unset($subtypes);
7966 $ignorelist = array_flip(array_filter([
7967 'CVS',
7968 '_vti_cnf',
7969 'amd',
7970 'classes',
7971 'simpletest',
7972 'tests',
7973 'templates',
7974 'yui',
7975 $exclude,
7976 ]));
7978 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7979 if (!$dirhandle = opendir($basedir)) {
7980 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7981 return array();
7983 while (false !== ($dir = readdir($dirhandle))) {
7984 if (strpos($dir, '.') === 0) {
7985 // Ignore directories starting with .
7986 // These are treated as hidden directories.
7987 continue;
7989 if (array_key_exists($dir, $ignorelist)) {
7990 // This directory features on the ignore list.
7991 continue;
7993 if (filetype($basedir .'/'. $dir) != 'dir') {
7994 continue;
7996 $plugins[] = $dir;
7998 closedir($dirhandle);
8000 if ($plugins) {
8001 asort($plugins);
8003 return $plugins;
8007 * Invoke plugin's callback functions
8009 * @param string $type plugin type e.g. 'mod'
8010 * @param string $name plugin name
8011 * @param string $feature feature name
8012 * @param string $action feature's action
8013 * @param array $params parameters of callback function, should be an array
8014 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
8015 * @return mixed
8017 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
8019 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
8020 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
8024 * Invoke component's callback functions
8026 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
8027 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
8028 * @param array $params parameters of callback function
8029 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
8030 * @return mixed
8032 function component_callback($component, $function, array $params = array(), $default = null) {
8034 $functionname = component_callback_exists($component, $function);
8036 if ($params && (array_keys($params) !== range(0, count($params) - 1))) {
8037 // PHP 8 allows to have associative arrays in the call_user_func_array() parameters but
8038 // PHP 7 does not. Using associative arrays can result in different behavior in different PHP versions.
8039 // See https://php.watch/versions/8.0/named-parameters#named-params-call_user_func_array
8040 // This check can be removed when minimum PHP version for Moodle is raised to 8.
8041 debugging('Parameters array can not be an associative array while Moodle supports both PHP 7 and PHP 8.',
8042 DEBUG_DEVELOPER);
8043 $params = array_values($params);
8046 if ($functionname) {
8047 // Function exists, so just return function result.
8048 $ret = call_user_func_array($functionname, $params);
8049 if (is_null($ret)) {
8050 return $default;
8051 } else {
8052 return $ret;
8055 return $default;
8059 * Determine if a component callback exists and return the function name to call. Note that this
8060 * function will include the required library files so that the functioname returned can be
8061 * called directly.
8063 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
8064 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
8065 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
8066 * @throws coding_exception if invalid component specfied
8068 function component_callback_exists($component, $function) {
8069 global $CFG; // This is needed for the inclusions.
8071 $cleancomponent = clean_param($component, PARAM_COMPONENT);
8072 if (empty($cleancomponent)) {
8073 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8075 $component = $cleancomponent;
8077 list($type, $name) = core_component::normalize_component($component);
8078 $component = $type . '_' . $name;
8080 $oldfunction = $name.'_'.$function;
8081 $function = $component.'_'.$function;
8083 $dir = core_component::get_component_directory($component);
8084 if (empty($dir)) {
8085 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8088 // Load library and look for function.
8089 if (file_exists($dir.'/lib.php')) {
8090 require_once($dir.'/lib.php');
8093 if (!function_exists($function) and function_exists($oldfunction)) {
8094 if ($type !== 'mod' and $type !== 'core') {
8095 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
8097 $function = $oldfunction;
8100 if (function_exists($function)) {
8101 return $function;
8103 return false;
8107 * Call the specified callback method on the provided class.
8109 * If the callback returns null, then the default value is returned instead.
8110 * If the class does not exist, then the default value is returned.
8112 * @param string $classname The name of the class to call upon.
8113 * @param string $methodname The name of the staticically defined method on the class.
8114 * @param array $params The arguments to pass into the method.
8115 * @param mixed $default The default value.
8116 * @return mixed The return value.
8118 function component_class_callback($classname, $methodname, array $params, $default = null) {
8119 if (!class_exists($classname)) {
8120 return $default;
8123 if (!method_exists($classname, $methodname)) {
8124 return $default;
8127 $fullfunction = $classname . '::' . $methodname;
8128 $result = call_user_func_array($fullfunction, $params);
8130 if (null === $result) {
8131 return $default;
8132 } else {
8133 return $result;
8138 * Checks whether a plugin supports a specified feature.
8140 * @param string $type Plugin type e.g. 'mod'
8141 * @param string $name Plugin name e.g. 'forum'
8142 * @param string $feature Feature code (FEATURE_xx constant)
8143 * @param mixed $default default value if feature support unknown
8144 * @return mixed Feature result (false if not supported, null if feature is unknown,
8145 * otherwise usually true but may have other feature-specific value such as array)
8146 * @throws coding_exception
8148 function plugin_supports($type, $name, $feature, $default = null) {
8149 global $CFG;
8151 if ($type === 'mod' and $name === 'NEWMODULE') {
8152 // Somebody forgot to rename the module template.
8153 return false;
8156 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
8157 if (empty($component)) {
8158 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8161 $function = null;
8163 if ($type === 'mod') {
8164 // We need this special case because we support subplugins in modules,
8165 // otherwise it would end up in infinite loop.
8166 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8167 include_once("$CFG->dirroot/mod/$name/lib.php");
8168 $function = $component.'_supports';
8169 if (!function_exists($function)) {
8170 // Legacy non-frankenstyle function name.
8171 $function = $name.'_supports';
8175 } else {
8176 if (!$path = core_component::get_plugin_directory($type, $name)) {
8177 // Non existent plugin type.
8178 return false;
8180 if (file_exists("$path/lib.php")) {
8181 include_once("$path/lib.php");
8182 $function = $component.'_supports';
8186 if ($function and function_exists($function)) {
8187 $supports = $function($feature);
8188 if (is_null($supports)) {
8189 // Plugin does not know - use default.
8190 return $default;
8191 } else {
8192 return $supports;
8196 // Plugin does not care, so use default.
8197 return $default;
8201 * Returns true if the current version of PHP is greater that the specified one.
8203 * @todo Check PHP version being required here is it too low?
8205 * @param string $version The version of php being tested.
8206 * @return bool
8208 function check_php_version($version='5.2.4') {
8209 return (version_compare(phpversion(), $version) >= 0);
8213 * Determine if moodle installation requires update.
8215 * Checks version numbers of main code and all plugins to see
8216 * if there are any mismatches.
8218 * @return bool
8220 function moodle_needs_upgrading() {
8221 global $CFG;
8223 if (empty($CFG->version)) {
8224 return true;
8227 // There is no need to purge plugininfo caches here because
8228 // these caches are not used during upgrade and they are purged after
8229 // every upgrade.
8231 if (empty($CFG->allversionshash)) {
8232 return true;
8235 $hash = core_component::get_all_versions_hash();
8237 return ($hash !== $CFG->allversionshash);
8241 * Returns the major version of this site
8243 * Moodle version numbers consist of three numbers separated by a dot, for
8244 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
8245 * called major version. This function extracts the major version from either
8246 * $CFG->release (default) or eventually from the $release variable defined in
8247 * the main version.php.
8249 * @param bool $fromdisk should the version if source code files be used
8250 * @return string|false the major version like '2.3', false if could not be determined
8252 function moodle_major_version($fromdisk = false) {
8253 global $CFG;
8255 if ($fromdisk) {
8256 $release = null;
8257 require($CFG->dirroot.'/version.php');
8258 if (empty($release)) {
8259 return false;
8262 } else {
8263 if (empty($CFG->release)) {
8264 return false;
8266 $release = $CFG->release;
8269 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8270 return $matches[0];
8271 } else {
8272 return false;
8276 // MISCELLANEOUS.
8279 * Gets the system locale
8281 * @return string Retuns the current locale.
8283 function moodle_getlocale() {
8284 global $CFG;
8286 // Fetch the correct locale based on ostype.
8287 if ($CFG->ostype == 'WINDOWS') {
8288 $stringtofetch = 'localewin';
8289 } else {
8290 $stringtofetch = 'locale';
8293 if (!empty($CFG->locale)) { // Override locale for all language packs.
8294 return $CFG->locale;
8297 return get_string($stringtofetch, 'langconfig');
8301 * Sets the system locale
8303 * @category string
8304 * @param string $locale Can be used to force a locale
8306 function moodle_setlocale($locale='') {
8307 global $CFG;
8309 static $currentlocale = ''; // Last locale caching.
8311 $oldlocale = $currentlocale;
8313 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8314 if (!empty($locale)) {
8315 $currentlocale = $locale;
8316 } else {
8317 $currentlocale = moodle_getlocale();
8320 // Do nothing if locale already set up.
8321 if ($oldlocale == $currentlocale) {
8322 return;
8325 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8326 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8327 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8329 // Get current values.
8330 $monetary= setlocale (LC_MONETARY, 0);
8331 $numeric = setlocale (LC_NUMERIC, 0);
8332 $ctype = setlocale (LC_CTYPE, 0);
8333 if ($CFG->ostype != 'WINDOWS') {
8334 $messages= setlocale (LC_MESSAGES, 0);
8336 // Set locale to all.
8337 $result = setlocale (LC_ALL, $currentlocale);
8338 // If setting of locale fails try the other utf8 or utf-8 variant,
8339 // some operating systems support both (Debian), others just one (OSX).
8340 if ($result === false) {
8341 if (stripos($currentlocale, '.UTF-8') !== false) {
8342 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8343 setlocale (LC_ALL, $newlocale);
8344 } else if (stripos($currentlocale, '.UTF8') !== false) {
8345 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8346 setlocale (LC_ALL, $newlocale);
8349 // Set old values.
8350 setlocale (LC_MONETARY, $monetary);
8351 setlocale (LC_NUMERIC, $numeric);
8352 if ($CFG->ostype != 'WINDOWS') {
8353 setlocale (LC_MESSAGES, $messages);
8355 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8356 // To workaround a well-known PHP problem with Turkish letter Ii.
8357 setlocale (LC_CTYPE, $ctype);
8362 * Count words in a string.
8364 * Words are defined as things between whitespace.
8366 * @category string
8367 * @param string $string The text to be searched for words. May be HTML.
8368 * @return int The count of words in the specified string
8370 function count_words($string) {
8371 // Before stripping tags, add a space after the close tag of anything that is not obviously inline.
8372 // Also, br is a special case because it definitely delimits a word, but has no close tag.
8373 $string = preg_replace('~
8374 ( # Capture the tag we match.
8375 </ # Start of close tag.
8376 (?! # Do not match any of these specific close tag names.
8377 a> | b> | del> | em> | i> |
8378 ins> | s> | small> | span> |
8379 strong> | sub> | sup> | u>
8381 \w+ # But, apart from those execptions, match any tag name.
8382 > # End of close tag.
8384 <br> | <br\s*/> # Special cases that are not close tags.
8386 ~x', '$1 ', $string); // Add a space after the close tag.
8387 // Now remove HTML tags.
8388 $string = strip_tags($string);
8389 // Decode HTML entities.
8390 $string = html_entity_decode($string);
8392 // Now, the word count is the number of blocks of characters separated
8393 // by any sort of space. That seems to be the definition used by all other systems.
8394 // To be precise about what is considered to separate words:
8395 // * Anything that Unicode considers a 'Separator'
8396 // * Anything that Unicode considers a 'Control character'
8397 // * An em- or en- dash.
8398 return count(preg_split('~[\p{Z}\p{Cc}—–]+~u', $string, -1, PREG_SPLIT_NO_EMPTY));
8402 * Count letters in a string.
8404 * Letters are defined as chars not in tags and different from whitespace.
8406 * @category string
8407 * @param string $string The text to be searched for letters. May be HTML.
8408 * @return int The count of letters in the specified text.
8410 function count_letters($string) {
8411 $string = strip_tags($string); // Tags are out now.
8412 $string = html_entity_decode($string);
8413 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8415 return core_text::strlen($string);
8419 * Generate and return a random string of the specified length.
8421 * @param int $length The length of the string to be created.
8422 * @return string
8424 function random_string($length=15) {
8425 $randombytes = random_bytes_emulate($length);
8426 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8427 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8428 $pool .= '0123456789';
8429 $poollen = strlen($pool);
8430 $string = '';
8431 for ($i = 0; $i < $length; $i++) {
8432 $rand = ord($randombytes[$i]);
8433 $string .= substr($pool, ($rand%($poollen)), 1);
8435 return $string;
8439 * Generate a complex random string (useful for md5 salts)
8441 * This function is based on the above {@link random_string()} however it uses a
8442 * larger pool of characters and generates a string between 24 and 32 characters
8444 * @param int $length Optional if set generates a string to exactly this length
8445 * @return string
8447 function complex_random_string($length=null) {
8448 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8449 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8450 $poollen = strlen($pool);
8451 if ($length===null) {
8452 $length = floor(rand(24, 32));
8454 $randombytes = random_bytes_emulate($length);
8455 $string = '';
8456 for ($i = 0; $i < $length; $i++) {
8457 $rand = ord($randombytes[$i]);
8458 $string .= $pool[($rand%$poollen)];
8460 return $string;
8464 * Try to generates cryptographically secure pseudo-random bytes.
8466 * Note this is achieved by fallbacking between:
8467 * - PHP 7 random_bytes().
8468 * - OpenSSL openssl_random_pseudo_bytes().
8469 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8471 * @param int $length requested length in bytes
8472 * @return string binary data
8474 function random_bytes_emulate($length) {
8475 global $CFG;
8476 if ($length <= 0) {
8477 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8478 return '';
8480 if (function_exists('random_bytes')) {
8481 // Use PHP 7 goodness.
8482 $hash = @random_bytes($length);
8483 if ($hash !== false) {
8484 return $hash;
8487 if (function_exists('openssl_random_pseudo_bytes')) {
8488 // If you have the openssl extension enabled.
8489 $hash = openssl_random_pseudo_bytes($length);
8490 if ($hash !== false) {
8491 return $hash;
8495 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8496 $staticdata = serialize($CFG) . serialize($_SERVER);
8497 $hash = '';
8498 do {
8499 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8500 } while (strlen($hash) < $length);
8502 return substr($hash, 0, $length);
8506 * Given some text (which may contain HTML) and an ideal length,
8507 * this function truncates the text neatly on a word boundary if possible
8509 * @category string
8510 * @param string $text text to be shortened
8511 * @param int $ideal ideal string length
8512 * @param boolean $exact if false, $text will not be cut mid-word
8513 * @param string $ending The string to append if the passed string is truncated
8514 * @return string $truncate shortened string
8516 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8517 // If the plain text is shorter than the maximum length, return the whole text.
8518 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8519 return $text;
8522 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8523 // and only tag in its 'line'.
8524 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8526 $totallength = core_text::strlen($ending);
8527 $truncate = '';
8529 // This array stores information about open and close tags and their position
8530 // in the truncated string. Each item in the array is an object with fields
8531 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8532 // (byte position in truncated text).
8533 $tagdetails = array();
8535 foreach ($lines as $linematchings) {
8536 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8537 if (!empty($linematchings[1])) {
8538 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8539 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8540 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8541 // Record closing tag.
8542 $tagdetails[] = (object) array(
8543 'open' => false,
8544 'tag' => core_text::strtolower($tagmatchings[1]),
8545 'pos' => core_text::strlen($truncate),
8548 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8549 // Record opening tag.
8550 $tagdetails[] = (object) array(
8551 'open' => true,
8552 'tag' => core_text::strtolower($tagmatchings[1]),
8553 'pos' => core_text::strlen($truncate),
8555 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8556 $tagdetails[] = (object) array(
8557 'open' => true,
8558 'tag' => core_text::strtolower('if'),
8559 'pos' => core_text::strlen($truncate),
8561 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8562 $tagdetails[] = (object) array(
8563 'open' => false,
8564 'tag' => core_text::strtolower('if'),
8565 'pos' => core_text::strlen($truncate),
8569 // Add html-tag to $truncate'd text.
8570 $truncate .= $linematchings[1];
8573 // Calculate the length of the plain text part of the line; handle entities as one character.
8574 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8575 if ($totallength + $contentlength > $ideal) {
8576 // The number of characters which are left.
8577 $left = $ideal - $totallength;
8578 $entitieslength = 0;
8579 // Search for html entities.
8580 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)) {
8581 // Calculate the real length of all entities in the legal range.
8582 foreach ($entities[0] as $entity) {
8583 if ($entity[1]+1-$entitieslength <= $left) {
8584 $left--;
8585 $entitieslength += core_text::strlen($entity[0]);
8586 } else {
8587 // No more characters left.
8588 break;
8592 $breakpos = $left + $entitieslength;
8594 // If the words shouldn't be cut in the middle...
8595 if (!$exact) {
8596 // Search the last occurence of a space.
8597 for (; $breakpos > 0; $breakpos--) {
8598 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8599 if ($char === '.' or $char === ' ') {
8600 $breakpos += 1;
8601 break;
8602 } else if (strlen($char) > 2) {
8603 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8604 $breakpos += 1;
8605 break;
8610 if ($breakpos == 0) {
8611 // This deals with the test_shorten_text_no_spaces case.
8612 $breakpos = $left + $entitieslength;
8613 } else if ($breakpos > $left + $entitieslength) {
8614 // This deals with the previous for loop breaking on the first char.
8615 $breakpos = $left + $entitieslength;
8618 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8619 // Maximum length is reached, so get off the loop.
8620 break;
8621 } else {
8622 $truncate .= $linematchings[2];
8623 $totallength += $contentlength;
8626 // If the maximum length is reached, get off the loop.
8627 if ($totallength >= $ideal) {
8628 break;
8632 // Add the defined ending to the text.
8633 $truncate .= $ending;
8635 // Now calculate the list of open html tags based on the truncate position.
8636 $opentags = array();
8637 foreach ($tagdetails as $taginfo) {
8638 if ($taginfo->open) {
8639 // Add tag to the beginning of $opentags list.
8640 array_unshift($opentags, $taginfo->tag);
8641 } else {
8642 // Can have multiple exact same open tags, close the last one.
8643 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8644 if ($pos !== false) {
8645 unset($opentags[$pos]);
8650 // Close all unclosed html-tags.
8651 foreach ($opentags as $tag) {
8652 if ($tag === 'if') {
8653 $truncate .= '<!--<![endif]-->';
8654 } else {
8655 $truncate .= '</' . $tag . '>';
8659 return $truncate;
8663 * Shortens a given filename by removing characters positioned after the ideal string length.
8664 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8665 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8667 * @param string $filename file name
8668 * @param int $length ideal string length
8669 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8670 * @return string $shortened shortened file name
8672 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8673 $shortened = $filename;
8674 // Extract a part of the filename if it's char size exceeds the ideal string length.
8675 if (core_text::strlen($filename) > $length) {
8676 // Exclude extension if present in filename.
8677 $mimetypes = get_mimetypes_array();
8678 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8679 if ($extension && !empty($mimetypes[$extension])) {
8680 $basename = pathinfo($filename, PATHINFO_FILENAME);
8681 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8682 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8683 $shortened .= '.' . $extension;
8684 } else {
8685 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8686 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8689 return $shortened;
8693 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8695 * @param array $path The paths to reduce the length.
8696 * @param int $length Ideal string length
8697 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8698 * @return array $result Shortened paths in array.
8700 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8701 $result = null;
8703 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8704 $carry[] = shorten_filename($singlepath, $length, $includehash);
8705 return $carry;
8706 }, []);
8708 return $result;
8712 * Given dates in seconds, how many weeks is the date from startdate
8713 * The first week is 1, the second 2 etc ...
8715 * @param int $startdate Timestamp for the start date
8716 * @param int $thedate Timestamp for the end date
8717 * @return string
8719 function getweek ($startdate, $thedate) {
8720 if ($thedate < $startdate) {
8721 return 0;
8724 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8728 * Returns a randomly generated password of length $maxlen. inspired by
8730 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8731 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8733 * @param int $maxlen The maximum size of the password being generated.
8734 * @return string
8736 function generate_password($maxlen=10) {
8737 global $CFG;
8739 if (empty($CFG->passwordpolicy)) {
8740 $fillers = PASSWORD_DIGITS;
8741 $wordlist = file($CFG->wordlist);
8742 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8743 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8744 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8745 $password = $word1 . $filler1 . $word2;
8746 } else {
8747 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8748 $digits = $CFG->minpassworddigits;
8749 $lower = $CFG->minpasswordlower;
8750 $upper = $CFG->minpasswordupper;
8751 $nonalphanum = $CFG->minpasswordnonalphanum;
8752 $total = $lower + $upper + $digits + $nonalphanum;
8753 // Var minlength should be the greater one of the two ( $minlen and $total ).
8754 $minlen = $minlen < $total ? $total : $minlen;
8755 // Var maxlen can never be smaller than minlen.
8756 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8757 $additional = $maxlen - $total;
8759 // Make sure we have enough characters to fulfill
8760 // complexity requirements.
8761 $passworddigits = PASSWORD_DIGITS;
8762 while ($digits > strlen($passworddigits)) {
8763 $passworddigits .= PASSWORD_DIGITS;
8765 $passwordlower = PASSWORD_LOWER;
8766 while ($lower > strlen($passwordlower)) {
8767 $passwordlower .= PASSWORD_LOWER;
8769 $passwordupper = PASSWORD_UPPER;
8770 while ($upper > strlen($passwordupper)) {
8771 $passwordupper .= PASSWORD_UPPER;
8773 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8774 while ($nonalphanum > strlen($passwordnonalphanum)) {
8775 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8778 // Now mix and shuffle it all.
8779 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8780 substr(str_shuffle ($passwordupper), 0, $upper) .
8781 substr(str_shuffle ($passworddigits), 0, $digits) .
8782 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8783 substr(str_shuffle ($passwordlower .
8784 $passwordupper .
8785 $passworddigits .
8786 $passwordnonalphanum), 0 , $additional));
8789 return substr ($password, 0, $maxlen);
8793 * Given a float, prints it nicely.
8794 * Localized floats must not be used in calculations!
8796 * The stripzeros feature is intended for making numbers look nicer in small
8797 * areas where it is not necessary to indicate the degree of accuracy by showing
8798 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8799 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8801 * @param float $float The float to print
8802 * @param int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision).
8803 * @param bool $localized use localized decimal separator
8804 * @param bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after
8805 * the decimal point are always striped if $decimalpoints is -1.
8806 * @return string locale float
8808 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8809 if (is_null($float)) {
8810 return '';
8812 if ($localized) {
8813 $separator = get_string('decsep', 'langconfig');
8814 } else {
8815 $separator = '.';
8817 if ($decimalpoints == -1) {
8818 // The following counts the number of decimals.
8819 // It is safe as both floatval() and round() functions have same behaviour when non-numeric values are provided.
8820 $floatval = floatval($float);
8821 for ($decimalpoints = 0; $floatval != round($float, $decimalpoints); $decimalpoints++);
8824 $result = number_format($float, $decimalpoints, $separator, '');
8825 if ($stripzeros && $decimalpoints > 0) {
8826 // Remove zeros and final dot if not needed.
8827 // However, only do this if there is a decimal point!
8828 $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
8830 return $result;
8834 * Converts locale specific floating point/comma number back to standard PHP float value
8835 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8837 * @param string $localefloat locale aware float representation
8838 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8839 * @return mixed float|bool - false or the parsed float.
8841 function unformat_float($localefloat, $strict = false) {
8842 $localefloat = trim($localefloat);
8844 if ($localefloat == '') {
8845 return null;
8848 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8849 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8851 if ($strict && !is_numeric($localefloat)) {
8852 return false;
8855 return (float)$localefloat;
8859 * Given a simple array, this shuffles it up just like shuffle()
8860 * Unlike PHP's shuffle() this function works on any machine.
8862 * @param array $array The array to be rearranged
8863 * @return array
8865 function swapshuffle($array) {
8867 $last = count($array) - 1;
8868 for ($i = 0; $i <= $last; $i++) {
8869 $from = rand(0, $last);
8870 $curr = $array[$i];
8871 $array[$i] = $array[$from];
8872 $array[$from] = $curr;
8874 return $array;
8878 * Like {@link swapshuffle()}, but works on associative arrays
8880 * @param array $array The associative array to be rearranged
8881 * @return array
8883 function swapshuffle_assoc($array) {
8885 $newarray = array();
8886 $newkeys = swapshuffle(array_keys($array));
8888 foreach ($newkeys as $newkey) {
8889 $newarray[$newkey] = $array[$newkey];
8891 return $newarray;
8895 * Given an arbitrary array, and a number of draws,
8896 * this function returns an array with that amount
8897 * of items. The indexes are retained.
8899 * @todo Finish documenting this function
8901 * @param array $array
8902 * @param int $draws
8903 * @return array
8905 function draw_rand_array($array, $draws) {
8907 $return = array();
8909 $last = count($array);
8911 if ($draws > $last) {
8912 $draws = $last;
8915 while ($draws > 0) {
8916 $last--;
8918 $keys = array_keys($array);
8919 $rand = rand(0, $last);
8921 $return[$keys[$rand]] = $array[$keys[$rand]];
8922 unset($array[$keys[$rand]]);
8924 $draws--;
8927 return $return;
8931 * Calculate the difference between two microtimes
8933 * @param string $a The first Microtime
8934 * @param string $b The second Microtime
8935 * @return string
8937 function microtime_diff($a, $b) {
8938 list($adec, $asec) = explode(' ', $a);
8939 list($bdec, $bsec) = explode(' ', $b);
8940 return $bsec - $asec + $bdec - $adec;
8944 * Given a list (eg a,b,c,d,e) this function returns
8945 * an array of 1->a, 2->b, 3->c etc
8947 * @param string $list The string to explode into array bits
8948 * @param string $separator The separator used within the list string
8949 * @return array The now assembled array
8951 function make_menu_from_list($list, $separator=',') {
8953 $array = array_reverse(explode($separator, $list), true);
8954 foreach ($array as $key => $item) {
8955 $outarray[$key+1] = trim($item);
8957 return $outarray;
8961 * Creates an array that represents all the current grades that
8962 * can be chosen using the given grading type.
8964 * Negative numbers
8965 * are scales, zero is no grade, and positive numbers are maximum
8966 * grades.
8968 * @todo Finish documenting this function or better deprecated this completely!
8970 * @param int $gradingtype
8971 * @return array
8973 function make_grades_menu($gradingtype) {
8974 global $DB;
8976 $grades = array();
8977 if ($gradingtype < 0) {
8978 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8979 return make_menu_from_list($scale->scale);
8981 } else if ($gradingtype > 0) {
8982 for ($i=$gradingtype; $i>=0; $i--) {
8983 $grades[$i] = $i .' / '. $gradingtype;
8985 return $grades;
8987 return $grades;
8991 * make_unique_id_code
8993 * @todo Finish documenting this function
8995 * @uses $_SERVER
8996 * @param string $extra Extra string to append to the end of the code
8997 * @return string
8999 function make_unique_id_code($extra = '') {
9001 $hostname = 'unknownhost';
9002 if (!empty($_SERVER['HTTP_HOST'])) {
9003 $hostname = $_SERVER['HTTP_HOST'];
9004 } else if (!empty($_ENV['HTTP_HOST'])) {
9005 $hostname = $_ENV['HTTP_HOST'];
9006 } else if (!empty($_SERVER['SERVER_NAME'])) {
9007 $hostname = $_SERVER['SERVER_NAME'];
9008 } else if (!empty($_ENV['SERVER_NAME'])) {
9009 $hostname = $_ENV['SERVER_NAME'];
9012 $date = gmdate("ymdHis");
9014 $random = random_string(6);
9016 if ($extra) {
9017 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
9018 } else {
9019 return $hostname .'+'. $date .'+'. $random;
9025 * Function to check the passed address is within the passed subnet
9027 * The parameter is a comma separated string of subnet definitions.
9028 * Subnet strings can be in one of three formats:
9029 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
9030 * 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)
9031 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
9032 * Code for type 1 modified from user posted comments by mediator at
9033 * {@link http://au.php.net/manual/en/function.ip2long.php}
9035 * @param string $addr The address you are checking
9036 * @param string $subnetstr The string of subnet addresses
9037 * @return bool
9039 function address_in_subnet($addr, $subnetstr) {
9041 if ($addr == '0.0.0.0') {
9042 return false;
9044 $subnets = explode(',', $subnetstr);
9045 $found = false;
9046 $addr = trim($addr);
9047 $addr = cleanremoteaddr($addr, false); // Normalise.
9048 if ($addr === null) {
9049 return false;
9051 $addrparts = explode(':', $addr);
9053 $ipv6 = strpos($addr, ':');
9055 foreach ($subnets as $subnet) {
9056 $subnet = trim($subnet);
9057 if ($subnet === '') {
9058 continue;
9061 if (strpos($subnet, '/') !== false) {
9062 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
9063 list($ip, $mask) = explode('/', $subnet);
9064 $mask = trim($mask);
9065 if (!is_number($mask)) {
9066 continue; // Incorect mask number, eh?
9068 $ip = cleanremoteaddr($ip, false); // Normalise.
9069 if ($ip === null) {
9070 continue;
9072 if (strpos($ip, ':') !== false) {
9073 // IPv6.
9074 if (!$ipv6) {
9075 continue;
9077 if ($mask > 128 or $mask < 0) {
9078 continue; // Nonsense.
9080 if ($mask == 0) {
9081 return true; // Any address.
9083 if ($mask == 128) {
9084 if ($ip === $addr) {
9085 return true;
9087 continue;
9089 $ipparts = explode(':', $ip);
9090 $modulo = $mask % 16;
9091 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
9092 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
9093 if (implode(':', $ipnet) === implode(':', $addrnet)) {
9094 if ($modulo == 0) {
9095 return true;
9097 $pos = ($mask-$modulo)/16;
9098 $ipnet = hexdec($ipparts[$pos]);
9099 $addrnet = hexdec($addrparts[$pos]);
9100 $mask = 0xffff << (16 - $modulo);
9101 if (($addrnet & $mask) == ($ipnet & $mask)) {
9102 return true;
9106 } else {
9107 // IPv4.
9108 if ($ipv6) {
9109 continue;
9111 if ($mask > 32 or $mask < 0) {
9112 continue; // Nonsense.
9114 if ($mask == 0) {
9115 return true;
9117 if ($mask == 32) {
9118 if ($ip === $addr) {
9119 return true;
9121 continue;
9123 $mask = 0xffffffff << (32 - $mask);
9124 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
9125 return true;
9129 } else if (strpos($subnet, '-') !== false) {
9130 // 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.
9131 $parts = explode('-', $subnet);
9132 if (count($parts) != 2) {
9133 continue;
9136 if (strpos($subnet, ':') !== false) {
9137 // IPv6.
9138 if (!$ipv6) {
9139 continue;
9141 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9142 if ($ipstart === null) {
9143 continue;
9145 $ipparts = explode(':', $ipstart);
9146 $start = hexdec(array_pop($ipparts));
9147 $ipparts[] = trim($parts[1]);
9148 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
9149 if ($ipend === null) {
9150 continue;
9152 $ipparts[7] = '';
9153 $ipnet = implode(':', $ipparts);
9154 if (strpos($addr, $ipnet) !== 0) {
9155 continue;
9157 $ipparts = explode(':', $ipend);
9158 $end = hexdec($ipparts[7]);
9160 $addrend = hexdec($addrparts[7]);
9162 if (($addrend >= $start) and ($addrend <= $end)) {
9163 return true;
9166 } else {
9167 // IPv4.
9168 if ($ipv6) {
9169 continue;
9171 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9172 if ($ipstart === null) {
9173 continue;
9175 $ipparts = explode('.', $ipstart);
9176 $ipparts[3] = trim($parts[1]);
9177 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
9178 if ($ipend === null) {
9179 continue;
9182 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9183 return true;
9187 } else {
9188 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9189 if (strpos($subnet, ':') !== false) {
9190 // IPv6.
9191 if (!$ipv6) {
9192 continue;
9194 $parts = explode(':', $subnet);
9195 $count = count($parts);
9196 if ($parts[$count-1] === '') {
9197 unset($parts[$count-1]); // Trim trailing :'s.
9198 $count--;
9199 $subnet = implode('.', $parts);
9201 $isip = cleanremoteaddr($subnet, false); // Normalise.
9202 if ($isip !== null) {
9203 if ($isip === $addr) {
9204 return true;
9206 continue;
9207 } else if ($count > 8) {
9208 continue;
9210 $zeros = array_fill(0, 8-$count, '0');
9211 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9212 if (address_in_subnet($addr, $subnet)) {
9213 return true;
9216 } else {
9217 // IPv4.
9218 if ($ipv6) {
9219 continue;
9221 $parts = explode('.', $subnet);
9222 $count = count($parts);
9223 if ($parts[$count-1] === '') {
9224 unset($parts[$count-1]); // Trim trailing .
9225 $count--;
9226 $subnet = implode('.', $parts);
9228 if ($count == 4) {
9229 $subnet = cleanremoteaddr($subnet, false); // Normalise.
9230 if ($subnet === $addr) {
9231 return true;
9233 continue;
9234 } else if ($count > 4) {
9235 continue;
9237 $zeros = array_fill(0, 4-$count, '0');
9238 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9239 if (address_in_subnet($addr, $subnet)) {
9240 return true;
9246 return false;
9250 * For outputting debugging info
9252 * @param string $string The string to write
9253 * @param string $eol The end of line char(s) to use
9254 * @param string $sleep Period to make the application sleep
9255 * This ensures any messages have time to display before redirect
9257 function mtrace($string, $eol="\n", $sleep=0) {
9258 global $CFG;
9260 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
9261 $fn = $CFG->mtrace_wrapper;
9262 $fn($string, $eol);
9263 return;
9264 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
9265 // We must explicitly call the add_line function here.
9266 // Uses of fwrite to STDOUT are not picked up by ob_start.
9267 if ($output = \core\task\logmanager::add_line("{$string}{$eol}")) {
9268 fwrite(STDOUT, $output);
9270 } else {
9271 echo $string . $eol;
9274 // Flush again.
9275 flush();
9277 // Delay to keep message on user's screen in case of subsequent redirect.
9278 if ($sleep) {
9279 sleep($sleep);
9284 * Helper to {@see mtrace()} an exception or throwable, including all relevant information.
9286 * @param Throwable $e the error to ouptput.
9288 function mtrace_exception(Throwable $e): void {
9289 $info = get_exception_info($e);
9291 $message = $info->message;
9292 if ($info->debuginfo) {
9293 $message .= "\n\n" . $info->debuginfo;
9295 if ($info->backtrace) {
9296 $message .= "\n\n" . format_backtrace($info->backtrace, true);
9299 mtrace($message);
9303 * Replace 1 or more slashes or backslashes to 1 slash
9305 * @param string $path The path to strip
9306 * @return string the path with double slashes removed
9308 function cleardoubleslashes ($path) {
9309 return preg_replace('/(\/|\\\){1,}/', '/', $path);
9313 * Is the current ip in a given list?
9315 * @param string $list
9316 * @return bool
9318 function remoteip_in_list($list) {
9319 $clientip = getremoteaddr(null);
9321 if (!$clientip) {
9322 // Ensure access on cli.
9323 return true;
9325 return \core\ip_utils::is_ip_in_subnet_list($clientip, $list);
9329 * Returns most reliable client address
9331 * @param string $default If an address can't be determined, then return this
9332 * @return string The remote IP address
9334 function getremoteaddr($default='0.0.0.0') {
9335 global $CFG;
9337 if (!isset($CFG->getremoteaddrconf)) {
9338 // This will happen, for example, before just after the upgrade, as the
9339 // user is redirected to the admin screen.
9340 $variablestoskip = GETREMOTEADDR_SKIP_DEFAULT;
9341 } else {
9342 $variablestoskip = $CFG->getremoteaddrconf;
9344 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
9345 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9346 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9347 return $address ? $address : $default;
9350 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
9351 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9352 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9354 $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
9355 global $CFG;
9356 return !\core\ip_utils::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore ?? '', ',');
9359 // Multiple proxies can append values to this header including an
9360 // untrusted original request header so we must only trust the last ip.
9361 $address = end($forwardedaddresses);
9363 if (substr_count($address, ":") > 1) {
9364 // Remove port and brackets from IPv6.
9365 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9366 $address = $matches[1];
9368 } else {
9369 // Remove port from IPv4.
9370 if (substr_count($address, ":") == 1) {
9371 $parts = explode(":", $address);
9372 $address = $parts[0];
9376 $address = cleanremoteaddr($address);
9377 return $address ? $address : $default;
9380 if (!empty($_SERVER['REMOTE_ADDR'])) {
9381 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9382 return $address ? $address : $default;
9383 } else {
9384 return $default;
9389 * Cleans an ip address. Internal addresses are now allowed.
9390 * (Originally local addresses were not allowed.)
9392 * @param string $addr IPv4 or IPv6 address
9393 * @param bool $compress use IPv6 address compression
9394 * @return string normalised ip address string, null if error
9396 function cleanremoteaddr($addr, $compress=false) {
9397 $addr = trim($addr);
9399 if (strpos($addr, ':') !== false) {
9400 // Can be only IPv6.
9401 $parts = explode(':', $addr);
9402 $count = count($parts);
9404 if (strpos($parts[$count-1], '.') !== false) {
9405 // Legacy ipv4 notation.
9406 $last = array_pop($parts);
9407 $ipv4 = cleanremoteaddr($last, true);
9408 if ($ipv4 === null) {
9409 return null;
9411 $bits = explode('.', $ipv4);
9412 $parts[] = dechex($bits[0]).dechex($bits[1]);
9413 $parts[] = dechex($bits[2]).dechex($bits[3]);
9414 $count = count($parts);
9415 $addr = implode(':', $parts);
9418 if ($count < 3 or $count > 8) {
9419 return null; // Severly malformed.
9422 if ($count != 8) {
9423 if (strpos($addr, '::') === false) {
9424 return null; // Malformed.
9426 // Uncompress.
9427 $insertat = array_search('', $parts, true);
9428 $missing = array_fill(0, 1 + 8 - $count, '0');
9429 array_splice($parts, $insertat, 1, $missing);
9430 foreach ($parts as $key => $part) {
9431 if ($part === '') {
9432 $parts[$key] = '0';
9437 $adr = implode(':', $parts);
9438 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9439 return null; // Incorrect format - sorry.
9442 // Normalise 0s and case.
9443 $parts = array_map('hexdec', $parts);
9444 $parts = array_map('dechex', $parts);
9446 $result = implode(':', $parts);
9448 if (!$compress) {
9449 return $result;
9452 if ($result === '0:0:0:0:0:0:0:0') {
9453 return '::'; // All addresses.
9456 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9457 if ($compressed !== $result) {
9458 return $compressed;
9461 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9462 if ($compressed !== $result) {
9463 return $compressed;
9466 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9467 if ($compressed !== $result) {
9468 return $compressed;
9471 return $result;
9474 // First get all things that look like IPv4 addresses.
9475 $parts = array();
9476 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9477 return null;
9479 unset($parts[0]);
9481 foreach ($parts as $key => $match) {
9482 if ($match > 255) {
9483 return null;
9485 $parts[$key] = (int)$match; // Normalise 0s.
9488 return implode('.', $parts);
9493 * Is IP address a public address?
9495 * @param string $ip The ip to check
9496 * @return bool true if the ip is public
9498 function ip_is_public($ip) {
9499 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9503 * This function will make a complete copy of anything it's given,
9504 * regardless of whether it's an object or not.
9506 * @param mixed $thing Something you want cloned
9507 * @return mixed What ever it is you passed it
9509 function fullclone($thing) {
9510 return unserialize(serialize($thing));
9514 * Used to make sure that $min <= $value <= $max
9516 * Make sure that value is between min, and max
9518 * @param int $min The minimum value
9519 * @param int $value The value to check
9520 * @param int $max The maximum value
9521 * @return int
9523 function bounded_number($min, $value, $max) {
9524 if ($value < $min) {
9525 return $min;
9527 if ($value > $max) {
9528 return $max;
9530 return $value;
9534 * Check if there is a nested array within the passed array
9536 * @param array $array
9537 * @return bool true if there is a nested array false otherwise
9539 function array_is_nested($array) {
9540 foreach ($array as $value) {
9541 if (is_array($value)) {
9542 return true;
9545 return false;
9549 * get_performance_info() pairs up with init_performance_info()
9550 * loaded in setup.php. Returns an array with 'html' and 'txt'
9551 * values ready for use, and each of the individual stats provided
9552 * separately as well.
9554 * @return array
9556 function get_performance_info() {
9557 global $CFG, $PERF, $DB, $PAGE;
9559 $info = array();
9560 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9562 $info['html'] = '';
9563 if (!empty($CFG->themedesignermode)) {
9564 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9565 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9567 $info['html'] .= '<ul class="list-unstyled row mx-md-0">'; // Holds userfriendly HTML representation.
9569 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9571 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9572 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9574 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9575 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9577 if (function_exists('memory_get_usage')) {
9578 $info['memory_total'] = memory_get_usage();
9579 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9580 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9581 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9582 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9585 if (function_exists('memory_get_peak_usage')) {
9586 $info['memory_peak'] = memory_get_peak_usage();
9587 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9588 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9591 $info['html'] .= '</ul><ul class="list-unstyled row mx-md-0">';
9592 $inc = get_included_files();
9593 $info['includecount'] = count($inc);
9594 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9595 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9597 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9598 // We can not track more performance before installation or before PAGE init, sorry.
9599 return $info;
9602 $filtermanager = filter_manager::instance();
9603 if (method_exists($filtermanager, 'get_performance_summary')) {
9604 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9605 $info = array_merge($filterinfo, $info);
9606 foreach ($filterinfo as $key => $value) {
9607 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9608 $info['txt'] .= "$key: $value ";
9612 $stringmanager = get_string_manager();
9613 if (method_exists($stringmanager, 'get_performance_summary')) {
9614 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9615 $info = array_merge($filterinfo, $info);
9616 foreach ($filterinfo as $key => $value) {
9617 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9618 $info['txt'] .= "$key: $value ";
9622 if (!empty($PERF->logwrites)) {
9623 $info['logwrites'] = $PERF->logwrites;
9624 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9625 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9628 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9629 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9630 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9632 if ($DB->want_read_slave()) {
9633 $info['dbreads_slave'] = $DB->perf_get_reads_slave();
9634 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads from slave: '.$info['dbreads_slave'].'</li> ';
9635 $info['txt'] .= 'db reads from slave: '.$info['dbreads_slave'].' ';
9638 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9639 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9640 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9642 if (function_exists('posix_times')) {
9643 $ptimes = posix_times();
9644 if (is_array($ptimes)) {
9645 foreach ($ptimes as $key => $val) {
9646 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9648 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9649 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9650 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9654 // Grab the load average for the last minute.
9655 // /proc will only work under some linux configurations
9656 // while uptime is there under MacOSX/Darwin and other unices.
9657 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9658 list($serverload) = explode(' ', $loadavg[0]);
9659 unset($loadavg);
9660 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9661 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9662 $serverload = $matches[1];
9663 } else {
9664 trigger_error('Could not parse uptime output!');
9667 if (!empty($serverload)) {
9668 $info['serverload'] = $serverload;
9669 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9670 $info['txt'] .= "serverload: {$info['serverload']} ";
9673 // Display size of session if session started.
9674 if ($si = \core\session\manager::get_performance_info()) {
9675 $info['sessionsize'] = $si['size'];
9676 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9677 $info['txt'] .= $si['txt'];
9680 $info['html'] .= '</ul>';
9681 $html = '';
9682 if ($stats = cache_helper::get_stats()) {
9684 $table = new html_table();
9685 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9686 $table->head = ['Mode', 'Cache item', 'Static', 'H', 'M', get_string('mappingprimary', 'cache'), 'H', 'M', 'S', 'I/O'];
9687 $table->data = [];
9688 $table->align = ['left', 'left', 'left', 'right', 'right', 'left', 'right', 'right', 'right', 'right'];
9690 $text = 'Caches used (hits/misses/sets): ';
9691 $hits = 0;
9692 $misses = 0;
9693 $sets = 0;
9694 $maxstores = 0;
9696 // We want to align static caches into their own column.
9697 $hasstatic = false;
9698 foreach ($stats as $definition => $details) {
9699 $numstores = count($details['stores']);
9700 $first = key($details['stores']);
9701 if ($first !== cache_store::STATIC_ACCEL) {
9702 $numstores++; // Add a blank space for the missing static store.
9704 $maxstores = max($maxstores, $numstores);
9707 $storec = 0;
9709 while ($storec++ < ($maxstores - 2)) {
9710 if ($storec == ($maxstores - 2)) {
9711 $table->head[] = get_string('mappingfinal', 'cache');
9712 } else {
9713 $table->head[] = "Store $storec";
9715 $table->align[] = 'left';
9716 $table->align[] = 'right';
9717 $table->align[] = 'right';
9718 $table->align[] = 'right';
9719 $table->align[] = 'right';
9720 $table->head[] = 'H';
9721 $table->head[] = 'M';
9722 $table->head[] = 'S';
9723 $table->head[] = 'I/O';
9726 ksort($stats);
9728 foreach ($stats as $definition => $details) {
9729 switch ($details['mode']) {
9730 case cache_store::MODE_APPLICATION:
9731 $modeclass = 'application';
9732 $mode = ' <span title="application cache">App</span>';
9733 break;
9734 case cache_store::MODE_SESSION:
9735 $modeclass = 'session';
9736 $mode = ' <span title="session cache">Ses</span>';
9737 break;
9738 case cache_store::MODE_REQUEST:
9739 $modeclass = 'request';
9740 $mode = ' <span title="request cache">Req</span>';
9741 break;
9743 $row = [$mode, $definition];
9745 $text .= "$definition {";
9747 $storec = 0;
9748 foreach ($details['stores'] as $store => $data) {
9750 if ($storec == 0 && $store !== cache_store::STATIC_ACCEL) {
9751 $row[] = '';
9752 $row[] = '';
9753 $row[] = '';
9754 $storec++;
9757 $hits += $data['hits'];
9758 $misses += $data['misses'];
9759 $sets += $data['sets'];
9760 if ($data['hits'] == 0 and $data['misses'] > 0) {
9761 $cachestoreclass = 'nohits bg-danger';
9762 } else if ($data['hits'] < $data['misses']) {
9763 $cachestoreclass = 'lowhits bg-warning text-dark';
9764 } else {
9765 $cachestoreclass = 'hihits';
9767 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9768 $cell = new html_table_cell($store);
9769 $cell->attributes = ['class' => $cachestoreclass];
9770 $row[] = $cell;
9771 $cell = new html_table_cell($data['hits']);
9772 $cell->attributes = ['class' => $cachestoreclass];
9773 $row[] = $cell;
9774 $cell = new html_table_cell($data['misses']);
9775 $cell->attributes = ['class' => $cachestoreclass];
9776 $row[] = $cell;
9778 if ($store !== cache_store::STATIC_ACCEL) {
9779 // The static cache is never set.
9780 $cell = new html_table_cell($data['sets']);
9781 $cell->attributes = ['class' => $cachestoreclass];
9782 $row[] = $cell;
9784 if ($data['hits'] || $data['sets']) {
9785 if ($data['iobytes'] === cache_store::IO_BYTES_NOT_SUPPORTED) {
9786 $size = '-';
9787 } else {
9788 $size = display_size($data['iobytes'], 1, 'KB');
9789 if ($data['iobytes'] >= 10 * 1024) {
9790 $cachestoreclass = ' bg-warning text-dark';
9793 } else {
9794 $size = '';
9796 $cell = new html_table_cell($size);
9797 $cell->attributes = ['class' => $cachestoreclass];
9798 $row[] = $cell;
9800 $storec++;
9802 while ($storec++ < $maxstores) {
9803 $row[] = '';
9804 $row[] = '';
9805 $row[] = '';
9806 $row[] = '';
9807 $row[] = '';
9809 $text .= '} ';
9811 $table->data[] = $row;
9814 $html .= html_writer::table($table);
9816 // Now lets also show sub totals for each cache store.
9817 $storetotals = [];
9818 $storetotal = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9819 foreach ($stats as $definition => $details) {
9820 foreach ($details['stores'] as $store => $data) {
9821 if (!array_key_exists($store, $storetotals)) {
9822 $storetotals[$store] = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9824 $storetotals[$store]['class'] = $data['class'];
9825 $storetotals[$store]['hits'] += $data['hits'];
9826 $storetotals[$store]['misses'] += $data['misses'];
9827 $storetotals[$store]['sets'] += $data['sets'];
9828 $storetotal['hits'] += $data['hits'];
9829 $storetotal['misses'] += $data['misses'];
9830 $storetotal['sets'] += $data['sets'];
9831 if ($data['iobytes'] !== cache_store::IO_BYTES_NOT_SUPPORTED) {
9832 $storetotals[$store]['iobytes'] += $data['iobytes'];
9833 $storetotal['iobytes'] += $data['iobytes'];
9838 $table = new html_table();
9839 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9840 $table->head = [get_string('storename', 'cache'), get_string('type_cachestore', 'plugin'), 'H', 'M', 'S', 'I/O'];
9841 $table->data = [];
9842 $table->align = ['left', 'left', 'right', 'right', 'right', 'right'];
9844 ksort($storetotals);
9846 foreach ($storetotals as $store => $data) {
9847 $row = [];
9848 if ($data['hits'] == 0 and $data['misses'] > 0) {
9849 $cachestoreclass = 'nohits bg-danger';
9850 } else if ($data['hits'] < $data['misses']) {
9851 $cachestoreclass = 'lowhits bg-warning text-dark';
9852 } else {
9853 $cachestoreclass = 'hihits';
9855 $cell = new html_table_cell($store);
9856 $cell->attributes = ['class' => $cachestoreclass];
9857 $row[] = $cell;
9858 $cell = new html_table_cell($data['class']);
9859 $cell->attributes = ['class' => $cachestoreclass];
9860 $row[] = $cell;
9861 $cell = new html_table_cell($data['hits']);
9862 $cell->attributes = ['class' => $cachestoreclass];
9863 $row[] = $cell;
9864 $cell = new html_table_cell($data['misses']);
9865 $cell->attributes = ['class' => $cachestoreclass];
9866 $row[] = $cell;
9867 $cell = new html_table_cell($data['sets']);
9868 $cell->attributes = ['class' => $cachestoreclass];
9869 $row[] = $cell;
9870 if ($data['hits'] || $data['sets']) {
9871 if ($data['iobytes']) {
9872 $size = display_size($data['iobytes'], 1, 'KB');
9873 } else {
9874 $size = '-';
9876 } else {
9877 $size = '';
9879 $cell = new html_table_cell($size);
9880 $cell->attributes = ['class' => $cachestoreclass];
9881 $row[] = $cell;
9882 $table->data[] = $row;
9884 if (!empty($storetotal['iobytes'])) {
9885 $size = display_size($storetotal['iobytes'], 1, 'KB');
9886 } else if (!empty($storetotal['hits']) || !empty($storetotal['sets'])) {
9887 $size = '-';
9888 } else {
9889 $size = '';
9891 $row = [
9892 get_string('total'),
9894 $storetotal['hits'],
9895 $storetotal['misses'],
9896 $storetotal['sets'],
9897 $size,
9899 $table->data[] = $row;
9901 $html .= html_writer::table($table);
9903 $info['cachesused'] = "$hits / $misses / $sets";
9904 $info['html'] .= $html;
9905 $info['txt'] .= $text.'. ';
9906 } else {
9907 $info['cachesused'] = '0 / 0 / 0';
9908 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9909 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9912 $info['html'] = '<div class="performanceinfo siteinfo container-fluid px-md-0 overflow-auto pt-3">'.$info['html'].'</div>';
9913 return $info;
9917 * Renames a file or directory to a unique name within the same directory.
9919 * This function is designed to avoid any potential race conditions, and select an unused name.
9921 * @param string $filepath Original filepath
9922 * @param string $prefix Prefix to use for the temporary name
9923 * @return string|bool New file path or false if failed
9924 * @since Moodle 3.10
9926 function rename_to_unused_name(string $filepath, string $prefix = '_temp_') {
9927 $dir = dirname($filepath);
9928 $basename = $dir . '/' . $prefix;
9929 $limit = 0;
9930 while ($limit < 100) {
9931 // Select a new name based on a random number.
9932 $newfilepath = $basename . md5(mt_rand());
9934 // Attempt a rename to that new name.
9935 if (@rename($filepath, $newfilepath)) {
9936 return $newfilepath;
9939 // The first time, do some sanity checks, maybe it is failing for a good reason and there
9940 // is no point trying 100 times if so.
9941 if ($limit === 0 && (!file_exists($filepath) || !is_writable($dir))) {
9942 return false;
9944 $limit++;
9946 return false;
9950 * Delete directory or only its content
9952 * @param string $dir directory path
9953 * @param bool $contentonly
9954 * @return bool success, true also if dir does not exist
9956 function remove_dir($dir, $contentonly=false) {
9957 if (!is_dir($dir)) {
9958 // Nothing to do.
9959 return true;
9962 if (!$contentonly) {
9963 // Start by renaming the directory; this will guarantee that other processes don't write to it
9964 // while it is in the process of being deleted.
9965 $tempdir = rename_to_unused_name($dir);
9966 if ($tempdir) {
9967 // If the rename was successful then delete the $tempdir instead.
9968 $dir = $tempdir;
9970 // If the rename fails, we will continue through and attempt to delete the directory
9971 // without renaming it since that is likely to at least delete most of the files.
9974 if (!$handle = opendir($dir)) {
9975 return false;
9977 $result = true;
9978 while (false!==($item = readdir($handle))) {
9979 if ($item != '.' && $item != '..') {
9980 if (is_dir($dir.'/'.$item)) {
9981 $result = remove_dir($dir.'/'.$item) && $result;
9982 } else {
9983 $result = unlink($dir.'/'.$item) && $result;
9987 closedir($handle);
9988 if ($contentonly) {
9989 clearstatcache(); // Make sure file stat cache is properly invalidated.
9990 return $result;
9992 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9993 clearstatcache(); // Make sure file stat cache is properly invalidated.
9994 return $result;
9998 * Detect if an object or a class contains a given property
9999 * will take an actual object or the name of a class
10001 * @param mix $obj Name of class or real object to test
10002 * @param string $property name of property to find
10003 * @return bool true if property exists
10005 function object_property_exists( $obj, $property ) {
10006 if (is_string( $obj )) {
10007 $properties = get_class_vars( $obj );
10008 } else {
10009 $properties = get_object_vars( $obj );
10011 return array_key_exists( $property, $properties );
10015 * Converts an object into an associative array
10017 * This function converts an object into an associative array by iterating
10018 * over its public properties. Because this function uses the foreach
10019 * construct, Iterators are respected. It works recursively on arrays of objects.
10020 * Arrays and simple values are returned as is.
10022 * If class has magic properties, it can implement IteratorAggregate
10023 * and return all available properties in getIterator()
10025 * @param mixed $var
10026 * @return array
10028 function convert_to_array($var) {
10029 $result = array();
10031 // Loop over elements/properties.
10032 foreach ($var as $key => $value) {
10033 // Recursively convert objects.
10034 if (is_object($value) || is_array($value)) {
10035 $result[$key] = convert_to_array($value);
10036 } else {
10037 // Simple values are untouched.
10038 $result[$key] = $value;
10041 return $result;
10045 * Detect a custom script replacement in the data directory that will
10046 * replace an existing moodle script
10048 * @return string|bool full path name if a custom script exists, false if no custom script exists
10050 function custom_script_path() {
10051 global $CFG, $SCRIPT;
10053 if ($SCRIPT === null) {
10054 // Probably some weird external script.
10055 return false;
10058 $scriptpath = $CFG->customscripts . $SCRIPT;
10060 // Check the custom script exists.
10061 if (file_exists($scriptpath) and is_file($scriptpath)) {
10062 return $scriptpath;
10063 } else {
10064 return false;
10069 * Returns whether or not the user object is a remote MNET user. This function
10070 * is in moodlelib because it does not rely on loading any of the MNET code.
10072 * @param object $user A valid user object
10073 * @return bool True if the user is from a remote Moodle.
10075 function is_mnet_remote_user($user) {
10076 global $CFG;
10078 if (!isset($CFG->mnet_localhost_id)) {
10079 include_once($CFG->dirroot . '/mnet/lib.php');
10080 $env = new mnet_environment();
10081 $env->init();
10082 unset($env);
10085 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
10089 * This function will search for browser prefereed languages, setting Moodle
10090 * to use the best one available if $SESSION->lang is undefined
10092 function setup_lang_from_browser() {
10093 global $CFG, $SESSION, $USER;
10095 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
10096 // Lang is defined in session or user profile, nothing to do.
10097 return;
10100 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
10101 return;
10104 // Extract and clean langs from headers.
10105 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
10106 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
10107 $rawlangs = explode(',', $rawlangs); // Convert to array.
10108 $langs = array();
10110 $order = 1.0;
10111 foreach ($rawlangs as $lang) {
10112 if (strpos($lang, ';') === false) {
10113 $langs[(string)$order] = $lang;
10114 $order = $order-0.01;
10115 } else {
10116 $parts = explode(';', $lang);
10117 $pos = strpos($parts[1], '=');
10118 $langs[substr($parts[1], $pos+1)] = $parts[0];
10121 krsort($langs, SORT_NUMERIC);
10123 // Look for such langs under standard locations.
10124 foreach ($langs as $lang) {
10125 // Clean it properly for include.
10126 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
10127 if (get_string_manager()->translation_exists($lang, false)) {
10128 // Lang exists, set it in session.
10129 $SESSION->lang = $lang;
10130 // We have finished. Go out.
10131 break;
10134 return;
10138 * Check if $url matches anything in proxybypass list
10140 * Any errors just result in the proxy being used (least bad)
10142 * @param string $url url to check
10143 * @return boolean true if we should bypass the proxy
10145 function is_proxybypass( $url ) {
10146 global $CFG;
10148 // Sanity check.
10149 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
10150 return false;
10153 // Get the host part out of the url.
10154 if (!$host = parse_url( $url, PHP_URL_HOST )) {
10155 return false;
10158 // Get the possible bypass hosts into an array.
10159 $matches = explode( ',', $CFG->proxybypass );
10161 // Check for a match.
10162 // (IPs need to match the left hand side and hosts the right of the url,
10163 // but we can recklessly check both as there can't be a false +ve).
10164 foreach ($matches as $match) {
10165 $match = trim($match);
10167 // Try for IP match (Left side).
10168 $lhs = substr($host, 0, strlen($match));
10169 if (strcasecmp($match, $lhs)==0) {
10170 return true;
10173 // Try for host match (Right side).
10174 $rhs = substr($host, -strlen($match));
10175 if (strcasecmp($match, $rhs)==0) {
10176 return true;
10180 // Nothing matched.
10181 return false;
10185 * Check if the passed navigation is of the new style
10187 * @param mixed $navigation
10188 * @return bool true for yes false for no
10190 function is_newnav($navigation) {
10191 if (is_array($navigation) && !empty($navigation['newnav'])) {
10192 return true;
10193 } else {
10194 return false;
10199 * Checks whether the given variable name is defined as a variable within the given object.
10201 * This will NOT work with stdClass objects, which have no class variables.
10203 * @param string $var The variable name
10204 * @param object $object The object to check
10205 * @return boolean
10207 function in_object_vars($var, $object) {
10208 $classvars = get_class_vars(get_class($object));
10209 $classvars = array_keys($classvars);
10210 return in_array($var, $classvars);
10214 * Returns an array without repeated objects.
10215 * This function is similar to array_unique, but for arrays that have objects as values
10217 * @param array $array
10218 * @param bool $keepkeyassoc
10219 * @return array
10221 function object_array_unique($array, $keepkeyassoc = true) {
10222 $duplicatekeys = array();
10223 $tmp = array();
10225 foreach ($array as $key => $val) {
10226 // Convert objects to arrays, in_array() does not support objects.
10227 if (is_object($val)) {
10228 $val = (array)$val;
10231 if (!in_array($val, $tmp)) {
10232 $tmp[] = $val;
10233 } else {
10234 $duplicatekeys[] = $key;
10238 foreach ($duplicatekeys as $key) {
10239 unset($array[$key]);
10242 return $keepkeyassoc ? $array : array_values($array);
10246 * Is a userid the primary administrator?
10248 * @param int $userid int id of user to check
10249 * @return boolean
10251 function is_primary_admin($userid) {
10252 $primaryadmin = get_admin();
10254 if ($userid == $primaryadmin->id) {
10255 return true;
10256 } else {
10257 return false;
10262 * Returns the site identifier
10264 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
10266 function get_site_identifier() {
10267 global $CFG;
10268 // Check to see if it is missing. If so, initialise it.
10269 if (empty($CFG->siteidentifier)) {
10270 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
10272 // Return it.
10273 return $CFG->siteidentifier;
10277 * Check whether the given password has no more than the specified
10278 * number of consecutive identical characters.
10280 * @param string $password password to be checked against the password policy
10281 * @param integer $maxchars maximum number of consecutive identical characters
10282 * @return bool
10284 function check_consecutive_identical_characters($password, $maxchars) {
10286 if ($maxchars < 1) {
10287 return true; // Zero 0 is to disable this check.
10289 if (strlen($password) <= $maxchars) {
10290 return true; // Too short to fail this test.
10293 $previouschar = '';
10294 $consecutivecount = 1;
10295 foreach (str_split($password) as $char) {
10296 if ($char != $previouschar) {
10297 $consecutivecount = 1;
10298 } else {
10299 $consecutivecount++;
10300 if ($consecutivecount > $maxchars) {
10301 return false; // Check failed already.
10305 $previouschar = $char;
10308 return true;
10312 * Helper function to do partial function binding.
10313 * so we can use it for preg_replace_callback, for example
10314 * this works with php functions, user functions, static methods and class methods
10315 * it returns you a callback that you can pass on like so:
10317 * $callback = partial('somefunction', $arg1, $arg2);
10318 * or
10319 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
10320 * or even
10321 * $obj = new someclass();
10322 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
10324 * and then the arguments that are passed through at calltime are appended to the argument list.
10326 * @param mixed $function a php callback
10327 * @param mixed $arg1,... $argv arguments to partially bind with
10328 * @return array Array callback
10330 function partial() {
10331 if (!class_exists('partial')) {
10333 * Used to manage function binding.
10334 * @copyright 2009 Penny Leach
10335 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10337 class partial{
10338 /** @var array */
10339 public $values = array();
10340 /** @var string The function to call as a callback. */
10341 public $func;
10343 * Constructor
10344 * @param string $func
10345 * @param array $args
10347 public function __construct($func, $args) {
10348 $this->values = $args;
10349 $this->func = $func;
10352 * Calls the callback function.
10353 * @return mixed
10355 public function method() {
10356 $args = func_get_args();
10357 return call_user_func_array($this->func, array_merge($this->values, $args));
10361 $args = func_get_args();
10362 $func = array_shift($args);
10363 $p = new partial($func, $args);
10364 return array($p, 'method');
10368 * helper function to load up and initialise the mnet environment
10369 * this must be called before you use mnet functions.
10371 * @return mnet_environment the equivalent of old $MNET global
10373 function get_mnet_environment() {
10374 global $CFG;
10375 require_once($CFG->dirroot . '/mnet/lib.php');
10376 static $instance = null;
10377 if (empty($instance)) {
10378 $instance = new mnet_environment();
10379 $instance->init();
10381 return $instance;
10385 * during xmlrpc server code execution, any code wishing to access
10386 * information about the remote peer must use this to get it.
10388 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
10390 function get_mnet_remote_client() {
10391 if (!defined('MNET_SERVER')) {
10392 debugging(get_string('notinxmlrpcserver', 'mnet'));
10393 return false;
10395 global $MNET_REMOTE_CLIENT;
10396 if (isset($MNET_REMOTE_CLIENT)) {
10397 return $MNET_REMOTE_CLIENT;
10399 return false;
10403 * during the xmlrpc server code execution, this will be called
10404 * to setup the object returned by {@link get_mnet_remote_client}
10406 * @param mnet_remote_client $client the client to set up
10407 * @throws moodle_exception
10409 function set_mnet_remote_client($client) {
10410 if (!defined('MNET_SERVER')) {
10411 throw new moodle_exception('notinxmlrpcserver', 'mnet');
10413 global $MNET_REMOTE_CLIENT;
10414 $MNET_REMOTE_CLIENT = $client;
10418 * return the jump url for a given remote user
10419 * this is used for rewriting forum post links in emails, etc
10421 * @param stdclass $user the user to get the idp url for
10423 function mnet_get_idp_jump_url($user) {
10424 global $CFG;
10426 static $mnetjumps = array();
10427 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
10428 $idp = mnet_get_peer_host($user->mnethostid);
10429 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
10430 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
10432 return $mnetjumps[$user->mnethostid];
10436 * Gets the homepage to use for the current user
10438 * @return int One of HOMEPAGE_*
10440 function get_home_page() {
10441 global $CFG;
10443 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
10444 // If dashboard is disabled, home will be set to default page.
10445 $defaultpage = get_default_home_page();
10446 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
10447 if (!empty($CFG->enabledashboard)) {
10448 return HOMEPAGE_MY;
10449 } else {
10450 return $defaultpage;
10452 } else if ($CFG->defaulthomepage == HOMEPAGE_MYCOURSES) {
10453 return HOMEPAGE_MYCOURSES;
10454 } else {
10455 $userhomepage = (int) get_user_preferences('user_home_page_preference', $defaultpage);
10456 if (empty($CFG->enabledashboard) && $userhomepage == HOMEPAGE_MY) {
10457 // If the user was using the dashboard but it's disabled, return the default home page.
10458 $userhomepage = $defaultpage;
10460 return $userhomepage;
10463 return HOMEPAGE_SITE;
10467 * Returns the default home page to display if current one is not defined or can't be applied.
10468 * The default behaviour is to return Dashboard if it's enabled or My courses page if it isn't.
10470 * @return int The default home page.
10472 function get_default_home_page(): int {
10473 global $CFG;
10475 return !empty($CFG->enabledashboard) ? HOMEPAGE_MY : HOMEPAGE_MYCOURSES;
10479 * Gets the name of a course to be displayed when showing a list of courses.
10480 * By default this is just $course->fullname but user can configure it. The
10481 * result of this function should be passed through print_string.
10482 * @param stdClass|core_course_list_element $course Moodle course object
10483 * @return string Display name of course (either fullname or short + fullname)
10485 function get_course_display_name_for_list($course) {
10486 global $CFG;
10487 if (!empty($CFG->courselistshortnames)) {
10488 if (!($course instanceof stdClass)) {
10489 $course = (object)convert_to_array($course);
10491 return get_string('courseextendednamedisplay', '', $course);
10492 } else {
10493 return $course->fullname;
10498 * Safe analogue of unserialize() that can only parse arrays
10500 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
10501 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
10502 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
10504 * @param string $expression
10505 * @return array|bool either parsed array or false if parsing was impossible.
10507 function unserialize_array($expression) {
10508 $subs = [];
10509 // Find nested arrays, parse them and store in $subs , substitute with special string.
10510 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
10511 $key = '--SUB' . count($subs) . '--';
10512 $subs[$key] = unserialize_array($matches[2]);
10513 if ($subs[$key] === false) {
10514 return false;
10516 $expression = str_replace($matches[2], $key . ';', $expression);
10519 // Check the expression is an array.
10520 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
10521 return false;
10523 // Get the size and elements of an array (key;value;key;value;....).
10524 $parts = explode(';', $matches1[2]);
10525 $size = intval($matches1[1]);
10526 if (count($parts) < $size * 2 + 1) {
10527 return false;
10529 // Analyze each part and make sure it is an integer or string or a substitute.
10530 $value = [];
10531 for ($i = 0; $i < $size * 2; $i++) {
10532 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
10533 $parts[$i] = (int)$matches2[1];
10534 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
10535 $parts[$i] = $matches3[2];
10536 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
10537 $parts[$i] = $subs[$parts[$i]];
10538 } else {
10539 return false;
10542 // Combine keys and values.
10543 for ($i = 0; $i < $size * 2; $i += 2) {
10544 $value[$parts[$i]] = $parts[$i+1];
10546 return $value;
10550 * Safe method for unserializing given input that is expected to contain only a serialized instance of an stdClass object
10552 * If any class type other than stdClass is included in the input string, it will not be instantiated and will be cast to an
10553 * stdClass object. The initial cast to array, then back to object is to ensure we are always returning the correct type,
10554 * otherwise we would return an instances of {@see __PHP_Incomplete_class} for malformed strings
10556 * @param string $input
10557 * @return stdClass
10559 function unserialize_object(string $input): stdClass {
10560 $instance = (array) unserialize($input, ['allowed_classes' => [stdClass::class]]);
10561 return (object) $instance;
10565 * The lang_string class
10567 * This special class is used to create an object representation of a string request.
10568 * It is special because processing doesn't occur until the object is first used.
10569 * The class was created especially to aid performance in areas where strings were
10570 * required to be generated but were not necessarily used.
10571 * As an example the admin tree when generated uses over 1500 strings, of which
10572 * normally only 1/3 are ever actually printed at any time.
10573 * The performance advantage is achieved by not actually processing strings that
10574 * arn't being used, as such reducing the processing required for the page.
10576 * How to use the lang_string class?
10577 * There are two methods of using the lang_string class, first through the
10578 * forth argument of the get_string function, and secondly directly.
10579 * The following are examples of both.
10580 * 1. Through get_string calls e.g.
10581 * $string = get_string($identifier, $component, $a, true);
10582 * $string = get_string('yes', 'moodle', null, true);
10583 * 2. Direct instantiation
10584 * $string = new lang_string($identifier, $component, $a, $lang);
10585 * $string = new lang_string('yes');
10587 * How do I use a lang_string object?
10588 * The lang_string object makes use of a magic __toString method so that you
10589 * are able to use the object exactly as you would use a string in most cases.
10590 * This means you are able to collect it into a variable and then directly
10591 * echo it, or concatenate it into another string, or similar.
10592 * The other thing you can do is manually get the string by calling the
10593 * lang_strings out method e.g.
10594 * $string = new lang_string('yes');
10595 * $string->out();
10596 * Also worth noting is that the out method can take one argument, $lang which
10597 * allows the developer to change the language on the fly.
10599 * When should I use a lang_string object?
10600 * The lang_string object is designed to be used in any situation where a
10601 * string may not be needed, but needs to be generated.
10602 * The admin tree is a good example of where lang_string objects should be
10603 * used.
10604 * A more practical example would be any class that requries strings that may
10605 * not be printed (after all classes get renderer by renderers and who knows
10606 * what they will do ;))
10608 * When should I not use a lang_string object?
10609 * Don't use lang_strings when you are going to use a string immediately.
10610 * There is no need as it will be processed immediately and there will be no
10611 * advantage, and in fact perhaps a negative hit as a class has to be
10612 * instantiated for a lang_string object, however get_string won't require
10613 * that.
10615 * Limitations:
10616 * 1. You cannot use a lang_string object as an array offset. Doing so will
10617 * result in PHP throwing an error. (You can use it as an object property!)
10619 * @package core
10620 * @category string
10621 * @copyright 2011 Sam Hemelryk
10622 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10624 class lang_string {
10626 /** @var string The strings identifier */
10627 protected $identifier;
10628 /** @var string The strings component. Default '' */
10629 protected $component = '';
10630 /** @var array|stdClass Any arguments required for the string. Default null */
10631 protected $a = null;
10632 /** @var string The language to use when processing the string. Default null */
10633 protected $lang = null;
10635 /** @var string The processed string (once processed) */
10636 protected $string = null;
10639 * A special boolean. If set to true then the object has been woken up and
10640 * cannot be regenerated. If this is set then $this->string MUST be used.
10641 * @var bool
10643 protected $forcedstring = false;
10646 * Constructs a lang_string object
10648 * This function should do as little processing as possible to ensure the best
10649 * performance for strings that won't be used.
10651 * @param string $identifier The strings identifier
10652 * @param string $component The strings component
10653 * @param stdClass|array $a Any arguments the string requires
10654 * @param string $lang The language to use when processing the string.
10655 * @throws coding_exception
10657 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10658 if (empty($component)) {
10659 $component = 'moodle';
10662 $this->identifier = $identifier;
10663 $this->component = $component;
10664 $this->lang = $lang;
10666 // We MUST duplicate $a to ensure that it if it changes by reference those
10667 // changes are not carried across.
10668 // To do this we always ensure $a or its properties/values are strings
10669 // and that any properties/values that arn't convertable are forgotten.
10670 if ($a !== null) {
10671 if (is_scalar($a)) {
10672 $this->a = $a;
10673 } else if ($a instanceof lang_string) {
10674 $this->a = $a->out();
10675 } else if (is_object($a) or is_array($a)) {
10676 $a = (array)$a;
10677 $this->a = array();
10678 foreach ($a as $key => $value) {
10679 // Make sure conversion errors don't get displayed (results in '').
10680 if (is_array($value)) {
10681 $this->a[$key] = '';
10682 } else if (is_object($value)) {
10683 if (method_exists($value, '__toString')) {
10684 $this->a[$key] = $value->__toString();
10685 } else {
10686 $this->a[$key] = '';
10688 } else {
10689 $this->a[$key] = (string)$value;
10695 if (debugging(false, DEBUG_DEVELOPER)) {
10696 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10697 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10699 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10700 throw new coding_exception('Invalid string compontent. Please check your string definition');
10702 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10703 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10709 * Processes the string.
10711 * This function actually processes the string, stores it in the string property
10712 * and then returns it.
10713 * You will notice that this function is VERY similar to the get_string method.
10714 * That is because it is pretty much doing the same thing.
10715 * However as this function is an upgrade it isn't as tolerant to backwards
10716 * compatibility.
10718 * @return string
10719 * @throws coding_exception
10721 protected function get_string() {
10722 global $CFG;
10724 // Check if we need to process the string.
10725 if ($this->string === null) {
10726 // Check the quality of the identifier.
10727 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10728 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);
10731 // Process the string.
10732 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10733 // Debugging feature lets you display string identifier and component.
10734 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10735 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10738 // Return the string.
10739 return $this->string;
10743 * Returns the string
10745 * @param string $lang The langauge to use when processing the string
10746 * @return string
10748 public function out($lang = null) {
10749 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10750 if ($this->forcedstring) {
10751 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10752 return $this->get_string();
10754 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10755 return $translatedstring->out();
10757 return $this->get_string();
10761 * Magic __toString method for printing a string
10763 * @return string
10765 public function __toString() {
10766 return $this->get_string();
10770 * Magic __set_state method used for var_export
10772 * @param array $array
10773 * @return self
10775 public static function __set_state(array $array): self {
10776 $tmp = new lang_string($array['identifier'], $array['component'], $array['a'], $array['lang']);
10777 $tmp->string = $array['string'];
10778 $tmp->forcedstring = $array['forcedstring'];
10779 return $tmp;
10783 * Prepares the lang_string for sleep and stores only the forcedstring and
10784 * string properties... the string cannot be regenerated so we need to ensure
10785 * it is generated for this.
10787 * @return string
10789 public function __sleep() {
10790 $this->get_string();
10791 $this->forcedstring = true;
10792 return array('forcedstring', 'string', 'lang');
10796 * Returns the identifier.
10798 * @return string
10800 public function get_identifier() {
10801 return $this->identifier;
10805 * Returns the component.
10807 * @return string
10809 public function get_component() {
10810 return $this->component;
10815 * Get human readable name describing the given callable.
10817 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10818 * It does not check if the callable actually exists.
10820 * @param callable|string|array $callable
10821 * @return string|bool Human readable name of callable, or false if not a valid callable.
10823 function get_callable_name($callable) {
10825 if (!is_callable($callable, true, $name)) {
10826 return false;
10828 } else {
10829 return $name;
10834 * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10835 * Never put your faith on this function and rely on its accuracy as there might be false positives.
10836 * It just performs some simple checks, and mainly is used for places where we want to hide some options
10837 * such as site registration when $CFG->wwwroot is not publicly accessible.
10838 * Good thing is there is no false negative.
10839 * Note that it's possible to force the result of this check by specifying $CFG->site_is_public in config.php
10841 * @return bool
10843 function site_is_public() {
10844 global $CFG;
10846 // Return early if site admin has forced this setting.
10847 if (isset($CFG->site_is_public)) {
10848 return (bool)$CFG->site_is_public;
10851 $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
10853 if ($host === 'localhost' || preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10854 $ispublic = false;
10855 } else if (\core\ip_utils::is_ip_address($host) && !ip_is_public($host)) {
10856 $ispublic = false;
10857 } else if (($address = \core\ip_utils::get_ip_address($host)) && !ip_is_public($address)) {
10858 $ispublic = false;
10859 } else {
10860 $ispublic = true;
10863 return $ispublic;