Merge branch 'MDL-75176' of https://github.com/call-learning/moodle
[moodle.git] / lib / moodlelib.php
blob5cc89ea432c20166e3c0b6848b3e6a438d97004f
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 throw new \moodle_exception('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 throw new \moodle_exception('missingparam', '', '', $parname);
636 if (!is_array($param)) {
637 throw new \moodle_exception('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 = (string)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 = (string)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', '', (string)$param);
883 case PARAM_ALPHAEXT:
884 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
885 return preg_replace('/[^a-zA-Z_-]/i', '', (string)$param);
887 case PARAM_ALPHANUM:
888 // Remove everything not `a-zA-Z0-9`.
889 return preg_replace('/[^A-Za-z0-9]/i', '', (string)$param);
891 case PARAM_ALPHANUMEXT:
892 // Remove everything not `a-zA-Z0-9_-`.
893 return preg_replace('/[^A-Za-z0-9_-]/i', '', (string)$param);
895 case PARAM_SEQUENCE:
896 // Remove everything not `0-9,`.
897 return preg_replace('/[^0-9,]/i', '', (string)$param);
899 case PARAM_BOOL:
900 // Convert to 1 or 0.
901 $tempstr = strtolower((string)$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((string)$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((string)$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((string)$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((string)$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 $param = (string)$param;
984 if (!preg_match('/^[a-z][a-z0-9]*(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
985 return '';
987 if (strpos($param, '__') !== false) {
988 return '';
990 if (strpos($param, 'mod_') === 0) {
991 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
992 if (substr_count($param, '_') != 1) {
993 return '';
996 return $param;
998 case PARAM_PLUGIN:
999 case PARAM_AREA:
1000 // We do not want any guessing here, either the name is correct or not.
1001 if (!is_valid_plugin_name($param)) {
1002 return '';
1004 return $param;
1006 case PARAM_SAFEDIR:
1007 // Remove everything not a-zA-Z0-9_- .
1008 return preg_replace('/[^a-zA-Z0-9_-]/i', '', (string)$param);
1010 case PARAM_SAFEPATH:
1011 // Remove everything not a-zA-Z0-9/_- .
1012 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', (string)$param);
1014 case PARAM_FILE:
1015 // Strip all suspicious characters from filename.
1016 $param = (string)fix_utf8($param);
1017 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
1018 if ($param === '.' || $param === '..') {
1019 $param = '';
1021 return $param;
1023 case PARAM_PATH:
1024 // Strip all suspicious characters from file path.
1025 $param = (string)fix_utf8($param);
1026 $param = str_replace('\\', '/', $param);
1028 // Explode the path and clean each element using the PARAM_FILE rules.
1029 $breadcrumb = explode('/', $param);
1030 foreach ($breadcrumb as $key => $crumb) {
1031 if ($crumb === '.' && $key === 0) {
1032 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1033 } else {
1034 $crumb = clean_param($crumb, PARAM_FILE);
1036 $breadcrumb[$key] = $crumb;
1038 $param = implode('/', $breadcrumb);
1040 // Remove multiple current path (./././) and multiple slashes (///).
1041 $param = preg_replace('~//+~', '/', $param);
1042 $param = preg_replace('~/(\./)+~', '/', $param);
1043 return $param;
1045 case PARAM_HOST:
1046 // Allow FQDN or IPv4 dotted quad.
1047 $param = preg_replace('/[^\.\d\w-]/', '', (string)$param );
1048 // Match ipv4 dotted quad.
1049 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1050 // Confirm values are ok.
1051 if ( $match[0] > 255
1052 || $match[1] > 255
1053 || $match[3] > 255
1054 || $match[4] > 255 ) {
1055 // Hmmm, what kind of dotted quad is this?
1056 $param = '';
1058 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1059 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1060 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1062 // All is ok - $param is respected.
1063 } else {
1064 // All is not ok...
1065 $param='';
1067 return $param;
1069 case PARAM_URL:
1070 // Allow safe urls.
1071 $param = (string)fix_utf8($param);
1072 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1073 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1074 // All is ok, param is respected.
1075 } else {
1076 // Not really ok.
1077 $param ='';
1079 return $param;
1081 case PARAM_LOCALURL:
1082 // Allow http absolute, root relative and relative URLs within wwwroot.
1083 $param = clean_param($param, PARAM_URL);
1084 if (!empty($param)) {
1086 if ($param === $CFG->wwwroot) {
1087 // Exact match;
1088 } else if (preg_match(':^/:', $param)) {
1089 // Root-relative, ok!
1090 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1091 // Absolute, and matches our wwwroot.
1092 } else {
1093 // Relative - let's make sure there are no tricks.
1094 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1095 // Looks ok.
1096 } else {
1097 $param = '';
1101 return $param;
1103 case PARAM_PEM:
1104 $param = trim((string)$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 = (string)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 = (string)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 = (string)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\.:/_-]*$|', (string)$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 = (string)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 throw new \moodle_exception("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)$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 // Redirect to appropriate handler when value is null.
1419 if ($value === null) {
1420 return unset_config($name, $plugin);
1423 // Set variables determining conditions and where to store the new config.
1424 // Plugin config goes to {config_plugins}, core config goes to {config}.
1425 $iscore = empty($plugin);
1426 if ($iscore) {
1427 // If it's for core config.
1428 $table = 'config';
1429 $conditions = ['name' => $name];
1430 $invalidatecachekey = 'core';
1431 } else {
1432 // If it's a plugin.
1433 $table = 'config_plugins';
1434 $conditions = ['name' => $name, 'plugin' => $plugin];
1435 $invalidatecachekey = $plugin;
1438 // DB handling - checks for existing config, updating or inserting only if necessary.
1439 $invalidatecache = true;
1440 $inserted = false;
1441 $record = $DB->get_record($table, $conditions, 'id, value');
1442 if ($record === false) {
1443 // Inserts a new config record.
1444 $config = new stdClass();
1445 $config->name = $name;
1446 $config->value = $value;
1447 if (!$iscore) {
1448 $config->plugin = $plugin;
1450 $inserted = $DB->insert_record($table, $config, false);
1451 } else if ($invalidatecache = ($record->value !== $value)) {
1452 // Record exists - Check and only set new value if it has changed.
1453 $DB->set_field($table, 'value', $value, ['id' => $record->id]);
1456 if ($iscore && !isset($CFG->config_php_settings[$name])) {
1457 // So it's defined for this invocation at least.
1458 // Settings from db are always strings.
1459 $CFG->$name = (string) $value;
1462 // When setting config during a Behat test (in the CLI script, not in the web browser
1463 // requests), remember which ones are set so that we can clear them later.
1464 if ($iscore && $inserted && defined('BEHAT_TEST')) {
1465 $CFG->behat_cli_added_config[$name] = true;
1468 // Update siteidentifier cache, if required.
1469 if ($iscore && $name === 'siteidentifier') {
1470 cache_helper::update_site_identifier($value);
1473 // Invalidate cache, if required.
1474 if ($invalidatecache) {
1475 cache_helper::invalidate_by_definition('core', 'config', [], $invalidatecachekey);
1478 return true;
1482 * Get configuration values from the global config table
1483 * or the config_plugins table.
1485 * If called with one parameter, it will load all the config
1486 * variables for one plugin, and return them as an object.
1488 * If called with 2 parameters it will return a string single
1489 * value or false if the value is not found.
1491 * NOTE: this function is called from lib/db/upgrade.php
1493 * @param string $plugin full component name
1494 * @param string $name default null
1495 * @return mixed hash-like object or single value, return false no config found
1496 * @throws dml_exception
1498 function get_config($plugin, $name = null) {
1499 global $CFG, $DB;
1501 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1502 $forced =& $CFG->config_php_settings;
1503 $iscore = true;
1504 $plugin = 'core';
1505 } else {
1506 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1507 $forced =& $CFG->forced_plugin_settings[$plugin];
1508 } else {
1509 $forced = array();
1511 $iscore = false;
1514 if (!isset($CFG->siteidentifier)) {
1515 try {
1516 // This may throw an exception during installation, which is how we detect the
1517 // need to install the database. For more details see {@see initialise_cfg()}.
1518 $CFG->siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1519 } catch (dml_exception $ex) {
1520 // Set siteidentifier to false. We don't want to trip this continually.
1521 $siteidentifier = false;
1522 throw $ex;
1526 if (!empty($name)) {
1527 if (array_key_exists($name, $forced)) {
1528 return (string)$forced[$name];
1529 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1530 return $CFG->siteidentifier;
1534 $cache = cache::make('core', 'config');
1535 $result = $cache->get($plugin);
1536 if ($result === false) {
1537 // The user is after a recordset.
1538 if (!$iscore) {
1539 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1540 } else {
1541 // This part is not really used any more, but anyway...
1542 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1544 $cache->set($plugin, $result);
1547 if (!empty($name)) {
1548 if (array_key_exists($name, $result)) {
1549 return $result[$name];
1551 return false;
1554 if ($plugin === 'core') {
1555 $result['siteidentifier'] = $CFG->siteidentifier;
1558 foreach ($forced as $key => $value) {
1559 if (is_null($value) or is_array($value) or is_object($value)) {
1560 // We do not want any extra mess here, just real settings that could be saved in db.
1561 unset($result[$key]);
1562 } else {
1563 // Convert to string as if it went through the DB.
1564 $result[$key] = (string)$value;
1568 return (object)$result;
1572 * Removes a key from global configuration.
1574 * NOTE: this function is called from lib/db/upgrade.php
1576 * @param string $name the key to set
1577 * @param string $plugin (optional) the plugin scope
1578 * @return boolean whether the operation succeeded.
1580 function unset_config($name, $plugin=null) {
1581 global $CFG, $DB;
1583 if (empty($plugin)) {
1584 unset($CFG->$name);
1585 $DB->delete_records('config', array('name' => $name));
1586 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1587 } else {
1588 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1589 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1592 return true;
1596 * Remove all the config variables for a given plugin.
1598 * NOTE: this function is called from lib/db/upgrade.php
1600 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1601 * @return boolean whether the operation succeeded.
1603 function unset_all_config_for_plugin($plugin) {
1604 global $DB;
1605 // Delete from the obvious config_plugins first.
1606 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1607 // Next delete any suspect settings from config.
1608 $like = $DB->sql_like('name', '?', true, true, false, '|');
1609 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1610 $DB->delete_records_select('config', $like, $params);
1611 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1612 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1614 return true;
1618 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1620 * All users are verified if they still have the necessary capability.
1622 * @param string $value the value of the config setting.
1623 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1624 * @param bool $includeadmins include administrators.
1625 * @return array of user objects.
1627 function get_users_from_config($value, $capability, $includeadmins = true) {
1628 if (empty($value) or $value === '$@NONE@$') {
1629 return array();
1632 // We have to make sure that users still have the necessary capability,
1633 // it should be faster to fetch them all first and then test if they are present
1634 // instead of validating them one-by-one.
1635 $users = get_users_by_capability(context_system::instance(), $capability);
1636 if ($includeadmins) {
1637 $admins = get_admins();
1638 foreach ($admins as $admin) {
1639 $users[$admin->id] = $admin;
1643 if ($value === '$@ALL@$') {
1644 return $users;
1647 $result = array(); // Result in correct order.
1648 $allowed = explode(',', $value);
1649 foreach ($allowed as $uid) {
1650 if (isset($users[$uid])) {
1651 $user = $users[$uid];
1652 $result[$user->id] = $user;
1656 return $result;
1661 * Invalidates browser caches and cached data in temp.
1663 * @return void
1665 function purge_all_caches() {
1666 purge_caches();
1670 * Selectively invalidate different types of cache.
1672 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1673 * areas alone or in combination.
1675 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1676 * 'muc' Purge MUC caches?
1677 * 'theme' Purge theme cache?
1678 * 'lang' Purge language string cache?
1679 * 'js' Purge javascript cache?
1680 * 'filter' Purge text filter cache?
1681 * 'other' Purge all other caches?
1683 function purge_caches($options = []) {
1684 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1685 if (empty(array_filter($options))) {
1686 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1687 } else {
1688 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1690 if ($options['muc']) {
1691 cache_helper::purge_all();
1693 if ($options['theme']) {
1694 theme_reset_all_caches();
1696 if ($options['lang']) {
1697 get_string_manager()->reset_caches();
1699 if ($options['js']) {
1700 js_reset_all_caches();
1702 if ($options['template']) {
1703 template_reset_all_caches();
1705 if ($options['filter']) {
1706 reset_text_filters_cache();
1708 if ($options['other']) {
1709 purge_other_caches();
1714 * Purge all non-MUC caches not otherwise purged in purge_caches.
1716 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1717 * {@link phpunit_util::reset_dataroot()}
1719 function purge_other_caches() {
1720 global $DB, $CFG;
1721 if (class_exists('core_plugin_manager')) {
1722 core_plugin_manager::reset_caches();
1725 // Bump up cacherev field for all courses.
1726 try {
1727 increment_revision_number('course', 'cacherev', '');
1728 } catch (moodle_exception $e) {
1729 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1732 $DB->reset_caches();
1734 // Purge all other caches: rss, simplepie, etc.
1735 clearstatcache();
1736 remove_dir($CFG->cachedir.'', true);
1738 // Make sure cache dir is writable, throws exception if not.
1739 make_cache_directory('');
1741 // This is the only place where we purge local caches, we are only adding files there.
1742 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1743 remove_dir($CFG->localcachedir, true);
1744 set_config('localcachedirpurged', time());
1745 make_localcache_directory('', true);
1746 \core\task\manager::clear_static_caches();
1750 * Get volatile flags
1752 * @param string $type
1753 * @param int $changedsince default null
1754 * @return array records array
1756 function get_cache_flags($type, $changedsince = null) {
1757 global $DB;
1759 $params = array('type' => $type, 'expiry' => time());
1760 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1761 if ($changedsince !== null) {
1762 $params['changedsince'] = $changedsince;
1763 $sqlwhere .= " AND timemodified > :changedsince";
1765 $cf = array();
1766 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1767 foreach ($flags as $flag) {
1768 $cf[$flag->name] = $flag->value;
1771 return $cf;
1775 * Get volatile flags
1777 * @param string $type
1778 * @param string $name
1779 * @param int $changedsince default null
1780 * @return string|false The cache flag value or false
1782 function get_cache_flag($type, $name, $changedsince=null) {
1783 global $DB;
1785 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1787 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1788 if ($changedsince !== null) {
1789 $params['changedsince'] = $changedsince;
1790 $sqlwhere .= " AND timemodified > :changedsince";
1793 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1797 * Set a volatile flag
1799 * @param string $type the "type" namespace for the key
1800 * @param string $name the key to set
1801 * @param string $value the value to set (without magic quotes) - null will remove the flag
1802 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1803 * @return bool Always returns true
1805 function set_cache_flag($type, $name, $value, $expiry = null) {
1806 global $DB;
1808 $timemodified = time();
1809 if ($expiry === null || $expiry < $timemodified) {
1810 $expiry = $timemodified + 24 * 60 * 60;
1811 } else {
1812 $expiry = (int)$expiry;
1815 if ($value === null) {
1816 unset_cache_flag($type, $name);
1817 return true;
1820 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1821 // This is a potential problem in DEBUG_DEVELOPER.
1822 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1823 return true; // No need to update.
1825 $f->value = $value;
1826 $f->expiry = $expiry;
1827 $f->timemodified = $timemodified;
1828 $DB->update_record('cache_flags', $f);
1829 } else {
1830 $f = new stdClass();
1831 $f->flagtype = $type;
1832 $f->name = $name;
1833 $f->value = $value;
1834 $f->expiry = $expiry;
1835 $f->timemodified = $timemodified;
1836 $DB->insert_record('cache_flags', $f);
1838 return true;
1842 * Removes a single volatile flag
1844 * @param string $type the "type" namespace for the key
1845 * @param string $name the key to set
1846 * @return bool
1848 function unset_cache_flag($type, $name) {
1849 global $DB;
1850 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1851 return true;
1855 * Garbage-collect volatile flags
1857 * @return bool Always returns true
1859 function gc_cache_flags() {
1860 global $DB;
1861 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1862 return true;
1865 // USER PREFERENCE API.
1868 * Refresh user preference cache. This is used most often for $USER
1869 * object that is stored in session, but it also helps with performance in cron script.
1871 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1873 * @package core
1874 * @category preference
1875 * @access public
1876 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1877 * @param int $cachelifetime Cache life time on the current page (in seconds)
1878 * @throws coding_exception
1879 * @return null
1881 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1882 global $DB;
1883 // Static cache, we need to check on each page load, not only every 2 minutes.
1884 static $loadedusers = array();
1886 if (!isset($user->id)) {
1887 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1890 if (empty($user->id) or isguestuser($user->id)) {
1891 // No permanent storage for not-logged-in users and guest.
1892 if (!isset($user->preference)) {
1893 $user->preference = array();
1895 return;
1898 $timenow = time();
1900 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1901 // Already loaded at least once on this page. Are we up to date?
1902 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1903 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1904 return;
1906 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1907 // No change since the lastcheck on this page.
1908 $user->preference['_lastloaded'] = $timenow;
1909 return;
1913 // OK, so we have to reload all preferences.
1914 $loadedusers[$user->id] = true;
1915 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1916 $user->preference['_lastloaded'] = $timenow;
1920 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1922 * NOTE: internal function, do not call from other code.
1924 * @package core
1925 * @access private
1926 * @param integer $userid the user whose prefs were changed.
1928 function mark_user_preferences_changed($userid) {
1929 global $CFG;
1931 if (empty($userid) or isguestuser($userid)) {
1932 // No cache flags for guest and not-logged-in users.
1933 return;
1936 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1940 * Sets a preference for the specified user.
1942 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1944 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1946 * @package core
1947 * @category preference
1948 * @access public
1949 * @param string $name The key to set as preference for the specified user
1950 * @param string $value The value to set for the $name key in the specified user's
1951 * record, null means delete current value.
1952 * @param stdClass|int|null $user A moodle user object or id, null means current user
1953 * @throws coding_exception
1954 * @return bool Always true or exception
1956 function set_user_preference($name, $value, $user = null) {
1957 global $USER, $DB;
1959 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1960 throw new coding_exception('Invalid preference name in set_user_preference() call');
1963 if (is_null($value)) {
1964 // Null means delete current.
1965 return unset_user_preference($name, $user);
1966 } else if (is_object($value)) {
1967 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1968 } else if (is_array($value)) {
1969 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1971 // Value column maximum length is 1333 characters.
1972 $value = (string)$value;
1973 if (core_text::strlen($value) > 1333) {
1974 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1977 if (is_null($user)) {
1978 $user = $USER;
1979 } else if (isset($user->id)) {
1980 // It is a valid object.
1981 } else if (is_numeric($user)) {
1982 $user = (object)array('id' => (int)$user);
1983 } else {
1984 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1987 check_user_preferences_loaded($user);
1989 if (empty($user->id) or isguestuser($user->id)) {
1990 // No permanent storage for not-logged-in users and guest.
1991 $user->preference[$name] = $value;
1992 return true;
1995 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1996 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1997 // Preference already set to this value.
1998 return true;
2000 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
2002 } else {
2003 $preference = new stdClass();
2004 $preference->userid = $user->id;
2005 $preference->name = $name;
2006 $preference->value = $value;
2007 $DB->insert_record('user_preferences', $preference);
2010 // Update value in cache.
2011 $user->preference[$name] = $value;
2012 // Update the $USER in case where we've not a direct reference to $USER.
2013 if ($user !== $USER && $user->id == $USER->id) {
2014 $USER->preference[$name] = $value;
2017 // Set reload flag for other sessions.
2018 mark_user_preferences_changed($user->id);
2020 return true;
2024 * Sets a whole array of preferences for the current user
2026 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2028 * @package core
2029 * @category preference
2030 * @access public
2031 * @param array $prefarray An array of key/value pairs to be set
2032 * @param stdClass|int|null $user A moodle user object or id, null means current user
2033 * @return bool Always true or exception
2035 function set_user_preferences(array $prefarray, $user = null) {
2036 foreach ($prefarray as $name => $value) {
2037 set_user_preference($name, $value, $user);
2039 return true;
2043 * Unsets a preference completely by deleting it from the database
2045 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2047 * @package core
2048 * @category preference
2049 * @access public
2050 * @param string $name The key to unset as preference for the specified user
2051 * @param stdClass|int|null $user A moodle user object or id, null means current user
2052 * @throws coding_exception
2053 * @return bool Always true or exception
2055 function unset_user_preference($name, $user = null) {
2056 global $USER, $DB;
2058 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2059 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2062 if (is_null($user)) {
2063 $user = $USER;
2064 } else if (isset($user->id)) {
2065 // It is a valid object.
2066 } else if (is_numeric($user)) {
2067 $user = (object)array('id' => (int)$user);
2068 } else {
2069 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2072 check_user_preferences_loaded($user);
2074 if (empty($user->id) or isguestuser($user->id)) {
2075 // No permanent storage for not-logged-in user and guest.
2076 unset($user->preference[$name]);
2077 return true;
2080 // Delete from DB.
2081 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2083 // Delete the preference from cache.
2084 unset($user->preference[$name]);
2085 // Update the $USER in case where we've not a direct reference to $USER.
2086 if ($user !== $USER && $user->id == $USER->id) {
2087 unset($USER->preference[$name]);
2090 // Set reload flag for other sessions.
2091 mark_user_preferences_changed($user->id);
2093 return true;
2097 * Used to fetch user preference(s)
2099 * If no arguments are supplied this function will return
2100 * all of the current user preferences as an array.
2102 * If a name is specified then this function
2103 * attempts to return that particular preference value. If
2104 * none is found, then the optional value $default is returned,
2105 * otherwise null.
2107 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2109 * @package core
2110 * @category preference
2111 * @access public
2112 * @param string $name Name of the key to use in finding a preference value
2113 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2114 * @param stdClass|int|null $user A moodle user object or id, null means current user
2115 * @throws coding_exception
2116 * @return string|mixed|null A string containing the value of a single preference. An
2117 * array with all of the preferences or null
2119 function get_user_preferences($name = null, $default = null, $user = null) {
2120 global $USER;
2122 if (is_null($name)) {
2123 // All prefs.
2124 } else if (is_numeric($name) or $name === '_lastloaded') {
2125 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2128 if (is_null($user)) {
2129 $user = $USER;
2130 } else if (isset($user->id)) {
2131 // Is a valid object.
2132 } else if (is_numeric($user)) {
2133 if ($USER->id == $user) {
2134 $user = $USER;
2135 } else {
2136 $user = (object)array('id' => (int)$user);
2138 } else {
2139 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2142 check_user_preferences_loaded($user);
2144 if (empty($name)) {
2145 // All values.
2146 return $user->preference;
2147 } else if (isset($user->preference[$name])) {
2148 // The single string value.
2149 return $user->preference[$name];
2150 } else {
2151 // Default value (null if not specified).
2152 return $default;
2156 // FUNCTIONS FOR HANDLING TIME.
2159 * Given Gregorian date parts in user time produce a GMT timestamp.
2161 * @package core
2162 * @category time
2163 * @param int $year The year part to create timestamp of
2164 * @param int $month The month part to create timestamp of
2165 * @param int $day The day part to create timestamp of
2166 * @param int $hour The hour part to create timestamp of
2167 * @param int $minute The minute part to create timestamp of
2168 * @param int $second The second part to create timestamp of
2169 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2170 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2171 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2172 * applied only if timezone is 99 or string.
2173 * @return int GMT timestamp
2175 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2176 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2177 $date->setDate((int)$year, (int)$month, (int)$day);
2178 $date->setTime((int)$hour, (int)$minute, (int)$second);
2180 $time = $date->getTimestamp();
2182 if ($time === false) {
2183 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2184 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2187 // Moodle BC DST stuff.
2188 if (!$applydst) {
2189 $time += dst_offset_on($time, $timezone);
2192 return $time;
2197 * Format a date/time (seconds) as weeks, days, hours etc as needed
2199 * Given an amount of time in seconds, returns string
2200 * formatted nicely as years, days, hours etc as needed
2202 * @package core
2203 * @category time
2204 * @uses MINSECS
2205 * @uses HOURSECS
2206 * @uses DAYSECS
2207 * @uses YEARSECS
2208 * @param int $totalsecs Time in seconds
2209 * @param stdClass $str Should be a time object
2210 * @return string A nicely formatted date/time string
2212 function format_time($totalsecs, $str = null) {
2214 $totalsecs = abs($totalsecs);
2216 if (!$str) {
2217 // Create the str structure the slow way.
2218 $str = new stdClass();
2219 $str->day = get_string('day');
2220 $str->days = get_string('days');
2221 $str->hour = get_string('hour');
2222 $str->hours = get_string('hours');
2223 $str->min = get_string('min');
2224 $str->mins = get_string('mins');
2225 $str->sec = get_string('sec');
2226 $str->secs = get_string('secs');
2227 $str->year = get_string('year');
2228 $str->years = get_string('years');
2231 $years = floor($totalsecs/YEARSECS);
2232 $remainder = $totalsecs - ($years*YEARSECS);
2233 $days = floor($remainder/DAYSECS);
2234 $remainder = $totalsecs - ($days*DAYSECS);
2235 $hours = floor($remainder/HOURSECS);
2236 $remainder = $remainder - ($hours*HOURSECS);
2237 $mins = floor($remainder/MINSECS);
2238 $secs = $remainder - ($mins*MINSECS);
2240 $ss = ($secs == 1) ? $str->sec : $str->secs;
2241 $sm = ($mins == 1) ? $str->min : $str->mins;
2242 $sh = ($hours == 1) ? $str->hour : $str->hours;
2243 $sd = ($days == 1) ? $str->day : $str->days;
2244 $sy = ($years == 1) ? $str->year : $str->years;
2246 $oyears = '';
2247 $odays = '';
2248 $ohours = '';
2249 $omins = '';
2250 $osecs = '';
2252 if ($years) {
2253 $oyears = $years .' '. $sy;
2255 if ($days) {
2256 $odays = $days .' '. $sd;
2258 if ($hours) {
2259 $ohours = $hours .' '. $sh;
2261 if ($mins) {
2262 $omins = $mins .' '. $sm;
2264 if ($secs) {
2265 $osecs = $secs .' '. $ss;
2268 if ($years) {
2269 return trim($oyears .' '. $odays);
2271 if ($days) {
2272 return trim($odays .' '. $ohours);
2274 if ($hours) {
2275 return trim($ohours .' '. $omins);
2277 if ($mins) {
2278 return trim($omins .' '. $osecs);
2280 if ($secs) {
2281 return $osecs;
2283 return get_string('now');
2287 * Returns a formatted string that represents a date in user time.
2289 * @package core
2290 * @category time
2291 * @param int $date the timestamp in UTC, as obtained from the database.
2292 * @param string $format strftime format. You should probably get this using
2293 * get_string('strftime...', 'langconfig');
2294 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2295 * not 99 then daylight saving will not be added.
2296 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2297 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2298 * If false then the leading zero is maintained.
2299 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2300 * @return string the formatted date/time.
2302 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2303 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2304 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2308 * Returns a html "time" tag with both the exact user date with timezone information
2309 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2311 * @package core
2312 * @category time
2313 * @param int $date the timestamp in UTC, as obtained from the database.
2314 * @param string $format strftime format. You should probably get this using
2315 * get_string('strftime...', 'langconfig');
2316 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2317 * not 99 then daylight saving will not be added.
2318 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2319 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2320 * If false then the leading zero is maintained.
2321 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2322 * @return string the formatted date/time.
2324 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2325 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2326 if (CLI_SCRIPT && !PHPUNIT_TEST) {
2327 return $userdatestr;
2329 $machinedate = new DateTime();
2330 $machinedate->setTimestamp(intval($date));
2331 $machinedate->setTimezone(core_date::get_user_timezone_object());
2333 return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2337 * Returns a formatted date ensuring it is UTF-8.
2339 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2340 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2342 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2343 * @param string $format strftime format.
2344 * @param int|float|string $tz the user timezone
2345 * @return string the formatted date/time.
2346 * @since Moodle 2.3.3
2348 function date_format_string($date, $format, $tz = 99) {
2349 global $CFG;
2351 $localewincharset = null;
2352 // Get the calendar type user is using.
2353 if ($CFG->ostype == 'WINDOWS') {
2354 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2355 $localewincharset = $calendartype->locale_win_charset();
2358 if ($localewincharset) {
2359 $format = core_text::convert($format, 'utf-8', $localewincharset);
2362 date_default_timezone_set(core_date::get_user_timezone($tz));
2364 if (strftime('%p', 0) === strftime('%p', HOURSECS * 18)) {
2365 $datearray = getdate($date);
2366 $format = str_replace([
2367 '%P',
2368 '%p',
2369 ], [
2370 $datearray['hours'] < 12 ? get_string('am', 'langconfig') : get_string('pm', 'langconfig'),
2371 $datearray['hours'] < 12 ? get_string('amcaps', 'langconfig') : get_string('pmcaps', 'langconfig'),
2372 ], $format);
2375 $datestring = strftime($format, $date);
2376 core_date::set_default_server_timezone();
2378 if ($localewincharset) {
2379 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2382 return $datestring;
2386 * Given a $time timestamp in GMT (seconds since epoch),
2387 * returns an array that represents the Gregorian date in user time
2389 * @package core
2390 * @category time
2391 * @param int $time Timestamp in GMT
2392 * @param float|int|string $timezone user timezone
2393 * @return array An array that represents the date in user time
2395 function usergetdate($time, $timezone=99) {
2396 if ($time === null) {
2397 // PHP8 and PHP7 return different results when getdate(null) is called.
2398 // Display warning and cast to 0 to make sure the usergetdate() behaves consistently on all versions of PHP.
2399 // In the future versions of Moodle we may consider adding a strict typehint.
2400 debugging('usergetdate() expects parameter $time to be int, null given', DEBUG_DEVELOPER);
2401 $time = 0;
2404 date_default_timezone_set(core_date::get_user_timezone($timezone));
2405 $result = getdate($time);
2406 core_date::set_default_server_timezone();
2408 return $result;
2412 * Given a GMT timestamp (seconds since epoch), offsets it by
2413 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2415 * NOTE: this function does not include DST properly,
2416 * you should use the PHP date stuff instead!
2418 * @package core
2419 * @category time
2420 * @param int $date Timestamp in GMT
2421 * @param float|int|string $timezone user timezone
2422 * @return int
2424 function usertime($date, $timezone=99) {
2425 $userdate = new DateTime('@' . $date);
2426 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2427 $dst = dst_offset_on($date, $timezone);
2429 return $date - $userdate->getOffset() + $dst;
2433 * Get a formatted string representation of an interval between two unix timestamps.
2435 * E.g.
2436 * $intervalstring = get_time_interval_string(12345600, 12345660);
2437 * Will produce the string:
2438 * '0d 0h 1m'
2440 * @param int $time1 unix timestamp
2441 * @param int $time2 unix timestamp
2442 * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2443 * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2445 function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
2446 $dtdate = new DateTime();
2447 $dtdate->setTimeStamp($time1);
2448 $dtdate2 = new DateTime();
2449 $dtdate2->setTimeStamp($time2);
2450 $interval = $dtdate2->diff($dtdate);
2451 $format = empty($format) ? get_string('dateintervaldayshoursmins', 'langconfig') : $format;
2452 return $interval->format($format);
2456 * Given a time, return the GMT timestamp of the most recent midnight
2457 * for the current user.
2459 * @package core
2460 * @category time
2461 * @param int $date Timestamp in GMT
2462 * @param float|int|string $timezone user timezone
2463 * @return int Returns a GMT timestamp
2465 function usergetmidnight($date, $timezone=99) {
2467 $userdate = usergetdate($date, $timezone);
2469 // Time of midnight of this user's day, in GMT.
2470 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2475 * Returns a string that prints the user's timezone
2477 * @package core
2478 * @category time
2479 * @param float|int|string $timezone user timezone
2480 * @return string
2482 function usertimezone($timezone=99) {
2483 $tz = core_date::get_user_timezone($timezone);
2484 return core_date::get_localised_timezone($tz);
2488 * Returns a float or a string which denotes the user's timezone
2489 * A float value means that a simple offset from GMT is used, while a string (it will be the name of a timezone in the database)
2490 * means that for this timezone there are also DST rules to be taken into account
2491 * Checks various settings and picks the most dominant of those which have a value
2493 * @package core
2494 * @category time
2495 * @param float|int|string $tz timezone to calculate GMT time offset before
2496 * calculating user timezone, 99 is default user timezone
2497 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2498 * @return float|string
2500 function get_user_timezone($tz = 99) {
2501 global $USER, $CFG;
2503 $timezones = array(
2504 $tz,
2505 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2506 isset($USER->timezone) ? $USER->timezone : 99,
2507 isset($CFG->timezone) ? $CFG->timezone : 99,
2510 $tz = 99;
2512 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2513 foreach ($timezones as $nextvalue) {
2514 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2515 $tz = $nextvalue;
2518 return is_numeric($tz) ? (float) $tz : $tz;
2522 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2523 * - Note: Daylight saving only works for string timezones and not for float.
2525 * @package core
2526 * @category time
2527 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2528 * @param int|float|string $strtimezone user timezone
2529 * @return int
2531 function dst_offset_on($time, $strtimezone = null) {
2532 $tz = core_date::get_user_timezone($strtimezone);
2533 $date = new DateTime('@' . $time);
2534 $date->setTimezone(new DateTimeZone($tz));
2535 if ($date->format('I') == '1') {
2536 if ($tz === 'Australia/Lord_Howe') {
2537 return 1800;
2539 return 3600;
2541 return 0;
2545 * Calculates when the day appears in specific month
2547 * @package core
2548 * @category time
2549 * @param int $startday starting day of the month
2550 * @param int $weekday The day when week starts (normally taken from user preferences)
2551 * @param int $month The month whose day is sought
2552 * @param int $year The year of the month whose day is sought
2553 * @return int
2555 function find_day_in_month($startday, $weekday, $month, $year) {
2556 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2558 $daysinmonth = days_in_month($month, $year);
2559 $daysinweek = count($calendartype->get_weekdays());
2561 if ($weekday == -1) {
2562 // Don't care about weekday, so return:
2563 // abs($startday) if $startday != -1
2564 // $daysinmonth otherwise.
2565 return ($startday == -1) ? $daysinmonth : abs($startday);
2568 // From now on we 're looking for a specific weekday.
2569 // Give "end of month" its actual value, since we know it.
2570 if ($startday == -1) {
2571 $startday = -1 * $daysinmonth;
2574 // Starting from day $startday, the sign is the direction.
2575 if ($startday < 1) {
2576 $startday = abs($startday);
2577 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2579 // This is the last such weekday of the month.
2580 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2581 if ($lastinmonth > $daysinmonth) {
2582 $lastinmonth -= $daysinweek;
2585 // Find the first such weekday <= $startday.
2586 while ($lastinmonth > $startday) {
2587 $lastinmonth -= $daysinweek;
2590 return $lastinmonth;
2591 } else {
2592 $indexweekday = dayofweek($startday, $month, $year);
2594 $diff = $weekday - $indexweekday;
2595 if ($diff < 0) {
2596 $diff += $daysinweek;
2599 // This is the first such weekday of the month equal to or after $startday.
2600 $firstfromindex = $startday + $diff;
2602 return $firstfromindex;
2607 * Calculate the number of days in a given month
2609 * @package core
2610 * @category time
2611 * @param int $month The month whose day count is sought
2612 * @param int $year The year of the month whose day count is sought
2613 * @return int
2615 function days_in_month($month, $year) {
2616 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2617 return $calendartype->get_num_days_in_month($year, $month);
2621 * Calculate the position in the week of a specific calendar day
2623 * @package core
2624 * @category time
2625 * @param int $day The day of the date whose position in the week is sought
2626 * @param int $month The month of the date whose position in the week is sought
2627 * @param int $year The year of the date whose position in the week is sought
2628 * @return int
2630 function dayofweek($day, $month, $year) {
2631 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2632 return $calendartype->get_weekday($year, $month, $day);
2635 // USER AUTHENTICATION AND LOGIN.
2638 * Returns full login url.
2640 * Any form submissions for authentication to this URL must include username,
2641 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2643 * @return string login url
2645 function get_login_url() {
2646 global $CFG;
2648 return "$CFG->wwwroot/login/index.php";
2652 * This function checks that the current user is logged in and has the
2653 * required privileges
2655 * This function checks that the current user is logged in, and optionally
2656 * whether they are allowed to be in a particular course and view a particular
2657 * course module.
2658 * If they are not logged in, then it redirects them to the site login unless
2659 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2660 * case they are automatically logged in as guests.
2661 * If $courseid is given and the user is not enrolled in that course then the
2662 * user is redirected to the course enrolment page.
2663 * If $cm is given and the course module is hidden and the user is not a teacher
2664 * in the course then the user is redirected to the course home page.
2666 * When $cm parameter specified, this function sets page layout to 'module'.
2667 * You need to change it manually later if some other layout needed.
2669 * @package core_access
2670 * @category access
2672 * @param mixed $courseorid id of the course or course object
2673 * @param bool $autologinguest default true
2674 * @param object $cm course module object
2675 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2676 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2677 * in order to keep redirects working properly. MDL-14495
2678 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2679 * @return mixed Void, exit, and die depending on path
2680 * @throws coding_exception
2681 * @throws require_login_exception
2682 * @throws moodle_exception
2684 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2685 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2687 // Must not redirect when byteserving already started.
2688 if (!empty($_SERVER['HTTP_RANGE'])) {
2689 $preventredirect = true;
2692 if (AJAX_SCRIPT) {
2693 // We cannot redirect for AJAX scripts either.
2694 $preventredirect = true;
2697 // Setup global $COURSE, themes, language and locale.
2698 if (!empty($courseorid)) {
2699 if (is_object($courseorid)) {
2700 $course = $courseorid;
2701 } else if ($courseorid == SITEID) {
2702 $course = clone($SITE);
2703 } else {
2704 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2706 if ($cm) {
2707 if ($cm->course != $course->id) {
2708 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2710 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2711 if (!($cm instanceof cm_info)) {
2712 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2713 // db queries so this is not really a performance concern, however it is obviously
2714 // better if you use get_fast_modinfo to get the cm before calling this.
2715 $modinfo = get_fast_modinfo($course);
2716 $cm = $modinfo->get_cm($cm->id);
2719 } else {
2720 // Do not touch global $COURSE via $PAGE->set_course(),
2721 // the reasons is we need to be able to call require_login() at any time!!
2722 $course = $SITE;
2723 if ($cm) {
2724 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2728 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2729 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2730 // risk leading the user back to the AJAX request URL.
2731 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2732 $setwantsurltome = false;
2735 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2736 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2737 if ($preventredirect) {
2738 throw new require_login_session_timeout_exception();
2739 } else {
2740 if ($setwantsurltome) {
2741 $SESSION->wantsurl = qualified_me();
2743 redirect(get_login_url());
2747 // If the user is not even logged in yet then make sure they are.
2748 if (!isloggedin()) {
2749 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2750 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2751 // Misconfigured site guest, just redirect to login page.
2752 redirect(get_login_url());
2753 exit; // Never reached.
2755 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2756 complete_user_login($guest);
2757 $USER->autologinguest = true;
2758 $SESSION->lang = $lang;
2759 } else {
2760 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2761 if ($preventredirect) {
2762 throw new require_login_exception('You are not logged in');
2765 if ($setwantsurltome) {
2766 $SESSION->wantsurl = qualified_me();
2769 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2770 $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
2771 foreach($authsequence as $authname) {
2772 $authplugin = get_auth_plugin($authname);
2773 $authplugin->pre_loginpage_hook();
2774 if (isloggedin()) {
2775 if ($cm) {
2776 $modinfo = get_fast_modinfo($course);
2777 $cm = $modinfo->get_cm($cm->id);
2779 set_access_log_user();
2780 break;
2784 // If we're still not logged in then go to the login page
2785 if (!isloggedin()) {
2786 redirect(get_login_url());
2787 exit; // Never reached.
2792 // Loginas as redirection if needed.
2793 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2794 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2795 if ($USER->loginascontext->instanceid != $course->id) {
2796 throw new \moodle_exception('loginasonecourse', '',
2797 $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2802 // Check whether the user should be changing password (but only if it is REALLY them).
2803 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2804 $userauth = get_auth_plugin($USER->auth);
2805 if ($userauth->can_change_password() and !$preventredirect) {
2806 if ($setwantsurltome) {
2807 $SESSION->wantsurl = qualified_me();
2809 if ($changeurl = $userauth->change_password_url()) {
2810 // Use plugin custom url.
2811 redirect($changeurl);
2812 } else {
2813 // Use moodle internal method.
2814 redirect($CFG->wwwroot .'/login/change_password.php');
2816 } else if ($userauth->can_change_password()) {
2817 throw new moodle_exception('forcepasswordchangenotice');
2818 } else {
2819 throw new moodle_exception('nopasswordchangeforced', 'auth');
2823 // Check that the user account is properly set up. If we can't redirect to
2824 // edit their profile and this is not a WS request, perform just the lax check.
2825 // It will allow them to use filepicker on the profile edit page.
2827 if ($preventredirect && !WS_SERVER) {
2828 $usernotfullysetup = user_not_fully_set_up($USER, false);
2829 } else {
2830 $usernotfullysetup = user_not_fully_set_up($USER, true);
2833 if ($usernotfullysetup) {
2834 if ($preventredirect) {
2835 throw new moodle_exception('usernotfullysetup');
2837 if ($setwantsurltome) {
2838 $SESSION->wantsurl = qualified_me();
2840 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2843 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2844 sesskey();
2846 if (\core\session\manager::is_loggedinas()) {
2847 // During a "logged in as" session we should force all content to be cleaned because the
2848 // logged in user will be viewing potentially malicious user generated content.
2849 // See MDL-63786 for more details.
2850 $CFG->forceclean = true;
2853 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2855 // Do not bother admins with any formalities, except for activities pending deletion.
2856 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2857 // Set the global $COURSE.
2858 if ($cm) {
2859 $PAGE->set_cm($cm, $course);
2860 $PAGE->set_pagelayout('incourse');
2861 } else if (!empty($courseorid)) {
2862 $PAGE->set_course($course);
2864 // Set accesstime or the user will appear offline which messes up messaging.
2865 // Do not update access time for webservice or ajax requests.
2866 if (!WS_SERVER && !AJAX_SCRIPT) {
2867 user_accesstime_log($course->id);
2870 foreach ($afterlogins as $plugintype => $plugins) {
2871 foreach ($plugins as $pluginfunction) {
2872 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2875 return;
2878 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2879 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2880 if (!defined('NO_SITEPOLICY_CHECK')) {
2881 define('NO_SITEPOLICY_CHECK', false);
2884 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2885 // Do not test if the script explicitly asked for skipping the site policies check.
2886 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2887 $manager = new \core_privacy\local\sitepolicy\manager();
2888 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2889 if ($preventredirect) {
2890 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2892 if ($setwantsurltome) {
2893 $SESSION->wantsurl = qualified_me();
2895 redirect($policyurl);
2899 // Fetch the system context, the course context, and prefetch its child contexts.
2900 $sysctx = context_system::instance();
2901 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2902 if ($cm) {
2903 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2904 } else {
2905 $cmcontext = null;
2908 // If the site is currently under maintenance, then print a message.
2909 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2910 if ($preventredirect) {
2911 throw new require_login_exception('Maintenance in progress');
2913 $PAGE->set_context(null);
2914 print_maintenance_message();
2917 // Make sure the course itself is not hidden.
2918 if ($course->id == SITEID) {
2919 // Frontpage can not be hidden.
2920 } else {
2921 if (is_role_switched($course->id)) {
2922 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2923 } else {
2924 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2925 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2926 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2927 if ($preventredirect) {
2928 throw new require_login_exception('Course is hidden');
2930 $PAGE->set_context(null);
2931 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2932 // the navigation will mess up when trying to find it.
2933 navigation_node::override_active_url(new moodle_url('/'));
2934 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2939 // Is the user enrolled?
2940 if ($course->id == SITEID) {
2941 // Everybody is enrolled on the frontpage.
2942 } else {
2943 if (\core\session\manager::is_loggedinas()) {
2944 // Make sure the REAL person can access this course first.
2945 $realuser = \core\session\manager::get_realuser();
2946 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2947 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2948 if ($preventredirect) {
2949 throw new require_login_exception('Invalid course login-as access');
2951 $PAGE->set_context(null);
2952 echo $OUTPUT->header();
2953 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2957 $access = false;
2959 if (is_role_switched($course->id)) {
2960 // Ok, user had to be inside this course before the switch.
2961 $access = true;
2963 } else if (is_viewing($coursecontext, $USER)) {
2964 // Ok, no need to mess with enrol.
2965 $access = true;
2967 } else {
2968 if (isset($USER->enrol['enrolled'][$course->id])) {
2969 if ($USER->enrol['enrolled'][$course->id] > time()) {
2970 $access = true;
2971 if (isset($USER->enrol['tempguest'][$course->id])) {
2972 unset($USER->enrol['tempguest'][$course->id]);
2973 remove_temp_course_roles($coursecontext);
2975 } else {
2976 // Expired.
2977 unset($USER->enrol['enrolled'][$course->id]);
2980 if (isset($USER->enrol['tempguest'][$course->id])) {
2981 if ($USER->enrol['tempguest'][$course->id] == 0) {
2982 $access = true;
2983 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2984 $access = true;
2985 } else {
2986 // Expired.
2987 unset($USER->enrol['tempguest'][$course->id]);
2988 remove_temp_course_roles($coursecontext);
2992 if (!$access) {
2993 // Cache not ok.
2994 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2995 if ($until !== false) {
2996 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2997 if ($until == 0) {
2998 $until = ENROL_MAX_TIMESTAMP;
3000 $USER->enrol['enrolled'][$course->id] = $until;
3001 $access = true;
3003 } else if (core_course_category::can_view_course_info($course)) {
3004 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
3005 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3006 $enrols = enrol_get_plugins(true);
3007 // First ask all enabled enrol instances in course if they want to auto enrol user.
3008 foreach ($instances as $instance) {
3009 if (!isset($enrols[$instance->enrol])) {
3010 continue;
3012 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3013 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3014 if ($until !== false) {
3015 if ($until == 0) {
3016 $until = ENROL_MAX_TIMESTAMP;
3018 $USER->enrol['enrolled'][$course->id] = $until;
3019 $access = true;
3020 break;
3023 // If not enrolled yet try to gain temporary guest access.
3024 if (!$access) {
3025 foreach ($instances as $instance) {
3026 if (!isset($enrols[$instance->enrol])) {
3027 continue;
3029 // Get a duration for the guest access, a timestamp in the future or false.
3030 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3031 if ($until !== false and $until > time()) {
3032 $USER->enrol['tempguest'][$course->id] = $until;
3033 $access = true;
3034 break;
3038 } else {
3039 // User is not enrolled and is not allowed to browse courses here.
3040 if ($preventredirect) {
3041 throw new require_login_exception('Course is not available');
3043 $PAGE->set_context(null);
3044 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3045 // the navigation will mess up when trying to find it.
3046 navigation_node::override_active_url(new moodle_url('/'));
3047 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3052 if (!$access) {
3053 if ($preventredirect) {
3054 throw new require_login_exception('Not enrolled');
3056 if ($setwantsurltome) {
3057 $SESSION->wantsurl = qualified_me();
3059 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3063 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3064 if ($cm && $cm->deletioninprogress) {
3065 if ($preventredirect) {
3066 throw new moodle_exception('activityisscheduledfordeletion');
3068 require_once($CFG->dirroot . '/course/lib.php');
3069 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3072 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3073 if ($cm && !$cm->uservisible) {
3074 if ($preventredirect) {
3075 throw new require_login_exception('Activity is hidden');
3077 // Get the error message that activity is not available and why (if explanation can be shown to the user).
3078 $PAGE->set_course($course);
3079 $renderer = $PAGE->get_renderer('course');
3080 $message = $renderer->course_section_cm_unavailable_error_message($cm);
3081 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
3084 // Set the global $COURSE.
3085 if ($cm) {
3086 $PAGE->set_cm($cm, $course);
3087 $PAGE->set_pagelayout('incourse');
3088 } else if (!empty($courseorid)) {
3089 $PAGE->set_course($course);
3092 foreach ($afterlogins as $plugintype => $plugins) {
3093 foreach ($plugins as $pluginfunction) {
3094 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3098 // Finally access granted, update lastaccess times.
3099 // Do not update access time for webservice or ajax requests.
3100 if (!WS_SERVER && !AJAX_SCRIPT) {
3101 user_accesstime_log($course->id);
3106 * A convenience function for where we must be logged in as admin
3107 * @return void
3109 function require_admin() {
3110 require_login(null, false);
3111 require_capability('moodle/site:config', context_system::instance());
3115 * This function just makes sure a user is logged out.
3117 * @package core_access
3118 * @category access
3120 function require_logout() {
3121 global $USER, $DB;
3123 if (!isloggedin()) {
3124 // This should not happen often, no need for hooks or events here.
3125 \core\session\manager::terminate_current();
3126 return;
3129 // Execute hooks before action.
3130 $authplugins = array();
3131 $authsequence = get_enabled_auth_plugins();
3132 foreach ($authsequence as $authname) {
3133 $authplugins[$authname] = get_auth_plugin($authname);
3134 $authplugins[$authname]->prelogout_hook();
3137 // Store info that gets removed during logout.
3138 $sid = session_id();
3139 $event = \core\event\user_loggedout::create(
3140 array(
3141 'userid' => $USER->id,
3142 'objectid' => $USER->id,
3143 'other' => array('sessionid' => $sid),
3146 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3147 $event->add_record_snapshot('sessions', $session);
3150 // Clone of $USER object to be used by auth plugins.
3151 $user = fullclone($USER);
3153 // Delete session record and drop $_SESSION content.
3154 \core\session\manager::terminate_current();
3156 // Trigger event AFTER action.
3157 $event->trigger();
3159 // Hook to execute auth plugins redirection after event trigger.
3160 foreach ($authplugins as $authplugin) {
3161 $authplugin->postlogout_hook($user);
3166 * Weaker version of require_login()
3168 * This is a weaker version of {@link require_login()} which only requires login
3169 * when called from within a course rather than the site page, unless
3170 * the forcelogin option is turned on.
3171 * @see require_login()
3173 * @package core_access
3174 * @category access
3176 * @param mixed $courseorid The course object or id in question
3177 * @param bool $autologinguest Allow autologin guests if that is wanted
3178 * @param object $cm Course activity module if known
3179 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3180 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3181 * in order to keep redirects working properly. MDL-14495
3182 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3183 * @return void
3184 * @throws coding_exception
3186 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3187 global $CFG, $PAGE, $SITE;
3188 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3189 or (!is_object($courseorid) and $courseorid == SITEID));
3190 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3191 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3192 // db queries so this is not really a performance concern, however it is obviously
3193 // better if you use get_fast_modinfo to get the cm before calling this.
3194 if (is_object($courseorid)) {
3195 $course = $courseorid;
3196 } else {
3197 $course = clone($SITE);
3199 $modinfo = get_fast_modinfo($course);
3200 $cm = $modinfo->get_cm($cm->id);
3202 if (!empty($CFG->forcelogin)) {
3203 // Login required for both SITE and courses.
3204 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3206 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3207 // Always login for hidden activities.
3208 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3210 } else if (isloggedin() && !isguestuser()) {
3211 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3212 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3214 } else if ($issite) {
3215 // Login for SITE not required.
3216 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3217 if (!empty($courseorid)) {
3218 if (is_object($courseorid)) {
3219 $course = $courseorid;
3220 } else {
3221 $course = clone $SITE;
3223 if ($cm) {
3224 if ($cm->course != $course->id) {
3225 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3227 $PAGE->set_cm($cm, $course);
3228 $PAGE->set_pagelayout('incourse');
3229 } else {
3230 $PAGE->set_course($course);
3232 } else {
3233 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3234 $PAGE->set_course($PAGE->course);
3236 // Do not update access time for webservice or ajax requests.
3237 if (!WS_SERVER && !AJAX_SCRIPT) {
3238 user_accesstime_log(SITEID);
3240 return;
3242 } else {
3243 // Course login always required.
3244 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3249 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3251 * @param string $keyvalue the key value
3252 * @param string $script unique script identifier
3253 * @param int $instance instance id
3254 * @return stdClass the key entry in the user_private_key table
3255 * @since Moodle 3.2
3256 * @throws moodle_exception
3258 function validate_user_key($keyvalue, $script, $instance) {
3259 global $DB;
3261 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3262 throw new \moodle_exception('invalidkey');
3265 if (!empty($key->validuntil) and $key->validuntil < time()) {
3266 throw new \moodle_exception('expiredkey');
3269 if ($key->iprestriction) {
3270 $remoteaddr = getremoteaddr(null);
3271 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3272 throw new \moodle_exception('ipmismatch');
3275 return $key;
3279 * Require key login. Function terminates with error if key not found or incorrect.
3281 * @uses NO_MOODLE_COOKIES
3282 * @uses PARAM_ALPHANUM
3283 * @param string $script unique script identifier
3284 * @param int $instance optional instance id
3285 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3286 * @return int Instance ID
3288 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3289 global $DB;
3291 if (!NO_MOODLE_COOKIES) {
3292 throw new \moodle_exception('sessioncookiesdisable');
3295 // Extra safety.
3296 \core\session\manager::write_close();
3298 if (null === $keyvalue) {
3299 $keyvalue = required_param('key', PARAM_ALPHANUM);
3302 $key = validate_user_key($keyvalue, $script, $instance);
3304 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3305 throw new \moodle_exception('invaliduserid');
3308 core_user::require_active_user($user, true, true);
3310 // Emulate normal session.
3311 enrol_check_plugins($user, false);
3312 \core\session\manager::set_user($user);
3314 // Note we are not using normal login.
3315 if (!defined('USER_KEY_LOGIN')) {
3316 define('USER_KEY_LOGIN', true);
3319 // Return instance id - it might be empty.
3320 return $key->instance;
3324 * Creates a new private user access key.
3326 * @param string $script unique target identifier
3327 * @param int $userid
3328 * @param int $instance optional instance id
3329 * @param string $iprestriction optional ip restricted access
3330 * @param int $validuntil key valid only until given data
3331 * @return string access key value
3333 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3334 global $DB;
3336 $key = new stdClass();
3337 $key->script = $script;
3338 $key->userid = $userid;
3339 $key->instance = $instance;
3340 $key->iprestriction = $iprestriction;
3341 $key->validuntil = $validuntil;
3342 $key->timecreated = time();
3344 // Something long and unique.
3345 $key->value = md5($userid.'_'.time().random_string(40));
3346 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3347 // Must be unique.
3348 $key->value = md5($userid.'_'.time().random_string(40));
3350 $DB->insert_record('user_private_key', $key);
3351 return $key->value;
3355 * Delete the user's new private user access keys for a particular script.
3357 * @param string $script unique target identifier
3358 * @param int $userid
3359 * @return void
3361 function delete_user_key($script, $userid) {
3362 global $DB;
3363 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3367 * Gets a private user access key (and creates one if one doesn't exist).
3369 * @param string $script unique target identifier
3370 * @param int $userid
3371 * @param int $instance optional instance id
3372 * @param string $iprestriction optional ip restricted access
3373 * @param int $validuntil key valid only until given date
3374 * @return string access key value
3376 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3377 global $DB;
3379 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3380 'instance' => $instance, 'iprestriction' => $iprestriction,
3381 'validuntil' => $validuntil))) {
3382 return $key->value;
3383 } else {
3384 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3390 * Modify the user table by setting the currently logged in user's last login to now.
3392 * @return bool Always returns true
3394 function update_user_login_times() {
3395 global $USER, $DB, $SESSION;
3397 if (isguestuser()) {
3398 // Do not update guest access times/ips for performance.
3399 return true;
3402 $now = time();
3404 $user = new stdClass();
3405 $user->id = $USER->id;
3407 // Make sure all users that logged in have some firstaccess.
3408 if ($USER->firstaccess == 0) {
3409 $USER->firstaccess = $user->firstaccess = $now;
3412 // Store the previous current as lastlogin.
3413 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3415 $USER->currentlogin = $user->currentlogin = $now;
3417 // Function user_accesstime_log() may not update immediately, better do it here.
3418 $USER->lastaccess = $user->lastaccess = $now;
3419 $SESSION->userpreviousip = $USER->lastip;
3420 $USER->lastip = $user->lastip = getremoteaddr();
3422 // Note: do not call user_update_user() here because this is part of the login process,
3423 // the login event means that these fields were updated.
3424 $DB->update_record('user', $user);
3425 return true;
3429 * Determines if a user has completed setting up their account.
3431 * The lax mode (with $strict = false) has been introduced for special cases
3432 * only where we want to skip certain checks intentionally. This is valid in
3433 * certain mnet or ajax scenarios when the user cannot / should not be
3434 * redirected to edit their profile. In most cases, you should perform the
3435 * strict check.
3437 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3438 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3439 * @return bool
3441 function user_not_fully_set_up($user, $strict = true) {
3442 global $CFG, $SESSION, $USER;
3443 require_once($CFG->dirroot.'/user/profile/lib.php');
3445 // If the user is setup then store this in the session to avoid re-checking.
3446 // Some edge cases are when the users email starts to bounce or the
3447 // configuration for custom fields has changed while they are logged in so
3448 // we re-check this fully every hour for the rare cases it has changed.
3449 if (isset($USER->id) && isset($user->id) && $USER->id === $user->id &&
3450 isset($SESSION->fullysetupstrict) && (time() - $SESSION->fullysetupstrict) < HOURSECS) {
3451 return false;
3454 if (isguestuser($user)) {
3455 return false;
3458 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3459 return true;
3462 if ($strict) {
3463 if (empty($user->id)) {
3464 // Strict mode can be used with existing accounts only.
3465 return true;
3467 if (!profile_has_required_custom_fields_set($user->id)) {
3468 return true;
3470 if (isset($USER->id) && isset($user->id) && $USER->id === $user->id) {
3471 $SESSION->fullysetupstrict = time();
3475 return false;
3479 * Check whether the user has exceeded the bounce threshold
3481 * @param stdClass $user A {@link $USER} object
3482 * @return bool true => User has exceeded bounce threshold
3484 function over_bounce_threshold($user) {
3485 global $CFG, $DB;
3487 if (empty($CFG->handlebounces)) {
3488 return false;
3491 if (empty($user->id)) {
3492 // No real (DB) user, nothing to do here.
3493 return false;
3496 // Set sensible defaults.
3497 if (empty($CFG->minbounces)) {
3498 $CFG->minbounces = 10;
3500 if (empty($CFG->bounceratio)) {
3501 $CFG->bounceratio = .20;
3503 $bouncecount = 0;
3504 $sendcount = 0;
3505 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3506 $bouncecount = $bounce->value;
3508 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3509 $sendcount = $send->value;
3511 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3515 * Used to increment or reset email sent count
3517 * @param stdClass $user object containing an id
3518 * @param bool $reset will reset the count to 0
3519 * @return void
3521 function set_send_count($user, $reset=false) {
3522 global $DB;
3524 if (empty($user->id)) {
3525 // No real (DB) user, nothing to do here.
3526 return;
3529 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3530 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3531 $DB->update_record('user_preferences', $pref);
3532 } else if (!empty($reset)) {
3533 // If it's not there and we're resetting, don't bother. Make a new one.
3534 $pref = new stdClass();
3535 $pref->name = 'email_send_count';
3536 $pref->value = 1;
3537 $pref->userid = $user->id;
3538 $DB->insert_record('user_preferences', $pref, false);
3543 * Increment or reset user's email bounce count
3545 * @param stdClass $user object containing an id
3546 * @param bool $reset will reset the count to 0
3548 function set_bounce_count($user, $reset=false) {
3549 global $DB;
3551 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3552 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3553 $DB->update_record('user_preferences', $pref);
3554 } else if (!empty($reset)) {
3555 // If it's not there and we're resetting, don't bother. Make a new one.
3556 $pref = new stdClass();
3557 $pref->name = 'email_bounce_count';
3558 $pref->value = 1;
3559 $pref->userid = $user->id;
3560 $DB->insert_record('user_preferences', $pref, false);
3565 * Determines if the logged in user is currently moving an activity
3567 * @param int $courseid The id of the course being tested
3568 * @return bool
3570 function ismoving($courseid) {
3571 global $USER;
3573 if (!empty($USER->activitycopy)) {
3574 return ($USER->activitycopycourse == $courseid);
3576 return false;
3580 * Returns a persons full name
3582 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3583 * The result may depend on system settings or language. 'override' will force the alternativefullnameformat to be used. In
3584 * English, fullname as well as alternativefullnameformat is set to 'firstname lastname' by default. But you could have
3585 * fullname set to 'firstname lastname' and alternativefullnameformat set to 'firstname middlename alternatename lastname'.
3587 * @param stdClass $user A {@link $USER} object to get full name of.
3588 * @param bool $override If true then the alternativefullnameformat format rather than fullnamedisplay format will be used.
3589 * @return string
3591 function fullname($user, $override=false) {
3592 global $CFG, $SESSION;
3594 if (!isset($user->firstname) and !isset($user->lastname)) {
3595 return '';
3598 // Get all of the name fields.
3599 $allnames = \core_user\fields::get_name_fields();
3600 if ($CFG->debugdeveloper) {
3601 foreach ($allnames as $allname) {
3602 if (!property_exists($user, $allname)) {
3603 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3604 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3605 // Message has been sent, no point in sending the message multiple times.
3606 break;
3611 if (!$override) {
3612 if (!empty($CFG->forcefirstname)) {
3613 $user->firstname = $CFG->forcefirstname;
3615 if (!empty($CFG->forcelastname)) {
3616 $user->lastname = $CFG->forcelastname;
3620 if (!empty($SESSION->fullnamedisplay)) {
3621 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3624 $template = null;
3625 // If the fullnamedisplay setting is available, set the template to that.
3626 if (isset($CFG->fullnamedisplay)) {
3627 $template = $CFG->fullnamedisplay;
3629 // If the template is empty, or set to language, return the language string.
3630 if ((empty($template) || $template == 'language') && !$override) {
3631 return get_string('fullnamedisplay', null, $user);
3634 // Check to see if we are displaying according to the alternative full name format.
3635 if ($override) {
3636 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3637 // Default to show just the user names according to the fullnamedisplay string.
3638 return get_string('fullnamedisplay', null, $user);
3639 } else {
3640 // If the override is true, then change the template to use the complete name.
3641 $template = $CFG->alternativefullnameformat;
3645 $requirednames = array();
3646 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3647 foreach ($allnames as $allname) {
3648 if (strpos($template, $allname) !== false) {
3649 $requirednames[] = $allname;
3653 $displayname = $template;
3654 // Switch in the actual data into the template.
3655 foreach ($requirednames as $altname) {
3656 if (isset($user->$altname)) {
3657 // Using empty() on the below if statement causes breakages.
3658 if ((string)$user->$altname == '') {
3659 $displayname = str_replace($altname, 'EMPTY', $displayname);
3660 } else {
3661 $displayname = str_replace($altname, $user->$altname, $displayname);
3663 } else {
3664 $displayname = str_replace($altname, 'EMPTY', $displayname);
3667 // Tidy up any misc. characters (Not perfect, but gets most characters).
3668 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3669 // katakana and parenthesis.
3670 $patterns = array();
3671 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3672 // filled in by a user.
3673 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3674 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3675 // This regular expression is to remove any double spaces in the display name.
3676 $patterns[] = '/\s{2,}/u';
3677 foreach ($patterns as $pattern) {
3678 $displayname = preg_replace($pattern, ' ', $displayname);
3681 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3682 $displayname = trim($displayname);
3683 if (empty($displayname)) {
3684 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3685 // people in general feel is a good setting to fall back on.
3686 $displayname = $user->firstname;
3688 return $displayname;
3692 * Reduces lines of duplicated code for getting user name fields.
3694 * See also {@link user_picture::unalias()}
3696 * @param object $addtoobject Object to add user name fields to.
3697 * @param object $secondobject Object that contains user name field information.
3698 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3699 * @param array $additionalfields Additional fields to be matched with data in the second object.
3700 * The key can be set to the user table field name.
3701 * @return object User name fields.
3703 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3704 $fields = [];
3705 foreach (\core_user\fields::get_name_fields() as $field) {
3706 $fields[$field] = $prefix . $field;
3708 if ($additionalfields) {
3709 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3710 // the key is a number and then sets the key to the array value.
3711 foreach ($additionalfields as $key => $value) {
3712 if (is_numeric($key)) {
3713 $additionalfields[$value] = $prefix . $value;
3714 unset($additionalfields[$key]);
3715 } else {
3716 $additionalfields[$key] = $prefix . $value;
3719 $fields = array_merge($fields, $additionalfields);
3721 foreach ($fields as $key => $field) {
3722 // Important that we have all of the user name fields present in the object that we are sending back.
3723 $addtoobject->$key = '';
3724 if (isset($secondobject->$field)) {
3725 $addtoobject->$key = $secondobject->$field;
3728 return $addtoobject;
3732 * Returns an array of values in order of occurance in a provided string.
3733 * The key in the result is the character postion in the string.
3735 * @param array $values Values to be found in the string format
3736 * @param string $stringformat The string which may contain values being searched for.
3737 * @return array An array of values in order according to placement in the string format.
3739 function order_in_string($values, $stringformat) {
3740 $valuearray = array();
3741 foreach ($values as $value) {
3742 $pattern = "/$value\b/";
3743 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3744 if (preg_match($pattern, $stringformat)) {
3745 $replacement = "thing";
3746 // Replace the value with something more unique to ensure we get the right position when using strpos().
3747 $newformat = preg_replace($pattern, $replacement, $stringformat);
3748 $position = strpos($newformat, $replacement);
3749 $valuearray[$position] = $value;
3752 ksort($valuearray);
3753 return $valuearray;
3757 * Returns whether a given authentication plugin exists.
3759 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3760 * @return boolean Whether the plugin is available.
3762 function exists_auth_plugin($auth) {
3763 global $CFG;
3765 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3766 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3768 return false;
3772 * Checks if a given plugin is in the list of enabled authentication plugins.
3774 * @param string $auth Authentication plugin.
3775 * @return boolean Whether the plugin is enabled.
3777 function is_enabled_auth($auth) {
3778 if (empty($auth)) {
3779 return false;
3782 $enabled = get_enabled_auth_plugins();
3784 return in_array($auth, $enabled);
3788 * Returns an authentication plugin instance.
3790 * @param string $auth name of authentication plugin
3791 * @return auth_plugin_base An instance of the required authentication plugin.
3793 function get_auth_plugin($auth) {
3794 global $CFG;
3796 // Check the plugin exists first.
3797 if (! exists_auth_plugin($auth)) {
3798 throw new \moodle_exception('authpluginnotfound', 'debug', '', $auth);
3801 // Return auth plugin instance.
3802 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3803 $class = "auth_plugin_$auth";
3804 return new $class;
3808 * Returns array of active auth plugins.
3810 * @param bool $fix fix $CFG->auth if needed. Only set if logged in as admin.
3811 * @return array
3813 function get_enabled_auth_plugins($fix=false) {
3814 global $CFG;
3816 $default = array('manual', 'nologin');
3818 if (empty($CFG->auth)) {
3819 $auths = array();
3820 } else {
3821 $auths = explode(',', $CFG->auth);
3824 $auths = array_unique($auths);
3825 $oldauthconfig = implode(',', $auths);
3826 foreach ($auths as $k => $authname) {
3827 if (in_array($authname, $default)) {
3828 // The manual and nologin plugin never need to be stored.
3829 unset($auths[$k]);
3830 } else if (!exists_auth_plugin($authname)) {
3831 debugging(get_string('authpluginnotfound', 'debug', $authname));
3832 unset($auths[$k]);
3836 // Ideally only explicit interaction from a human admin should trigger a
3837 // change in auth config, see MDL-70424 for details.
3838 if ($fix) {
3839 $newconfig = implode(',', $auths);
3840 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3841 add_to_config_log('auth', $oldauthconfig, $newconfig, 'core');
3842 set_config('auth', $newconfig);
3846 return (array_merge($default, $auths));
3850 * Returns true if an internal authentication method is being used.
3851 * if method not specified then, global default is assumed
3853 * @param string $auth Form of authentication required
3854 * @return bool
3856 function is_internal_auth($auth) {
3857 // Throws error if bad $auth.
3858 $authplugin = get_auth_plugin($auth);
3859 return $authplugin->is_internal();
3863 * Returns true if the user is a 'restored' one.
3865 * Used in the login process to inform the user and allow him/her to reset the password
3867 * @param string $username username to be checked
3868 * @return bool
3870 function is_restored_user($username) {
3871 global $CFG, $DB;
3873 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3877 * Returns an array of user fields
3879 * @return array User field/column names
3881 function get_user_fieldnames() {
3882 global $DB;
3884 $fieldarray = $DB->get_columns('user');
3885 unset($fieldarray['id']);
3886 $fieldarray = array_keys($fieldarray);
3888 return $fieldarray;
3892 * Returns the string of the language for the new user.
3894 * @return string language for the new user
3896 function get_newuser_language() {
3897 global $CFG, $SESSION;
3898 return (!empty($CFG->autolangusercreation) && !empty($SESSION->lang)) ? $SESSION->lang : $CFG->lang;
3902 * Creates a bare-bones user record
3904 * @todo Outline auth types and provide code example
3906 * @param string $username New user's username to add to record
3907 * @param string $password New user's password to add to record
3908 * @param string $auth Form of authentication required
3909 * @return stdClass A complete user object
3911 function create_user_record($username, $password, $auth = 'manual') {
3912 global $CFG, $DB, $SESSION;
3913 require_once($CFG->dirroot.'/user/profile/lib.php');
3914 require_once($CFG->dirroot.'/user/lib.php');
3916 // Just in case check text case.
3917 $username = trim(core_text::strtolower($username));
3919 $authplugin = get_auth_plugin($auth);
3920 $customfields = $authplugin->get_custom_user_profile_fields();
3921 $newuser = new stdClass();
3922 if ($newinfo = $authplugin->get_userinfo($username)) {
3923 $newinfo = truncate_userinfo($newinfo);
3924 foreach ($newinfo as $key => $value) {
3925 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3926 $newuser->$key = $value;
3931 if (!empty($newuser->email)) {
3932 if (email_is_not_allowed($newuser->email)) {
3933 unset($newuser->email);
3937 $newuser->auth = $auth;
3938 $newuser->username = $username;
3940 // Fix for MDL-8480
3941 // user CFG lang for user if $newuser->lang is empty
3942 // or $user->lang is not an installed language.
3943 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3944 $newuser->lang = get_newuser_language();
3946 $newuser->confirmed = 1;
3947 $newuser->lastip = getremoteaddr();
3948 $newuser->timecreated = time();
3949 $newuser->timemodified = $newuser->timecreated;
3950 $newuser->mnethostid = $CFG->mnet_localhost_id;
3952 $newuser->id = user_create_user($newuser, false, false);
3954 // Save user profile data.
3955 profile_save_data($newuser);
3957 $user = get_complete_user_data('id', $newuser->id);
3958 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3959 set_user_preference('auth_forcepasswordchange', 1, $user);
3961 // Set the password.
3962 update_internal_user_password($user, $password);
3964 // Trigger event.
3965 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3967 return $user;
3971 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3973 * @param string $username user's username to update the record
3974 * @return stdClass A complete user object
3976 function update_user_record($username) {
3977 global $DB, $CFG;
3978 // Just in case check text case.
3979 $username = trim(core_text::strtolower($username));
3981 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3982 return update_user_record_by_id($oldinfo->id);
3986 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3988 * @param int $id user id
3989 * @return stdClass A complete user object
3991 function update_user_record_by_id($id) {
3992 global $DB, $CFG;
3993 require_once($CFG->dirroot."/user/profile/lib.php");
3994 require_once($CFG->dirroot.'/user/lib.php');
3996 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3997 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3999 $newuser = array();
4000 $userauth = get_auth_plugin($oldinfo->auth);
4002 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
4003 $newinfo = truncate_userinfo($newinfo);
4004 $customfields = $userauth->get_custom_user_profile_fields();
4006 foreach ($newinfo as $key => $value) {
4007 $iscustom = in_array($key, $customfields);
4008 if (!$iscustom) {
4009 $key = strtolower($key);
4011 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4012 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4013 // Unknown or must not be changed.
4014 continue;
4016 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
4017 continue;
4019 $confval = $userauth->config->{'field_updatelocal_' . $key};
4020 $lockval = $userauth->config->{'field_lock_' . $key};
4021 if ($confval === 'onlogin') {
4022 // MDL-4207 Don't overwrite modified user profile values with
4023 // empty LDAP values when 'unlocked if empty' is set. The purpose
4024 // of the setting 'unlocked if empty' is to allow the user to fill
4025 // in a value for the selected field _if LDAP is giving
4026 // nothing_ for this field. Thus it makes sense to let this value
4027 // stand in until LDAP is giving a value for this field.
4028 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4029 if ($iscustom || (in_array($key, $userauth->userfields) &&
4030 ((string)$oldinfo->$key !== (string)$value))) {
4031 $newuser[$key] = (string)$value;
4036 if ($newuser) {
4037 $newuser['id'] = $oldinfo->id;
4038 $newuser['timemodified'] = time();
4039 user_update_user((object) $newuser, false, false);
4041 // Save user profile data.
4042 profile_save_data((object) $newuser);
4044 // Trigger event.
4045 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4049 return get_complete_user_data('id', $oldinfo->id);
4053 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4055 * @param array $info Array of user properties to truncate if needed
4056 * @return array The now truncated information that was passed in
4058 function truncate_userinfo(array $info) {
4059 // Define the limits.
4060 $limit = array(
4061 'username' => 100,
4062 'idnumber' => 255,
4063 'firstname' => 100,
4064 'lastname' => 100,
4065 'email' => 100,
4066 'phone1' => 20,
4067 'phone2' => 20,
4068 'institution' => 255,
4069 'department' => 255,
4070 'address' => 255,
4071 'city' => 120,
4072 'country' => 2,
4075 // Apply where needed.
4076 foreach (array_keys($info) as $key) {
4077 if (!empty($limit[$key])) {
4078 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4082 return $info;
4086 * Marks user deleted in internal user database and notifies the auth plugin.
4087 * Also unenrols user from all roles and does other cleanup.
4089 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4091 * @param stdClass $user full user object before delete
4092 * @return boolean success
4093 * @throws coding_exception if invalid $user parameter detected
4095 function delete_user(stdClass $user) {
4096 global $CFG, $DB, $SESSION;
4097 require_once($CFG->libdir.'/grouplib.php');
4098 require_once($CFG->libdir.'/gradelib.php');
4099 require_once($CFG->dirroot.'/message/lib.php');
4100 require_once($CFG->dirroot.'/user/lib.php');
4102 // Make sure nobody sends bogus record type as parameter.
4103 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4104 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4107 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4108 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4109 debugging('Attempt to delete unknown user account.');
4110 return false;
4113 // There must be always exactly one guest record, originally the guest account was identified by username only,
4114 // now we use $CFG->siteguest for performance reasons.
4115 if ($user->username === 'guest' or isguestuser($user)) {
4116 debugging('Guest user account can not be deleted.');
4117 return false;
4120 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4121 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4122 if ($user->auth === 'manual' and is_siteadmin($user)) {
4123 debugging('Local administrator accounts can not be deleted.');
4124 return false;
4127 // Allow plugins to use this user object before we completely delete it.
4128 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4129 foreach ($pluginsfunction as $plugintype => $plugins) {
4130 foreach ($plugins as $pluginfunction) {
4131 $pluginfunction($user);
4136 // Keep user record before updating it, as we have to pass this to user_deleted event.
4137 $olduser = clone $user;
4139 // Keep a copy of user context, we need it for event.
4140 $usercontext = context_user::instance($user->id);
4142 // Delete all grades - backup is kept in grade_grades_history table.
4143 grade_user_delete($user->id);
4145 // TODO: remove from cohorts using standard API here.
4147 // Remove user tags.
4148 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4150 // Unconditionally unenrol from all courses.
4151 enrol_user_delete($user);
4153 // Unenrol from all roles in all contexts.
4154 // This might be slow but it is really needed - modules might do some extra cleanup!
4155 role_unassign_all(array('userid' => $user->id));
4157 // Notify the competency subsystem.
4158 \core_competency\api::hook_user_deleted($user->id);
4160 // Now do a brute force cleanup.
4162 // Delete all user events and subscription events.
4163 $DB->delete_records_select('event', 'userid = :userid AND subscriptionid IS NOT NULL', ['userid' => $user->id]);
4165 // Now, delete all calendar subscription from the user.
4166 $DB->delete_records('event_subscriptions', ['userid' => $user->id]);
4168 // Remove from all cohorts.
4169 $DB->delete_records('cohort_members', array('userid' => $user->id));
4171 // Remove from all groups.
4172 $DB->delete_records('groups_members', array('userid' => $user->id));
4174 // Brute force unenrol from all courses.
4175 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4177 // Purge user preferences.
4178 $DB->delete_records('user_preferences', array('userid' => $user->id));
4180 // Purge user extra profile info.
4181 $DB->delete_records('user_info_data', array('userid' => $user->id));
4183 // Purge log of previous password hashes.
4184 $DB->delete_records('user_password_history', array('userid' => $user->id));
4186 // Last course access not necessary either.
4187 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4188 // Remove all user tokens.
4189 $DB->delete_records('external_tokens', array('userid' => $user->id));
4191 // Unauthorise the user for all services.
4192 $DB->delete_records('external_services_users', array('userid' => $user->id));
4194 // Remove users private keys.
4195 $DB->delete_records('user_private_key', array('userid' => $user->id));
4197 // Remove users customised pages.
4198 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4200 // Remove user's oauth2 refresh tokens, if present.
4201 $DB->delete_records('oauth2_refresh_token', array('userid' => $user->id));
4203 // Delete user from $SESSION->bulk_users.
4204 if (isset($SESSION->bulk_users[$user->id])) {
4205 unset($SESSION->bulk_users[$user->id]);
4208 // Force logout - may fail if file based sessions used, sorry.
4209 \core\session\manager::kill_user_sessions($user->id);
4211 // Generate username from email address, or a fake email.
4212 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4214 $deltime = time();
4215 $deltimelength = core_text::strlen((string) $deltime);
4217 // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
4218 $delname = clean_param($delemail, PARAM_USERNAME);
4219 $delname = core_text::substr($delname, 0, 100 - ($deltimelength + 1)) . ".{$deltime}";
4221 // Workaround for bulk deletes of users with the same email address.
4222 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4223 $delname++;
4226 // Mark internal user record as "deleted".
4227 $updateuser = new stdClass();
4228 $updateuser->id = $user->id;
4229 $updateuser->deleted = 1;
4230 $updateuser->username = $delname; // Remember it just in case.
4231 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4232 $updateuser->idnumber = ''; // Clear this field to free it up.
4233 $updateuser->picture = 0;
4234 $updateuser->timemodified = $deltime;
4236 // Don't trigger update event, as user is being deleted.
4237 user_update_user($updateuser, false, false);
4239 // Delete all content associated with the user context, but not the context itself.
4240 $usercontext->delete_content();
4242 // Delete any search data.
4243 \core_search\manager::context_deleted($usercontext);
4245 // Any plugin that needs to cleanup should register this event.
4246 // Trigger event.
4247 $event = \core\event\user_deleted::create(
4248 array(
4249 'objectid' => $user->id,
4250 'relateduserid' => $user->id,
4251 'context' => $usercontext,
4252 'other' => array(
4253 'username' => $user->username,
4254 'email' => $user->email,
4255 'idnumber' => $user->idnumber,
4256 'picture' => $user->picture,
4257 'mnethostid' => $user->mnethostid
4261 $event->add_record_snapshot('user', $olduser);
4262 $event->trigger();
4264 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4265 // should know about this updated property persisted to the user's table.
4266 $user->timemodified = $updateuser->timemodified;
4268 // Notify auth plugin - do not block the delete even when plugin fails.
4269 $authplugin = get_auth_plugin($user->auth);
4270 $authplugin->user_delete($user);
4272 return true;
4276 * Retrieve the guest user object.
4278 * @return stdClass A {@link $USER} object
4280 function guest_user() {
4281 global $CFG, $DB;
4283 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4284 $newuser->confirmed = 1;
4285 $newuser->lang = get_newuser_language();
4286 $newuser->lastip = getremoteaddr();
4289 return $newuser;
4293 * Authenticates a user against the chosen authentication mechanism
4295 * Given a username and password, this function looks them
4296 * up using the currently selected authentication mechanism,
4297 * and if the authentication is successful, it returns a
4298 * valid $user object from the 'user' table.
4300 * Uses auth_ functions from the currently active auth module
4302 * After authenticate_user_login() returns success, you will need to
4303 * log that the user has logged in, and call complete_user_login() to set
4304 * the session up.
4306 * Note: this function works only with non-mnet accounts!
4308 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4309 * @param string $password User's password
4310 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4311 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4312 * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4313 * @return stdClass|false A {@link $USER} object or false if error
4315 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4316 global $CFG, $DB, $PAGE;
4317 require_once("$CFG->libdir/authlib.php");
4319 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4320 // we have found the user
4322 } else if (!empty($CFG->authloginviaemail)) {
4323 if ($email = clean_param($username, PARAM_EMAIL)) {
4324 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4325 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4326 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4327 if (count($users) === 1) {
4328 // Use email for login only if unique.
4329 $user = reset($users);
4330 $user = get_complete_user_data('id', $user->id);
4331 $username = $user->username;
4333 unset($users);
4337 // Make sure this request came from the login form.
4338 if (!\core\session\manager::validate_login_token($logintoken)) {
4339 $failurereason = AUTH_LOGIN_FAILED;
4341 // Trigger login failed event (specifying the ID of the found user, if available).
4342 \core\event\user_login_failed::create([
4343 'userid' => ($user->id ?? 0),
4344 'other' => [
4345 'username' => $username,
4346 'reason' => $failurereason,
4348 ])->trigger();
4350 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4351 return false;
4354 $authsenabled = get_enabled_auth_plugins();
4356 if ($user) {
4357 // Use manual if auth not set.
4358 $auth = empty($user->auth) ? 'manual' : $user->auth;
4360 if (in_array($user->auth, $authsenabled)) {
4361 $authplugin = get_auth_plugin($user->auth);
4362 $authplugin->pre_user_login_hook($user);
4365 if (!empty($user->suspended)) {
4366 $failurereason = AUTH_LOGIN_SUSPENDED;
4368 // Trigger login failed event.
4369 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4370 'other' => array('username' => $username, 'reason' => $failurereason)));
4371 $event->trigger();
4372 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4373 return false;
4375 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4376 // Legacy way to suspend user.
4377 $failurereason = AUTH_LOGIN_SUSPENDED;
4379 // Trigger login failed event.
4380 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4381 'other' => array('username' => $username, 'reason' => $failurereason)));
4382 $event->trigger();
4383 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4384 return false;
4386 $auths = array($auth);
4388 } else {
4389 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4390 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4391 $failurereason = AUTH_LOGIN_NOUSER;
4393 // Trigger login failed event.
4394 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4395 'reason' => $failurereason)));
4396 $event->trigger();
4397 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4398 return false;
4401 // User does not exist.
4402 $auths = $authsenabled;
4403 $user = new stdClass();
4404 $user->id = 0;
4407 if ($ignorelockout) {
4408 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4409 // or this function is called from a SSO script.
4410 } else if ($user->id) {
4411 // Verify login lockout after other ways that may prevent user login.
4412 if (login_is_lockedout($user)) {
4413 $failurereason = AUTH_LOGIN_LOCKOUT;
4415 // Trigger login failed event.
4416 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4417 'other' => array('username' => $username, 'reason' => $failurereason)));
4418 $event->trigger();
4420 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4421 return false;
4423 } else {
4424 // We can not lockout non-existing accounts.
4427 foreach ($auths as $auth) {
4428 $authplugin = get_auth_plugin($auth);
4430 // On auth fail fall through to the next plugin.
4431 if (!$authplugin->user_login($username, $password)) {
4432 continue;
4435 // Before performing login actions, check if user still passes password policy, if admin setting is enabled.
4436 if (!empty($CFG->passwordpolicycheckonlogin)) {
4437 $errmsg = '';
4438 $passed = check_password_policy($password, $errmsg, $user);
4439 if (!$passed) {
4440 // First trigger event for failure.
4441 $failedevent = \core\event\user_password_policy_failed::create_from_user($user);
4442 $failedevent->trigger();
4444 // If able to change password, set flag and move on.
4445 if ($authplugin->can_change_password()) {
4446 // Check if we are on internal change password page, or service is external, don't show notification.
4447 $internalchangeurl = new moodle_url('/login/change_password.php');
4448 if (!($PAGE->has_set_url() && $internalchangeurl->compare($PAGE->url)) && $authplugin->is_internal()) {
4449 \core\notification::error(get_string('passwordpolicynomatch', '', $errmsg));
4451 set_user_preference('auth_forcepasswordchange', 1, $user);
4452 } else if ($authplugin->can_reset_password()) {
4453 // Else force a reset if possible.
4454 \core\notification::error(get_string('forcepasswordresetnotice', '', $errmsg));
4455 redirect(new moodle_url('/login/forgot_password.php'));
4456 } else {
4457 $notifymsg = get_string('forcepasswordresetfailurenotice', '', $errmsg);
4458 // If support page is set, add link for help.
4459 if (!empty($CFG->supportpage)) {
4460 $link = \html_writer::link($CFG->supportpage, $CFG->supportpage);
4461 $link = \html_writer::tag('p', $link);
4462 $notifymsg .= $link;
4465 // If no change or reset is possible, add a notification for user.
4466 \core\notification::error($notifymsg);
4471 // Successful authentication.
4472 if ($user->id) {
4473 // User already exists in database.
4474 if (empty($user->auth)) {
4475 // For some reason auth isn't set yet.
4476 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4477 $user->auth = $auth;
4480 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4481 // the current hash algorithm while we have access to the user's password.
4482 update_internal_user_password($user, $password);
4484 if ($authplugin->is_synchronised_with_external()) {
4485 // Update user record from external DB.
4486 $user = update_user_record_by_id($user->id);
4488 } else {
4489 // The user is authenticated but user creation may be disabled.
4490 if (!empty($CFG->authpreventaccountcreation)) {
4491 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4493 // Trigger login failed event.
4494 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4495 'reason' => $failurereason)));
4496 $event->trigger();
4498 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4499 $_SERVER['HTTP_USER_AGENT']);
4500 return false;
4501 } else {
4502 $user = create_user_record($username, $password, $auth);
4506 $authplugin->sync_roles($user);
4508 foreach ($authsenabled as $hau) {
4509 $hauth = get_auth_plugin($hau);
4510 $hauth->user_authenticated_hook($user, $username, $password);
4513 if (empty($user->id)) {
4514 $failurereason = AUTH_LOGIN_NOUSER;
4515 // Trigger login failed event.
4516 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4517 'reason' => $failurereason)));
4518 $event->trigger();
4519 return false;
4522 if (!empty($user->suspended)) {
4523 // Just in case some auth plugin suspended account.
4524 $failurereason = AUTH_LOGIN_SUSPENDED;
4525 // Trigger login failed event.
4526 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4527 'other' => array('username' => $username, 'reason' => $failurereason)));
4528 $event->trigger();
4529 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4530 return false;
4533 login_attempt_valid($user);
4534 $failurereason = AUTH_LOGIN_OK;
4535 return $user;
4538 // Failed if all the plugins have failed.
4539 if (debugging('', DEBUG_ALL)) {
4540 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4543 if ($user->id) {
4544 login_attempt_failed($user);
4545 $failurereason = AUTH_LOGIN_FAILED;
4546 // Trigger login failed event.
4547 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4548 'other' => array('username' => $username, 'reason' => $failurereason)));
4549 $event->trigger();
4550 } else {
4551 $failurereason = AUTH_LOGIN_NOUSER;
4552 // Trigger login failed event.
4553 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4554 'reason' => $failurereason)));
4555 $event->trigger();
4558 return false;
4562 * Call to complete the user login process after authenticate_user_login()
4563 * has succeeded. It will setup the $USER variable and other required bits
4564 * and pieces.
4566 * NOTE:
4567 * - It will NOT log anything -- up to the caller to decide what to log.
4568 * - this function does not set any cookies any more!
4570 * @param stdClass $user
4571 * @param array $extrauserinfo
4572 * @return stdClass A {@link $USER} object - BC only, do not use
4574 function complete_user_login($user, array $extrauserinfo = []) {
4575 global $CFG, $DB, $USER, $SESSION;
4577 \core\session\manager::login_user($user);
4579 // Reload preferences from DB.
4580 unset($USER->preference);
4581 check_user_preferences_loaded($USER);
4583 // Update login times.
4584 update_user_login_times();
4586 // Extra session prefs init.
4587 set_login_session_preferences();
4589 // Trigger login event.
4590 $event = \core\event\user_loggedin::create(
4591 array(
4592 'userid' => $USER->id,
4593 'objectid' => $USER->id,
4594 'other' => [
4595 'username' => $USER->username,
4596 'extrauserinfo' => $extrauserinfo
4600 $event->trigger();
4602 // Check if the user is using a new browser or session (a new MoodleSession cookie is set in that case).
4603 // If the user is accessing from the same IP, ignore everything (most of the time will be a new session in the same browser).
4604 // Skip Web Service requests, CLI scripts, AJAX scripts, and request from the mobile app itself.
4605 $loginip = getremoteaddr();
4606 $isnewip = isset($SESSION->userpreviousip) && $SESSION->userpreviousip != $loginip;
4607 $isvalidenv = (!WS_SERVER && !CLI_SCRIPT && !NO_MOODLE_COOKIES) || PHPUNIT_TEST;
4609 if (!empty($SESSION->isnewsessioncookie) && $isnewip && $isvalidenv && !\core_useragent::is_moodle_app()) {
4611 $logintime = time();
4612 $ismoodleapp = false;
4613 $useragent = \core_useragent::get_user_agent_string();
4615 // Schedule adhoc task to sent a login notification to the user.
4616 $task = new \core\task\send_login_notifications();
4617 $task->set_userid($USER->id);
4618 $task->set_custom_data(compact('ismoodleapp', 'useragent', 'loginip', 'logintime'));
4619 $task->set_component('core');
4620 \core\task\manager::queue_adhoc_task($task);
4623 // Queue migrating the messaging data, if we need to.
4624 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4625 // Check if there are any legacy messages to migrate.
4626 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4627 \core_message\task\migrate_message_data::queue_task($USER->id);
4628 } else {
4629 set_user_preference('core_message_migrate_data', true, $USER->id);
4633 if (isguestuser()) {
4634 // No need to continue when user is THE guest.
4635 return $USER;
4638 if (CLI_SCRIPT) {
4639 // We can redirect to password change URL only in browser.
4640 return $USER;
4643 // Select password change url.
4644 $userauth = get_auth_plugin($USER->auth);
4646 // Check whether the user should be changing password.
4647 if (get_user_preferences('auth_forcepasswordchange', false)) {
4648 if ($userauth->can_change_password()) {
4649 if ($changeurl = $userauth->change_password_url()) {
4650 redirect($changeurl);
4651 } else {
4652 require_once($CFG->dirroot . '/login/lib.php');
4653 $SESSION->wantsurl = core_login_get_return_url();
4654 redirect($CFG->wwwroot.'/login/change_password.php');
4656 } else {
4657 throw new \moodle_exception('nopasswordchangeforced', 'auth');
4660 return $USER;
4664 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4666 * @param string $password String to check.
4667 * @return boolean True if the $password matches the format of an md5 sum.
4669 function password_is_legacy_hash($password) {
4670 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4674 * Compare password against hash stored in user object to determine if it is valid.
4676 * If necessary it also updates the stored hash to the current format.
4678 * @param stdClass $user (Password property may be updated).
4679 * @param string $password Plain text password.
4680 * @return bool True if password is valid.
4682 function validate_internal_user_password($user, $password) {
4683 global $CFG;
4685 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4686 // Internal password is not used at all, it can not validate.
4687 return false;
4690 // If hash isn't a legacy (md5) hash, validate using the library function.
4691 if (!password_is_legacy_hash($user->password)) {
4692 return password_verify($password, $user->password);
4695 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4696 // is valid we can then update it to the new algorithm.
4698 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4699 $validated = false;
4701 if ($user->password === md5($password.$sitesalt)
4702 or $user->password === md5($password)
4703 or $user->password === md5(addslashes($password).$sitesalt)
4704 or $user->password === md5(addslashes($password))) {
4705 // Note: we are intentionally using the addslashes() here because we
4706 // need to accept old password hashes of passwords with magic quotes.
4707 $validated = true;
4709 } else {
4710 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4711 $alt = 'passwordsaltalt'.$i;
4712 if (!empty($CFG->$alt)) {
4713 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4714 $validated = true;
4715 break;
4721 if ($validated) {
4722 // If the password matches the existing md5 hash, update to the
4723 // current hash algorithm while we have access to the user's password.
4724 update_internal_user_password($user, $password);
4727 return $validated;
4731 * Calculate hash for a plain text password.
4733 * @param string $password Plain text password to be hashed.
4734 * @param bool $fasthash If true, use a low cost factor when generating the hash
4735 * This is much faster to generate but makes the hash
4736 * less secure. It is used when lots of hashes need to
4737 * be generated quickly.
4738 * @return string The hashed password.
4740 * @throws moodle_exception If a problem occurs while generating the hash.
4742 function hash_internal_user_password($password, $fasthash = false) {
4743 global $CFG;
4745 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4746 $options = ($fasthash) ? array('cost' => 4) : array();
4748 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4750 if ($generatedhash === false || $generatedhash === null) {
4751 throw new moodle_exception('Failed to generate password hash.');
4754 return $generatedhash;
4758 * Update password hash in user object (if necessary).
4760 * The password is updated if:
4761 * 1. The password has changed (the hash of $user->password is different
4762 * to the hash of $password).
4763 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4764 * md5 algorithm).
4766 * Updating the password will modify the $user object and the database
4767 * record to use the current hashing algorithm.
4768 * It will remove Web Services user tokens too.
4770 * @param stdClass $user User object (password property may be updated).
4771 * @param string $password Plain text password.
4772 * @param bool $fasthash If true, use a low cost factor when generating the hash
4773 * This is much faster to generate but makes the hash
4774 * less secure. It is used when lots of hashes need to
4775 * be generated quickly.
4776 * @return bool Always returns true.
4778 function update_internal_user_password($user, $password, $fasthash = false) {
4779 global $CFG, $DB;
4781 // Figure out what the hashed password should be.
4782 if (!isset($user->auth)) {
4783 debugging('User record in update_internal_user_password() must include field auth',
4784 DEBUG_DEVELOPER);
4785 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4787 $authplugin = get_auth_plugin($user->auth);
4788 if ($authplugin->prevent_local_passwords()) {
4789 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4790 } else {
4791 $hashedpassword = hash_internal_user_password($password, $fasthash);
4794 $algorithmchanged = false;
4796 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4797 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4798 $passwordchanged = ($user->password !== $hashedpassword);
4800 } else if (isset($user->password)) {
4801 // If verification fails then it means the password has changed.
4802 $passwordchanged = !password_verify($password, $user->password);
4803 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4804 } else {
4805 // While creating new user, password in unset in $user object, to avoid
4806 // saving it with user_create()
4807 $passwordchanged = true;
4810 if ($passwordchanged || $algorithmchanged) {
4811 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4812 $user->password = $hashedpassword;
4814 // Trigger event.
4815 $user = $DB->get_record('user', array('id' => $user->id));
4816 \core\event\user_password_updated::create_from_user($user)->trigger();
4818 // Remove WS user tokens.
4819 if (!empty($CFG->passwordchangetokendeletion)) {
4820 require_once($CFG->dirroot.'/webservice/lib.php');
4821 webservice::delete_user_ws_tokens($user->id);
4825 return true;
4829 * Get a complete user record, which includes all the info in the user record.
4831 * Intended for setting as $USER session variable
4833 * @param string $field The user field to be checked for a given value.
4834 * @param string $value The value to match for $field.
4835 * @param int $mnethostid
4836 * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4837 * found. Otherwise, it will just return false.
4838 * @return mixed False, or A {@link $USER} object.
4840 function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4841 global $CFG, $DB;
4843 if (!$field || !$value) {
4844 return false;
4847 // Change the field to lowercase.
4848 $field = core_text::strtolower($field);
4850 // List of case insensitive fields.
4851 $caseinsensitivefields = ['email'];
4853 // Username input is forced to lowercase and should be case sensitive.
4854 if ($field == 'username') {
4855 $value = core_text::strtolower($value);
4858 // Build the WHERE clause for an SQL query.
4859 $params = array('fieldval' => $value);
4861 // Do a case-insensitive query, if necessary. These are generally very expensive. The performance can be improved on some DBs
4862 // such as MySQL by pre-filtering users with accent-insensitive subselect.
4863 if (in_array($field, $caseinsensitivefields)) {
4864 $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4865 $idsubselect = $DB->sql_equal($field, ':fieldval2', false, false);
4866 $params['fieldval2'] = $value;
4867 } else {
4868 $fieldselect = "$field = :fieldval";
4869 $idsubselect = '';
4871 $constraints = "$fieldselect AND deleted <> 1";
4873 // If we are loading user data based on anything other than id,
4874 // we must also restrict our search based on mnet host.
4875 if ($field != 'id') {
4876 if (empty($mnethostid)) {
4877 // If empty, we restrict to local users.
4878 $mnethostid = $CFG->mnet_localhost_id;
4881 if (!empty($mnethostid)) {
4882 $params['mnethostid'] = $mnethostid;
4883 $constraints .= " AND mnethostid = :mnethostid";
4886 if ($idsubselect) {
4887 $constraints .= " AND id IN (SELECT id FROM {user} WHERE {$idsubselect})";
4890 // Get all the basic user data.
4891 try {
4892 // Make sure that there's only a single record that matches our query.
4893 // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4894 // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4895 $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST);
4896 } catch (dml_exception $exception) {
4897 if ($throwexception) {
4898 throw $exception;
4899 } else {
4900 // Return false when no records or multiple records were found.
4901 return false;
4905 // Get various settings and preferences.
4907 // Preload preference cache.
4908 check_user_preferences_loaded($user);
4910 // Load course enrolment related stuff.
4911 $user->lastcourseaccess = array(); // During last session.
4912 $user->currentcourseaccess = array(); // During current session.
4913 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4914 foreach ($lastaccesses as $lastaccess) {
4915 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4919 // Add cohort theme.
4920 if (!empty($CFG->allowcohortthemes)) {
4921 require_once($CFG->dirroot . '/cohort/lib.php');
4922 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4923 $user->cohorttheme = $cohorttheme;
4927 // Add the custom profile fields to the user record.
4928 $user->profile = array();
4929 if (!isguestuser($user)) {
4930 require_once($CFG->dirroot.'/user/profile/lib.php');
4931 profile_load_custom_fields($user);
4934 // Rewrite some variables if necessary.
4935 if (!empty($user->description)) {
4936 // No need to cart all of it around.
4937 $user->description = true;
4939 if (isguestuser($user)) {
4940 // Guest language always same as site.
4941 $user->lang = get_newuser_language();
4942 // Name always in current language.
4943 $user->firstname = get_string('guestuser');
4944 $user->lastname = ' ';
4947 return $user;
4951 * Validate a password against the configured password policy
4953 * @param string $password the password to be checked against the password policy
4954 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4955 * @param stdClass $user the user object to perform password validation against. Defaults to null if not provided.
4957 * @return bool true if the password is valid according to the policy. false otherwise.
4959 function check_password_policy($password, &$errmsg, $user = null) {
4960 global $CFG;
4962 if (!empty($CFG->passwordpolicy)) {
4963 $errmsg = '';
4964 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4965 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4967 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4968 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4970 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4971 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4973 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4974 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4976 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4977 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4979 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4980 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4983 // Fire any additional password policy functions from plugins.
4984 // Plugin functions should output an error message string or empty string for success.
4985 $pluginsfunction = get_plugins_with_function('check_password_policy');
4986 foreach ($pluginsfunction as $plugintype => $plugins) {
4987 foreach ($plugins as $pluginfunction) {
4988 $pluginerr = $pluginfunction($password, $user);
4989 if ($pluginerr) {
4990 $errmsg .= '<div>'. $pluginerr .'</div>';
4996 if ($errmsg == '') {
4997 return true;
4998 } else {
4999 return false;
5005 * When logging in, this function is run to set certain preferences for the current SESSION.
5007 function set_login_session_preferences() {
5008 global $SESSION;
5010 $SESSION->justloggedin = true;
5012 unset($SESSION->lang);
5013 unset($SESSION->forcelang);
5014 unset($SESSION->load_navigation_admin);
5019 * Delete a course, including all related data from the database, and any associated files.
5021 * @param mixed $courseorid The id of the course or course object to delete.
5022 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5023 * @return bool true if all the removals succeeded. false if there were any failures. If this
5024 * method returns false, some of the removals will probably have succeeded, and others
5025 * failed, but you have no way of knowing which.
5027 function delete_course($courseorid, $showfeedback = true) {
5028 global $DB;
5030 if (is_object($courseorid)) {
5031 $courseid = $courseorid->id;
5032 $course = $courseorid;
5033 } else {
5034 $courseid = $courseorid;
5035 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
5036 return false;
5039 $context = context_course::instance($courseid);
5041 // Frontpage course can not be deleted!!
5042 if ($courseid == SITEID) {
5043 return false;
5046 // Allow plugins to use this course before we completely delete it.
5047 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
5048 foreach ($pluginsfunction as $plugintype => $plugins) {
5049 foreach ($plugins as $pluginfunction) {
5050 $pluginfunction($course);
5055 // Tell the search manager we are about to delete a course. This prevents us sending updates
5056 // for each individual context being deleted.
5057 \core_search\manager::course_deleting_start($courseid);
5059 $handler = core_course\customfield\course_handler::create();
5060 $handler->delete_instance($courseid);
5062 // Make the course completely empty.
5063 remove_course_contents($courseid, $showfeedback);
5065 // Delete the course and related context instance.
5066 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
5068 $DB->delete_records("course", array("id" => $courseid));
5069 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5071 // Reset all course related caches here.
5072 core_courseformat\base::reset_course_cache($courseid);
5074 // Tell search that we have deleted the course so it can delete course data from the index.
5075 \core_search\manager::course_deleting_finish($courseid);
5077 // Trigger a course deleted event.
5078 $event = \core\event\course_deleted::create(array(
5079 'objectid' => $course->id,
5080 'context' => $context,
5081 'other' => array(
5082 'shortname' => $course->shortname,
5083 'fullname' => $course->fullname,
5084 'idnumber' => $course->idnumber
5087 $event->add_record_snapshot('course', $course);
5088 $event->trigger();
5090 return true;
5094 * Clear a course out completely, deleting all content but don't delete the course itself.
5096 * This function does not verify any permissions.
5098 * Please note this function also deletes all user enrolments,
5099 * enrolment instances and role assignments by default.
5101 * $options:
5102 * - 'keep_roles_and_enrolments' - false by default
5103 * - 'keep_groups_and_groupings' - false by default
5105 * @param int $courseid The id of the course that is being deleted
5106 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5107 * @param array $options extra options
5108 * @return bool true if all the removals succeeded. false if there were any failures. If this
5109 * method returns false, some of the removals will probably have succeeded, and others
5110 * failed, but you have no way of knowing which.
5112 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5113 global $CFG, $DB, $OUTPUT;
5115 require_once($CFG->libdir.'/badgeslib.php');
5116 require_once($CFG->libdir.'/completionlib.php');
5117 require_once($CFG->libdir.'/questionlib.php');
5118 require_once($CFG->libdir.'/gradelib.php');
5119 require_once($CFG->dirroot.'/group/lib.php');
5120 require_once($CFG->dirroot.'/comment/lib.php');
5121 require_once($CFG->dirroot.'/rating/lib.php');
5122 require_once($CFG->dirroot.'/notes/lib.php');
5124 // Handle course badges.
5125 badges_handle_course_deletion($courseid);
5127 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5128 $strdeleted = get_string('deleted').' - ';
5130 // Some crazy wishlist of stuff we should skip during purging of course content.
5131 $options = (array)$options;
5133 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5134 $coursecontext = context_course::instance($courseid);
5135 $fs = get_file_storage();
5137 // Delete course completion information, this has to be done before grades and enrols.
5138 $cc = new completion_info($course);
5139 $cc->clear_criteria();
5140 if ($showfeedback) {
5141 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5144 // Remove all data from gradebook - this needs to be done before course modules
5145 // because while deleting this information, the system may need to reference
5146 // the course modules that own the grades.
5147 remove_course_grades($courseid, $showfeedback);
5148 remove_grade_letters($coursecontext, $showfeedback);
5150 // Delete course blocks in any all child contexts,
5151 // they may depend on modules so delete them first.
5152 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5153 foreach ($childcontexts as $childcontext) {
5154 blocks_delete_all_for_context($childcontext->id);
5156 unset($childcontexts);
5157 blocks_delete_all_for_context($coursecontext->id);
5158 if ($showfeedback) {
5159 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5162 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $courseid]);
5163 rebuild_course_cache($courseid, true);
5165 // Get the list of all modules that are properly installed.
5166 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5168 // Delete every instance of every module,
5169 // this has to be done before deleting of course level stuff.
5170 $locations = core_component::get_plugin_list('mod');
5171 foreach ($locations as $modname => $moddir) {
5172 if ($modname === 'NEWMODULE') {
5173 continue;
5175 if (array_key_exists($modname, $allmodules)) {
5176 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5177 FROM {".$modname."} m
5178 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5179 WHERE m.course = :courseid";
5180 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5181 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5183 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5184 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5186 if ($instances) {
5187 foreach ($instances as $cm) {
5188 if ($cm->id) {
5189 // Delete activity context questions and question categories.
5190 question_delete_activity($cm);
5191 // Notify the competency subsystem.
5192 \core_competency\api::hook_course_module_deleted($cm);
5194 // Delete all tag instances associated with the instance of this module.
5195 core_tag_tag::delete_instances("mod_{$modname}", null, context_module::instance($cm->id)->id);
5196 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
5198 if (function_exists($moddelete)) {
5199 // This purges all module data in related tables, extra user prefs, settings, etc.
5200 $moddelete($cm->modinstance);
5201 } else {
5202 // NOTE: we should not allow installation of modules with missing delete support!
5203 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5204 $DB->delete_records($modname, array('id' => $cm->modinstance));
5207 if ($cm->id) {
5208 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5209 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5210 $DB->delete_records('course_modules_completion', ['coursemoduleid' => $cm->id]);
5211 $DB->delete_records('course_modules', array('id' => $cm->id));
5212 rebuild_course_cache($cm->course, true);
5216 if ($instances and $showfeedback) {
5217 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5219 } else {
5220 // Ooops, this module is not properly installed, force-delete it in the next block.
5224 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5226 // Delete completion defaults.
5227 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5229 // Remove all data from availability and completion tables that is associated
5230 // with course-modules belonging to this course. Note this is done even if the
5231 // features are not enabled now, in case they were enabled previously.
5232 $DB->delete_records_subquery('course_modules_completion', 'coursemoduleid', 'id',
5233 'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
5235 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5236 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5237 $allmodulesbyid = array_flip($allmodules);
5238 foreach ($cms as $cm) {
5239 if (array_key_exists($cm->module, $allmodulesbyid)) {
5240 try {
5241 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5242 } catch (Exception $e) {
5243 // Ignore weird or missing table problems.
5246 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5247 $DB->delete_records('course_modules', array('id' => $cm->id));
5248 rebuild_course_cache($cm->course, true);
5251 if ($showfeedback) {
5252 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5255 // Delete questions and question categories.
5256 question_delete_course($course);
5257 if ($showfeedback) {
5258 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5261 // Delete content bank contents.
5262 $cb = new \core_contentbank\contentbank();
5263 $cbdeleted = $cb->delete_contents($coursecontext);
5264 if ($showfeedback && $cbdeleted) {
5265 echo $OUTPUT->notification($strdeleted.get_string('contentbank', 'contentbank'), 'notifysuccess');
5268 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5269 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5270 foreach ($childcontexts as $childcontext) {
5271 $childcontext->delete();
5273 unset($childcontexts);
5275 // Remove roles and enrolments by default.
5276 if (empty($options['keep_roles_and_enrolments'])) {
5277 // This hack is used in restore when deleting contents of existing course.
5278 // During restore, we should remove only enrolment related data that the user performing the restore has a
5279 // permission to remove.
5280 $userid = $options['userid'] ?? null;
5281 enrol_course_delete($course, $userid);
5282 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5283 if ($showfeedback) {
5284 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5288 // Delete any groups, removing members and grouping/course links first.
5289 if (empty($options['keep_groups_and_groupings'])) {
5290 groups_delete_groupings($course->id, $showfeedback);
5291 groups_delete_groups($course->id, $showfeedback);
5294 // Filters be gone!
5295 filter_delete_all_for_context($coursecontext->id);
5297 // Notes, you shall not pass!
5298 note_delete_all($course->id);
5300 // Die comments!
5301 comment::delete_comments($coursecontext->id);
5303 // Ratings are history too.
5304 $delopt = new stdclass();
5305 $delopt->contextid = $coursecontext->id;
5306 $rm = new rating_manager();
5307 $rm->delete_ratings($delopt);
5309 // Delete course tags.
5310 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5312 // Give the course format the opportunity to remove its obscure data.
5313 $format = course_get_format($course);
5314 $format->delete_format_data();
5316 // Notify the competency subsystem.
5317 \core_competency\api::hook_course_deleted($course);
5319 // Delete calendar events.
5320 $DB->delete_records('event', array('courseid' => $course->id));
5321 $fs->delete_area_files($coursecontext->id, 'calendar');
5323 // Delete all related records in other core tables that may have a courseid
5324 // This array stores the tables that need to be cleared, as
5325 // table_name => column_name that contains the course id.
5326 $tablestoclear = array(
5327 'backup_courses' => 'courseid', // Scheduled backup stuff.
5328 'user_lastaccess' => 'courseid', // User access info.
5330 foreach ($tablestoclear as $table => $col) {
5331 $DB->delete_records($table, array($col => $course->id));
5334 // Delete all course backup files.
5335 $fs->delete_area_files($coursecontext->id, 'backup');
5337 // Cleanup course record - remove links to deleted stuff.
5338 $oldcourse = new stdClass();
5339 $oldcourse->id = $course->id;
5340 $oldcourse->summary = '';
5341 $oldcourse->cacherev = 0;
5342 $oldcourse->legacyfiles = 0;
5343 if (!empty($options['keep_groups_and_groupings'])) {
5344 $oldcourse->defaultgroupingid = 0;
5346 $DB->update_record('course', $oldcourse);
5348 // Delete course sections.
5349 $DB->delete_records('course_sections', array('course' => $course->id));
5351 // Delete legacy, section and any other course files.
5352 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5354 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5355 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5356 // Easy, do not delete the context itself...
5357 $coursecontext->delete_content();
5358 } else {
5359 // Hack alert!!!!
5360 // We can not drop all context stuff because it would bork enrolments and roles,
5361 // there might be also files used by enrol plugins...
5364 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5365 // also some non-standard unsupported plugins may try to store something there.
5366 fulldelete($CFG->dataroot.'/'.$course->id);
5368 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5369 course_modinfo::purge_course_cache($courseid);
5371 // Trigger a course content deleted event.
5372 $event = \core\event\course_content_deleted::create(array(
5373 'objectid' => $course->id,
5374 'context' => $coursecontext,
5375 'other' => array('shortname' => $course->shortname,
5376 'fullname' => $course->fullname,
5377 'options' => $options) // Passing this for legacy reasons.
5379 $event->add_record_snapshot('course', $course);
5380 $event->trigger();
5382 return true;
5386 * Change dates in module - used from course reset.
5388 * @param string $modname forum, assignment, etc
5389 * @param array $fields array of date fields from mod table
5390 * @param int $timeshift time difference
5391 * @param int $courseid
5392 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5393 * @return bool success
5395 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5396 global $CFG, $DB;
5397 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5399 $return = true;
5400 $params = array($timeshift, $courseid);
5401 foreach ($fields as $field) {
5402 $updatesql = "UPDATE {".$modname."}
5403 SET $field = $field + ?
5404 WHERE course=? AND $field<>0";
5405 if ($modid) {
5406 $updatesql .= ' AND id=?';
5407 $params[] = $modid;
5409 $return = $DB->execute($updatesql, $params) && $return;
5412 return $return;
5416 * This function will empty a course of user data.
5417 * It will retain the activities and the structure of the course.
5419 * @param object $data an object containing all the settings including courseid (without magic quotes)
5420 * @return array status array of array component, item, error
5422 function reset_course_userdata($data) {
5423 global $CFG, $DB;
5424 require_once($CFG->libdir.'/gradelib.php');
5425 require_once($CFG->libdir.'/completionlib.php');
5426 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5427 require_once($CFG->dirroot.'/group/lib.php');
5429 $data->courseid = $data->id;
5430 $context = context_course::instance($data->courseid);
5432 $eventparams = array(
5433 'context' => $context,
5434 'courseid' => $data->id,
5435 'other' => array(
5436 'reset_options' => (array) $data
5439 $event = \core\event\course_reset_started::create($eventparams);
5440 $event->trigger();
5442 // Calculate the time shift of dates.
5443 if (!empty($data->reset_start_date)) {
5444 // Time part of course startdate should be zero.
5445 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5446 } else {
5447 $data->timeshift = 0;
5450 // Result array: component, item, error.
5451 $status = array();
5453 // Start the resetting.
5454 $componentstr = get_string('general');
5456 // Move the course start time.
5457 if (!empty($data->reset_start_date) and $data->timeshift) {
5458 // Change course start data.
5459 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5460 // Update all course and group events - do not move activity events.
5461 $updatesql = "UPDATE {event}
5462 SET timestart = timestart + ?
5463 WHERE courseid=? AND instance=0";
5464 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5466 // Update any date activity restrictions.
5467 if ($CFG->enableavailability) {
5468 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5471 // Update completion expected dates.
5472 if ($CFG->enablecompletion) {
5473 $modinfo = get_fast_modinfo($data->courseid);
5474 $changed = false;
5475 foreach ($modinfo->get_cms() as $cm) {
5476 if ($cm->completion && !empty($cm->completionexpected)) {
5477 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5478 array('id' => $cm->id));
5479 $changed = true;
5483 // Clear course cache if changes made.
5484 if ($changed) {
5485 rebuild_course_cache($data->courseid, true);
5488 // Update course date completion criteria.
5489 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5492 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5495 if (!empty($data->reset_end_date)) {
5496 // If the user set a end date value respect it.
5497 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5498 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5499 // If there is a time shift apply it to the end date as well.
5500 $enddate = $data->reset_end_date_old + $data->timeshift;
5501 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5504 if (!empty($data->reset_events)) {
5505 $DB->delete_records('event', array('courseid' => $data->courseid));
5506 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5509 if (!empty($data->reset_notes)) {
5510 require_once($CFG->dirroot.'/notes/lib.php');
5511 note_delete_all($data->courseid);
5512 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5515 if (!empty($data->delete_blog_associations)) {
5516 require_once($CFG->dirroot.'/blog/lib.php');
5517 blog_remove_associations_for_course($data->courseid);
5518 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5521 if (!empty($data->reset_completion)) {
5522 // Delete course and activity completion information.
5523 $course = $DB->get_record('course', array('id' => $data->courseid));
5524 $cc = new completion_info($course);
5525 $cc->delete_all_completion_data();
5526 $status[] = array('component' => $componentstr,
5527 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5530 if (!empty($data->reset_competency_ratings)) {
5531 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5532 $status[] = array('component' => $componentstr,
5533 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5536 $componentstr = get_string('roles');
5538 if (!empty($data->reset_roles_overrides)) {
5539 $children = $context->get_child_contexts();
5540 foreach ($children as $child) {
5541 $child->delete_capabilities();
5543 $context->delete_capabilities();
5544 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5547 if (!empty($data->reset_roles_local)) {
5548 $children = $context->get_child_contexts();
5549 foreach ($children as $child) {
5550 role_unassign_all(array('contextid' => $child->id));
5552 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5555 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5556 $data->unenrolled = array();
5557 if (!empty($data->unenrol_users)) {
5558 $plugins = enrol_get_plugins(true);
5559 $instances = enrol_get_instances($data->courseid, true);
5560 foreach ($instances as $key => $instance) {
5561 if (!isset($plugins[$instance->enrol])) {
5562 unset($instances[$key]);
5563 continue;
5567 $usersroles = enrol_get_course_users_roles($data->courseid);
5568 foreach ($data->unenrol_users as $withroleid) {
5569 if ($withroleid) {
5570 $sql = "SELECT ue.*
5571 FROM {user_enrolments} ue
5572 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5573 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5574 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5575 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5577 } else {
5578 // Without any role assigned at course context.
5579 $sql = "SELECT ue.*
5580 FROM {user_enrolments} ue
5581 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5582 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5583 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5584 WHERE ra.id IS null";
5585 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5588 $rs = $DB->get_recordset_sql($sql, $params);
5589 foreach ($rs as $ue) {
5590 if (!isset($instances[$ue->enrolid])) {
5591 continue;
5593 $instance = $instances[$ue->enrolid];
5594 $plugin = $plugins[$instance->enrol];
5595 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5596 continue;
5599 if ($withroleid && count($usersroles[$ue->userid]) > 1) {
5600 // If we don't remove all roles and user has more than one role, just remove this role.
5601 role_unassign($withroleid, $ue->userid, $context->id);
5603 unset($usersroles[$ue->userid][$withroleid]);
5604 } else {
5605 // If we remove all roles or user has only one role, unenrol user from course.
5606 $plugin->unenrol_user($instance, $ue->userid);
5608 $data->unenrolled[$ue->userid] = $ue->userid;
5610 $rs->close();
5613 if (!empty($data->unenrolled)) {
5614 $status[] = array(
5615 'component' => $componentstr,
5616 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5617 'error' => false
5621 $componentstr = get_string('groups');
5623 // Remove all group members.
5624 if (!empty($data->reset_groups_members)) {
5625 groups_delete_group_members($data->courseid);
5626 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5629 // Remove all groups.
5630 if (!empty($data->reset_groups_remove)) {
5631 groups_delete_groups($data->courseid, false);
5632 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5635 // Remove all grouping members.
5636 if (!empty($data->reset_groupings_members)) {
5637 groups_delete_groupings_groups($data->courseid, false);
5638 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5641 // Remove all groupings.
5642 if (!empty($data->reset_groupings_remove)) {
5643 groups_delete_groupings($data->courseid, false);
5644 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5647 // Look in every instance of every module for data to delete.
5648 $unsupportedmods = array();
5649 if ($allmods = $DB->get_records('modules') ) {
5650 foreach ($allmods as $mod) {
5651 $modname = $mod->name;
5652 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5653 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5654 if (file_exists($modfile)) {
5655 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5656 continue; // Skip mods with no instances.
5658 include_once($modfile);
5659 if (function_exists($moddeleteuserdata)) {
5660 $modstatus = $moddeleteuserdata($data);
5661 if (is_array($modstatus)) {
5662 $status = array_merge($status, $modstatus);
5663 } else {
5664 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5666 } else {
5667 $unsupportedmods[] = $mod;
5669 } else {
5670 debugging('Missing lib.php in '.$modname.' module!');
5672 // Update calendar events for all modules.
5673 course_module_bulk_update_calendar_events($modname, $data->courseid);
5677 // Mention unsupported mods.
5678 if (!empty($unsupportedmods)) {
5679 foreach ($unsupportedmods as $mod) {
5680 $status[] = array(
5681 'component' => get_string('modulenameplural', $mod->name),
5682 'item' => '',
5683 'error' => get_string('resetnotimplemented')
5688 $componentstr = get_string('gradebook', 'grades');
5689 // Reset gradebook,.
5690 if (!empty($data->reset_gradebook_items)) {
5691 remove_course_grades($data->courseid, false);
5692 grade_grab_course_grades($data->courseid);
5693 grade_regrade_final_grades($data->courseid);
5694 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5696 } else if (!empty($data->reset_gradebook_grades)) {
5697 grade_course_reset($data->courseid);
5698 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5700 // Reset comments.
5701 if (!empty($data->reset_comments)) {
5702 require_once($CFG->dirroot.'/comment/lib.php');
5703 comment::reset_course_page_comments($context);
5706 $event = \core\event\course_reset_ended::create($eventparams);
5707 $event->trigger();
5709 return $status;
5713 * Generate an email processing address.
5715 * @param int $modid
5716 * @param string $modargs
5717 * @return string Returns email processing address
5719 function generate_email_processing_address($modid, $modargs) {
5720 global $CFG;
5722 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5723 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5729 * @todo Finish documenting this function
5731 * @param string $modargs
5732 * @param string $body Currently unused
5734 function moodle_process_email($modargs, $body) {
5735 global $DB;
5737 // The first char should be an unencoded letter. We'll take this as an action.
5738 switch ($modargs[0]) {
5739 case 'B': { // Bounce.
5740 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5741 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5742 // Check the half md5 of their email.
5743 $md5check = substr(md5($user->email), 0, 16);
5744 if ($md5check == substr($modargs, -16)) {
5745 set_bounce_count($user);
5747 // Else maybe they've already changed it?
5750 break;
5751 // Maybe more later?
5755 // CORRESPONDENCE.
5758 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5760 * @param string $action 'get', 'buffer', 'close' or 'flush'
5761 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5763 function get_mailer($action='get') {
5764 global $CFG;
5766 /** @var moodle_phpmailer $mailer */
5767 static $mailer = null;
5768 static $counter = 0;
5770 if (!isset($CFG->smtpmaxbulk)) {
5771 $CFG->smtpmaxbulk = 1;
5774 if ($action == 'get') {
5775 $prevkeepalive = false;
5777 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5778 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5779 $counter++;
5780 // Reset the mailer.
5781 $mailer->Priority = 3;
5782 $mailer->CharSet = 'UTF-8'; // Our default.
5783 $mailer->ContentType = "text/plain";
5784 $mailer->Encoding = "8bit";
5785 $mailer->From = "root@localhost";
5786 $mailer->FromName = "Root User";
5787 $mailer->Sender = "";
5788 $mailer->Subject = "";
5789 $mailer->Body = "";
5790 $mailer->AltBody = "";
5791 $mailer->ConfirmReadingTo = "";
5793 $mailer->clearAllRecipients();
5794 $mailer->clearReplyTos();
5795 $mailer->clearAttachments();
5796 $mailer->clearCustomHeaders();
5797 return $mailer;
5800 $prevkeepalive = $mailer->SMTPKeepAlive;
5801 get_mailer('flush');
5804 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5805 $mailer = new moodle_phpmailer();
5807 $counter = 1;
5809 if ($CFG->smtphosts == 'qmail') {
5810 // Use Qmail system.
5811 $mailer->isQmail();
5813 } else if (empty($CFG->smtphosts)) {
5814 // Use PHP mail() = sendmail.
5815 $mailer->isMail();
5817 } else {
5818 // Use SMTP directly.
5819 $mailer->isSMTP();
5820 if (!empty($CFG->debugsmtp) && (!empty($CFG->debugdeveloper))) {
5821 $mailer->SMTPDebug = 3;
5823 // Specify main and backup servers.
5824 $mailer->Host = $CFG->smtphosts;
5825 // Specify secure connection protocol.
5826 $mailer->SMTPSecure = $CFG->smtpsecure;
5827 // Use previous keepalive.
5828 $mailer->SMTPKeepAlive = $prevkeepalive;
5830 if ($CFG->smtpuser) {
5831 // Use SMTP authentication.
5832 $mailer->SMTPAuth = true;
5833 $mailer->Username = $CFG->smtpuser;
5834 $mailer->Password = $CFG->smtppass;
5838 return $mailer;
5841 $nothing = null;
5843 // Keep smtp session open after sending.
5844 if ($action == 'buffer') {
5845 if (!empty($CFG->smtpmaxbulk)) {
5846 get_mailer('flush');
5847 $m = get_mailer();
5848 if ($m->Mailer == 'smtp') {
5849 $m->SMTPKeepAlive = true;
5852 return $nothing;
5855 // Close smtp session, but continue buffering.
5856 if ($action == 'flush') {
5857 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5858 if (!empty($mailer->SMTPDebug)) {
5859 echo '<pre>'."\n";
5861 $mailer->SmtpClose();
5862 if (!empty($mailer->SMTPDebug)) {
5863 echo '</pre>';
5866 return $nothing;
5869 // Close smtp session, do not buffer anymore.
5870 if ($action == 'close') {
5871 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5872 get_mailer('flush');
5873 $mailer->SMTPKeepAlive = false;
5875 $mailer = null; // Better force new instance.
5876 return $nothing;
5881 * A helper function to test for email diversion
5883 * @param string $email
5884 * @return bool Returns true if the email should be diverted
5886 function email_should_be_diverted($email) {
5887 global $CFG;
5889 if (empty($CFG->divertallemailsto)) {
5890 return false;
5893 if (empty($CFG->divertallemailsexcept)) {
5894 return true;
5897 $patterns = array_map('trim', preg_split("/[\s,]+/", $CFG->divertallemailsexcept, -1, PREG_SPLIT_NO_EMPTY));
5898 foreach ($patterns as $pattern) {
5899 if (preg_match("/$pattern/", $email)) {
5900 return false;
5904 return true;
5908 * Generate a unique email Message-ID using the moodle domain and install path
5910 * @param string $localpart An optional unique message id prefix.
5911 * @return string The formatted ID ready for appending to the email headers.
5913 function generate_email_messageid($localpart = null) {
5914 global $CFG;
5916 $urlinfo = parse_url($CFG->wwwroot);
5917 $base = '@' . $urlinfo['host'];
5919 // If multiple moodles are on the same domain we want to tell them
5920 // apart so we add the install path to the local part. This means
5921 // that the id local part should never contain a / character so
5922 // we can correctly parse the id to reassemble the wwwroot.
5923 if (isset($urlinfo['path'])) {
5924 $base = $urlinfo['path'] . $base;
5927 if (empty($localpart)) {
5928 $localpart = uniqid('', true);
5931 // Because we may have an option /installpath suffix to the local part
5932 // of the id we need to escape any / chars which are in the $localpart.
5933 $localpart = str_replace('/', '%2F', $localpart);
5935 return '<' . $localpart . $base . '>';
5939 * Send an email to a specified user
5941 * @param stdClass $user A {@link $USER} object
5942 * @param stdClass $from A {@link $USER} object
5943 * @param string $subject plain text subject line of the email
5944 * @param string $messagetext plain text version of the message
5945 * @param string $messagehtml complete html version of the message (optional)
5946 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in one of
5947 * the following directories: $CFG->cachedir, $CFG->dataroot, $CFG->dirroot, $CFG->localcachedir, $CFG->tempdir
5948 * @param string $attachname the name of the file (extension indicates MIME)
5949 * @param bool $usetrueaddress determines whether $from email address should
5950 * be sent out. Will be overruled by user profile setting for maildisplay
5951 * @param string $replyto Email address to reply to
5952 * @param string $replytoname Name of reply to recipient
5953 * @param int $wordwrapwidth custom word wrap width, default 79
5954 * @return bool Returns true if mail was sent OK and false if there was an error.
5956 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5957 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5959 global $CFG, $PAGE, $SITE;
5961 if (empty($user) or empty($user->id)) {
5962 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5963 return false;
5966 if (empty($user->email)) {
5967 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5968 return false;
5971 if (!empty($user->deleted)) {
5972 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5973 return false;
5976 if (defined('BEHAT_SITE_RUNNING')) {
5977 // Fake email sending in behat.
5978 return true;
5981 if (!empty($CFG->noemailever)) {
5982 // Hidden setting for development sites, set in config.php if needed.
5983 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5984 return true;
5987 if (email_should_be_diverted($user->email)) {
5988 $subject = "[DIVERTED {$user->email}] $subject";
5989 $user = clone($user);
5990 $user->email = $CFG->divertallemailsto;
5993 // Skip mail to suspended users.
5994 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5995 return true;
5998 if (!validate_email($user->email)) {
5999 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
6000 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
6001 return false;
6004 if (over_bounce_threshold($user)) {
6005 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
6006 return false;
6009 // TLD .invalid is specifically reserved for invalid domain names.
6010 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
6011 if (substr($user->email, -8) == '.invalid') {
6012 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
6013 return true; // This is not an error.
6016 // If the user is a remote mnet user, parse the email text for URL to the
6017 // wwwroot and modify the url to direct the user's browser to login at their
6018 // home site (identity provider - idp) before hitting the link itself.
6019 if (is_mnet_remote_user($user)) {
6020 require_once($CFG->dirroot.'/mnet/lib.php');
6022 $jumpurl = mnet_get_idp_jump_url($user);
6023 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
6025 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
6026 $callback,
6027 $messagetext);
6028 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
6029 $callback,
6030 $messagehtml);
6032 $mail = get_mailer();
6034 if (!empty($mail->SMTPDebug)) {
6035 echo '<pre>' . "\n";
6038 $temprecipients = array();
6039 $tempreplyto = array();
6041 // Make sure that we fall back onto some reasonable no-reply address.
6042 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
6043 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
6045 if (!validate_email($noreplyaddress)) {
6046 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
6047 $noreplyaddress = $noreplyaddressdefault;
6050 // Make up an email address for handling bounces.
6051 if (!empty($CFG->handlebounces)) {
6052 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
6053 $mail->Sender = generate_email_processing_address(0, $modargs);
6054 } else {
6055 $mail->Sender = $noreplyaddress;
6058 // Make sure that the explicit replyto is valid, fall back to the implicit one.
6059 if (!empty($replyto) && !validate_email($replyto)) {
6060 debugging('email_to_user: Invalid replyto-email '.s($replyto));
6061 $replyto = $noreplyaddress;
6064 if (is_string($from)) { // So we can pass whatever we want if there is need.
6065 $mail->From = $noreplyaddress;
6066 $mail->FromName = $from;
6067 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
6068 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6069 // in a course with the sender.
6070 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
6071 if (!validate_email($from->email)) {
6072 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
6073 // Better not to use $noreplyaddress in this case.
6074 return false;
6076 $mail->From = $from->email;
6077 $fromdetails = new stdClass();
6078 $fromdetails->name = fullname($from);
6079 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6080 $fromdetails->siteshortname = format_string($SITE->shortname);
6081 $fromstring = $fromdetails->name;
6082 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
6083 $fromstring = get_string('emailvia', 'core', $fromdetails);
6085 $mail->FromName = $fromstring;
6086 if (empty($replyto)) {
6087 $tempreplyto[] = array($from->email, fullname($from));
6089 } else {
6090 $mail->From = $noreplyaddress;
6091 $fromdetails = new stdClass();
6092 $fromdetails->name = fullname($from);
6093 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6094 $fromdetails->siteshortname = format_string($SITE->shortname);
6095 $fromstring = $fromdetails->name;
6096 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
6097 $fromstring = get_string('emailvia', 'core', $fromdetails);
6099 $mail->FromName = $fromstring;
6100 if (empty($replyto)) {
6101 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
6105 if (!empty($replyto)) {
6106 $tempreplyto[] = array($replyto, $replytoname);
6109 $temprecipients[] = array($user->email, fullname($user));
6111 // Set word wrap.
6112 $mail->WordWrap = $wordwrapwidth;
6114 if (!empty($from->customheaders)) {
6115 // Add custom headers.
6116 if (is_array($from->customheaders)) {
6117 foreach ($from->customheaders as $customheader) {
6118 $mail->addCustomHeader($customheader);
6120 } else {
6121 $mail->addCustomHeader($from->customheaders);
6125 // If the X-PHP-Originating-Script email header is on then also add an additional
6126 // header with details of where exactly in moodle the email was triggered from,
6127 // either a call to message_send() or to email_to_user().
6128 if (ini_get('mail.add_x_header')) {
6130 $stack = debug_backtrace(false);
6131 $origin = $stack[0];
6133 foreach ($stack as $depth => $call) {
6134 if ($call['function'] == 'message_send') {
6135 $origin = $call;
6139 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
6140 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
6141 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
6144 if (!empty($CFG->emailheaders)) {
6145 $headers = array_map('trim', explode("\n", $CFG->emailheaders));
6146 foreach ($headers as $header) {
6147 if (!empty($header)) {
6148 $mail->addCustomHeader($header);
6153 if (!empty($from->priority)) {
6154 $mail->Priority = $from->priority;
6157 $renderer = $PAGE->get_renderer('core');
6158 $context = array(
6159 'sitefullname' => $SITE->fullname,
6160 'siteshortname' => $SITE->shortname,
6161 'sitewwwroot' => $CFG->wwwroot,
6162 'subject' => $subject,
6163 'prefix' => $CFG->emailsubjectprefix,
6164 'to' => $user->email,
6165 'toname' => fullname($user),
6166 'from' => $mail->From,
6167 'fromname' => $mail->FromName,
6169 if (!empty($tempreplyto[0])) {
6170 $context['replyto'] = $tempreplyto[0][0];
6171 $context['replytoname'] = $tempreplyto[0][1];
6173 if ($user->id > 0) {
6174 $context['touserid'] = $user->id;
6175 $context['tousername'] = $user->username;
6178 if (!empty($user->mailformat) && $user->mailformat == 1) {
6179 // Only process html templates if the user preferences allow html email.
6181 if (!$messagehtml) {
6182 // If no html has been given, BUT there is an html wrapping template then
6183 // auto convert the text to html and then wrap it.
6184 $messagehtml = trim(text_to_html($messagetext));
6186 $context['body'] = $messagehtml;
6187 $messagehtml = $renderer->render_from_template('core/email_html', $context);
6190 $context['body'] = html_to_text(nl2br($messagetext));
6191 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
6192 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
6193 $messagetext = $renderer->render_from_template('core/email_text', $context);
6195 // Autogenerate a MessageID if it's missing.
6196 if (empty($mail->MessageID)) {
6197 $mail->MessageID = generate_email_messageid();
6200 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6201 // Don't ever send HTML to users who don't want it.
6202 $mail->isHTML(true);
6203 $mail->Encoding = 'quoted-printable';
6204 $mail->Body = $messagehtml;
6205 $mail->AltBody = "\n$messagetext\n";
6206 } else {
6207 $mail->IsHTML(false);
6208 $mail->Body = "\n$messagetext\n";
6211 if ($attachment && $attachname) {
6212 if (preg_match( "~\\.\\.~" , $attachment )) {
6213 // Security check for ".." in dir path.
6214 $supportuser = core_user::get_support_user();
6215 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6216 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6217 } else {
6218 require_once($CFG->libdir.'/filelib.php');
6219 $mimetype = mimeinfo('type', $attachname);
6221 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6222 // The absolute (real) path is also fetched to ensure that comparisons to allowed paths are compared equally.
6223 $attachpath = str_replace('\\', '/', realpath($attachment));
6225 // Build an array of all filepaths from which attachments can be added (normalised slashes, absolute/real path).
6226 $allowedpaths = array_map(function(string $path): string {
6227 return str_replace('\\', '/', realpath($path));
6228 }, [
6229 $CFG->cachedir,
6230 $CFG->dataroot,
6231 $CFG->dirroot,
6232 $CFG->localcachedir,
6233 $CFG->tempdir,
6234 $CFG->localrequestdir,
6237 // Set addpath to true.
6238 $addpath = true;
6240 // Check if attachment includes one of the allowed paths.
6241 foreach (array_filter($allowedpaths) as $allowedpath) {
6242 // Set addpath to false if the attachment includes one of the allowed paths.
6243 if (strpos($attachpath, $allowedpath) === 0) {
6244 $addpath = false;
6245 break;
6249 // If the attachment is a full path to a file in the multiple allowed paths, use it as is,
6250 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6251 if ($addpath == true) {
6252 $attachment = $CFG->dataroot . '/' . $attachment;
6255 $mail->addAttachment($attachment, $attachname, 'base64', $mimetype);
6259 // Check if the email should be sent in an other charset then the default UTF-8.
6260 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6262 // Use the defined site mail charset or eventually the one preferred by the recipient.
6263 $charset = $CFG->sitemailcharset;
6264 if (!empty($CFG->allowusermailcharset)) {
6265 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6266 $charset = $useremailcharset;
6270 // Convert all the necessary strings if the charset is supported.
6271 $charsets = get_list_of_charsets();
6272 unset($charsets['UTF-8']);
6273 if (in_array($charset, $charsets)) {
6274 $mail->CharSet = $charset;
6275 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6276 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6277 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6278 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6280 foreach ($temprecipients as $key => $values) {
6281 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6283 foreach ($tempreplyto as $key => $values) {
6284 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6289 foreach ($temprecipients as $values) {
6290 $mail->addAddress($values[0], $values[1]);
6292 foreach ($tempreplyto as $values) {
6293 $mail->addReplyTo($values[0], $values[1]);
6296 if (!empty($CFG->emaildkimselector)) {
6297 $domain = substr(strrchr($mail->From, "@"), 1);
6298 $pempath = "{$CFG->dataroot}/dkim/{$domain}/{$CFG->emaildkimselector}.private";
6299 if (file_exists($pempath)) {
6300 $mail->DKIM_domain = $domain;
6301 $mail->DKIM_private = $pempath;
6302 $mail->DKIM_selector = $CFG->emaildkimselector;
6303 $mail->DKIM_identity = $mail->From;
6304 } else {
6305 debugging("Email DKIM selector chosen due to {$mail->From} but no certificate found at $pempath", DEBUG_DEVELOPER);
6309 if ($mail->send()) {
6310 set_send_count($user);
6311 if (!empty($mail->SMTPDebug)) {
6312 echo '</pre>';
6314 return true;
6315 } else {
6316 // Trigger event for failing to send email.
6317 $event = \core\event\email_failed::create(array(
6318 'context' => context_system::instance(),
6319 'userid' => $from->id,
6320 'relateduserid' => $user->id,
6321 'other' => array(
6322 'subject' => $subject,
6323 'message' => $messagetext,
6324 'errorinfo' => $mail->ErrorInfo
6327 $event->trigger();
6328 if (CLI_SCRIPT) {
6329 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6331 if (!empty($mail->SMTPDebug)) {
6332 echo '</pre>';
6334 return false;
6339 * Check to see if a user's real email address should be used for the "From" field.
6341 * @param object $from The user object for the user we are sending the email from.
6342 * @param object $user The user object that we are sending the email to.
6343 * @param array $unused No longer used.
6344 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6346 function can_send_from_real_email_address($from, $user, $unused = null) {
6347 global $CFG;
6348 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6349 return false;
6351 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6352 // Email is in the list of allowed domains for sending email,
6353 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6354 // in a course with the sender.
6355 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6356 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6357 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6358 && enrol_get_shared_courses($user, $from, false, true)))) {
6359 return true;
6361 return false;
6365 * Generate a signoff for emails based on support settings
6367 * @return string
6369 function generate_email_signoff() {
6370 global $CFG;
6372 $signoff = "\n";
6373 if (!empty($CFG->supportname)) {
6374 $signoff .= $CFG->supportname."\n";
6376 if (!empty($CFG->supportemail)) {
6377 $signoff .= $CFG->supportemail."\n";
6379 if (!empty($CFG->supportpage)) {
6380 $signoff .= $CFG->supportpage."\n";
6382 return $signoff;
6386 * Sets specified user's password and send the new password to the user via email.
6388 * @param stdClass $user A {@link $USER} object
6389 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6390 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6392 function setnew_password_and_mail($user, $fasthash = false) {
6393 global $CFG, $DB;
6395 // We try to send the mail in language the user understands,
6396 // unfortunately the filter_string() does not support alternative langs yet
6397 // so multilang will not work properly for site->fullname.
6398 $lang = empty($user->lang) ? get_newuser_language() : $user->lang;
6400 $site = get_site();
6402 $supportuser = core_user::get_support_user();
6404 $newpassword = generate_password();
6406 update_internal_user_password($user, $newpassword, $fasthash);
6408 $a = new stdClass();
6409 $a->firstname = fullname($user, true);
6410 $a->sitename = format_string($site->fullname);
6411 $a->username = $user->username;
6412 $a->newpassword = $newpassword;
6413 $a->link = $CFG->wwwroot .'/login/?lang='.$lang;
6414 $a->signoff = generate_email_signoff();
6416 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6418 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6420 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6421 return email_to_user($user, $supportuser, $subject, $message);
6426 * Resets specified user's password and send the new password to the user via email.
6428 * @param stdClass $user A {@link $USER} object
6429 * @return bool Returns true if mail was sent OK and false if there was an error.
6431 function reset_password_and_mail($user) {
6432 global $CFG;
6434 $site = get_site();
6435 $supportuser = core_user::get_support_user();
6437 $userauth = get_auth_plugin($user->auth);
6438 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6439 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6440 return false;
6443 $newpassword = generate_password();
6445 if (!$userauth->user_update_password($user, $newpassword)) {
6446 throw new \moodle_exception("cannotsetpassword");
6449 $a = new stdClass();
6450 $a->firstname = $user->firstname;
6451 $a->lastname = $user->lastname;
6452 $a->sitename = format_string($site->fullname);
6453 $a->username = $user->username;
6454 $a->newpassword = $newpassword;
6455 $a->link = $CFG->wwwroot .'/login/change_password.php';
6456 $a->signoff = generate_email_signoff();
6458 $message = get_string('newpasswordtext', '', $a);
6460 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6462 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6464 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6465 return email_to_user($user, $supportuser, $subject, $message);
6469 * Send email to specified user with confirmation text and activation link.
6471 * @param stdClass $user A {@link $USER} object
6472 * @param string $confirmationurl user confirmation URL
6473 * @return bool Returns true if mail was sent OK and false if there was an error.
6475 function send_confirmation_email($user, $confirmationurl = null) {
6476 global $CFG;
6478 $site = get_site();
6479 $supportuser = core_user::get_support_user();
6481 $data = new stdClass();
6482 $data->sitename = format_string($site->fullname);
6483 $data->admin = generate_email_signoff();
6485 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6487 if (empty($confirmationurl)) {
6488 $confirmationurl = '/login/confirm.php';
6491 $confirmationurl = new moodle_url($confirmationurl);
6492 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6493 $confirmationurl->remove_params('data');
6494 $confirmationpath = $confirmationurl->out(false);
6496 // We need to custom encode the username to include trailing dots in the link.
6497 // Because of this custom encoding we can't use moodle_url directly.
6498 // Determine if a query string is present in the confirmation url.
6499 $hasquerystring = strpos($confirmationpath, '?') !== false;
6500 // Perform normal url encoding of the username first.
6501 $username = urlencode($user->username);
6502 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6503 $username = str_replace('.', '%2E', $username);
6505 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6507 $message = get_string('emailconfirmation', '', $data);
6508 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6510 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6511 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6515 * Sends a password change confirmation email.
6517 * @param stdClass $user A {@link $USER} object
6518 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6519 * @return bool Returns true if mail was sent OK and false if there was an error.
6521 function send_password_change_confirmation_email($user, $resetrecord) {
6522 global $CFG;
6524 $site = get_site();
6525 $supportuser = core_user::get_support_user();
6526 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6528 $data = new stdClass();
6529 $data->firstname = $user->firstname;
6530 $data->lastname = $user->lastname;
6531 $data->username = $user->username;
6532 $data->sitename = format_string($site->fullname);
6533 $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6534 $data->admin = generate_email_signoff();
6535 $data->resetminutes = $pwresetmins;
6537 $message = get_string('emailresetconfirmation', '', $data);
6538 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6540 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6541 return email_to_user($user, $supportuser, $subject, $message);
6546 * Sends an email containing information on how to change your password.
6548 * @param stdClass $user A {@link $USER} object
6549 * @return bool Returns true if mail was sent OK and false if there was an error.
6551 function send_password_change_info($user) {
6552 $site = get_site();
6553 $supportuser = core_user::get_support_user();
6555 $data = new stdClass();
6556 $data->firstname = $user->firstname;
6557 $data->lastname = $user->lastname;
6558 $data->username = $user->username;
6559 $data->sitename = format_string($site->fullname);
6560 $data->admin = generate_email_signoff();
6562 if (!is_enabled_auth($user->auth)) {
6563 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6564 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6565 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6566 return email_to_user($user, $supportuser, $subject, $message);
6569 $userauth = get_auth_plugin($user->auth);
6570 ['subject' => $subject, 'message' => $message] = $userauth->get_password_change_info($user);
6572 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6573 return email_to_user($user, $supportuser, $subject, $message);
6577 * Check that an email is allowed. It returns an error message if there was a problem.
6579 * @param string $email Content of email
6580 * @return string|false
6582 function email_is_not_allowed($email) {
6583 global $CFG;
6585 // Comparing lowercase domains.
6586 $email = strtolower($email);
6587 if (!empty($CFG->allowemailaddresses)) {
6588 $allowed = explode(' ', strtolower($CFG->allowemailaddresses));
6589 foreach ($allowed as $allowedpattern) {
6590 $allowedpattern = trim($allowedpattern);
6591 if (!$allowedpattern) {
6592 continue;
6594 if (strpos($allowedpattern, '.') === 0) {
6595 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6596 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6597 return false;
6600 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6601 return false;
6604 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6606 } else if (!empty($CFG->denyemailaddresses)) {
6607 $denied = explode(' ', strtolower($CFG->denyemailaddresses));
6608 foreach ($denied as $deniedpattern) {
6609 $deniedpattern = trim($deniedpattern);
6610 if (!$deniedpattern) {
6611 continue;
6613 if (strpos($deniedpattern, '.') === 0) {
6614 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6615 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6616 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6619 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6620 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6625 return false;
6628 // FILE HANDLING.
6631 * Returns local file storage instance
6633 * @return file_storage
6635 function get_file_storage($reset = false) {
6636 global $CFG;
6638 static $fs = null;
6640 if ($reset) {
6641 $fs = null;
6642 return;
6645 if ($fs) {
6646 return $fs;
6649 require_once("$CFG->libdir/filelib.php");
6651 $fs = new file_storage();
6653 return $fs;
6657 * Returns local file storage instance
6659 * @return file_browser
6661 function get_file_browser() {
6662 global $CFG;
6664 static $fb = null;
6666 if ($fb) {
6667 return $fb;
6670 require_once("$CFG->libdir/filelib.php");
6672 $fb = new file_browser();
6674 return $fb;
6678 * Returns file packer
6680 * @param string $mimetype default application/zip
6681 * @return file_packer
6683 function get_file_packer($mimetype='application/zip') {
6684 global $CFG;
6686 static $fp = array();
6688 if (isset($fp[$mimetype])) {
6689 return $fp[$mimetype];
6692 switch ($mimetype) {
6693 case 'application/zip':
6694 case 'application/vnd.moodle.profiling':
6695 $classname = 'zip_packer';
6696 break;
6698 case 'application/x-gzip' :
6699 $classname = 'tgz_packer';
6700 break;
6702 case 'application/vnd.moodle.backup':
6703 $classname = 'mbz_packer';
6704 break;
6706 default:
6707 return false;
6710 require_once("$CFG->libdir/filestorage/$classname.php");
6711 $fp[$mimetype] = new $classname();
6713 return $fp[$mimetype];
6717 * Returns current name of file on disk if it exists.
6719 * @param string $newfile File to be verified
6720 * @return string Current name of file on disk if true
6722 function valid_uploaded_file($newfile) {
6723 if (empty($newfile)) {
6724 return '';
6726 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6727 return $newfile['tmp_name'];
6728 } else {
6729 return '';
6734 * Returns the maximum size for uploading files.
6736 * There are seven possible upload limits:
6737 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6738 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6739 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6740 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6741 * 5. by the Moodle admin in $CFG->maxbytes
6742 * 6. by the teacher in the current course $course->maxbytes
6743 * 7. by the teacher for the current module, eg $assignment->maxbytes
6745 * These last two are passed to this function as arguments (in bytes).
6746 * Anything defined as 0 is ignored.
6747 * The smallest of all the non-zero numbers is returned.
6749 * @todo Finish documenting this function
6751 * @param int $sitebytes Set maximum size
6752 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6753 * @param int $modulebytes Current module ->maxbytes (in bytes)
6754 * @param bool $unused This parameter has been deprecated and is not used any more.
6755 * @return int The maximum size for uploading files.
6757 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6759 if (! $filesize = ini_get('upload_max_filesize')) {
6760 $filesize = '5M';
6762 $minimumsize = get_real_size($filesize);
6764 if ($postsize = ini_get('post_max_size')) {
6765 $postsize = get_real_size($postsize);
6766 if ($postsize < $minimumsize) {
6767 $minimumsize = $postsize;
6771 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6772 $minimumsize = $sitebytes;
6775 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6776 $minimumsize = $coursebytes;
6779 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6780 $minimumsize = $modulebytes;
6783 return $minimumsize;
6787 * Returns the maximum size for uploading files for the current user
6789 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6791 * @param context $context The context in which to check user capabilities
6792 * @param int $sitebytes Set maximum size
6793 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6794 * @param int $modulebytes Current module ->maxbytes (in bytes)
6795 * @param stdClass $user The user
6796 * @param bool $unused This parameter has been deprecated and is not used any more.
6797 * @return int The maximum size for uploading files.
6799 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6800 $unused = false) {
6801 global $USER;
6803 if (empty($user)) {
6804 $user = $USER;
6807 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6808 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6811 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6815 * Returns an array of possible sizes in local language
6817 * Related to {@link get_max_upload_file_size()} - this function returns an
6818 * array of possible sizes in an array, translated to the
6819 * local language.
6821 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6823 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6824 * with the value set to 0. This option will be the first in the list.
6826 * @uses SORT_NUMERIC
6827 * @param int $sitebytes Set maximum size
6828 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6829 * @param int $modulebytes Current module ->maxbytes (in bytes)
6830 * @param int|array $custombytes custom upload size/s which will be added to list,
6831 * Only value/s smaller then maxsize will be added to list.
6832 * @return array
6834 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6835 global $CFG;
6837 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6838 return array();
6841 if ($sitebytes == 0) {
6842 // Will get the minimum of upload_max_filesize or post_max_size.
6843 $sitebytes = get_max_upload_file_size();
6846 $filesize = array();
6847 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6848 5242880, 10485760, 20971520, 52428800, 104857600,
6849 262144000, 524288000, 786432000, 1073741824,
6850 2147483648, 4294967296, 8589934592);
6852 // If custombytes is given and is valid then add it to the list.
6853 if (is_number($custombytes) and $custombytes > 0) {
6854 $custombytes = (int)$custombytes;
6855 if (!in_array($custombytes, $sizelist)) {
6856 $sizelist[] = $custombytes;
6858 } else if (is_array($custombytes)) {
6859 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6862 // Allow maxbytes to be selected if it falls outside the above boundaries.
6863 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6864 // Note: get_real_size() is used in order to prevent problems with invalid values.
6865 $sizelist[] = get_real_size($CFG->maxbytes);
6868 foreach ($sizelist as $sizebytes) {
6869 if ($sizebytes < $maxsize && $sizebytes > 0) {
6870 $filesize[(string)intval($sizebytes)] = display_size($sizebytes, 0);
6874 $limitlevel = '';
6875 $displaysize = '';
6876 if ($modulebytes &&
6877 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6878 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6879 $limitlevel = get_string('activity', 'core');
6880 $displaysize = display_size($modulebytes, 0);
6881 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6883 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6884 $limitlevel = get_string('course', 'core');
6885 $displaysize = display_size($coursebytes, 0);
6886 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6888 } else if ($sitebytes) {
6889 $limitlevel = get_string('site', 'core');
6890 $displaysize = display_size($sitebytes, 0);
6891 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6894 krsort($filesize, SORT_NUMERIC);
6895 if ($limitlevel) {
6896 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6897 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6900 return $filesize;
6904 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6906 * If excludefiles is defined, then that file/directory is ignored
6907 * If getdirs is true, then (sub)directories are included in the output
6908 * If getfiles is true, then files are included in the output
6909 * (at least one of these must be true!)
6911 * @todo Finish documenting this function. Add examples of $excludefile usage.
6913 * @param string $rootdir A given root directory to start from
6914 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6915 * @param bool $descend If true then subdirectories are recursed as well
6916 * @param bool $getdirs If true then (sub)directories are included in the output
6917 * @param bool $getfiles If true then files are included in the output
6918 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6920 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6922 $dirs = array();
6924 if (!$getdirs and !$getfiles) { // Nothing to show.
6925 return $dirs;
6928 if (!is_dir($rootdir)) { // Must be a directory.
6929 return $dirs;
6932 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6933 return $dirs;
6936 if (!is_array($excludefiles)) {
6937 $excludefiles = array($excludefiles);
6940 while (false !== ($file = readdir($dir))) {
6941 $firstchar = substr($file, 0, 1);
6942 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6943 continue;
6945 $fullfile = $rootdir .'/'. $file;
6946 if (filetype($fullfile) == 'dir') {
6947 if ($getdirs) {
6948 $dirs[] = $file;
6950 if ($descend) {
6951 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6952 foreach ($subdirs as $subdir) {
6953 $dirs[] = $file .'/'. $subdir;
6956 } else if ($getfiles) {
6957 $dirs[] = $file;
6960 closedir($dir);
6962 asort($dirs);
6964 return $dirs;
6969 * Adds up all the files in a directory and works out the size.
6971 * @param string $rootdir The directory to start from
6972 * @param string $excludefile A file to exclude when summing directory size
6973 * @return int The summed size of all files and subfiles within the root directory
6975 function get_directory_size($rootdir, $excludefile='') {
6976 global $CFG;
6978 // Do it this way if we can, it's much faster.
6979 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6980 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6981 $output = null;
6982 $return = null;
6983 exec($command, $output, $return);
6984 if (is_array($output)) {
6985 // We told it to return k.
6986 return get_real_size(intval($output[0]).'k');
6990 if (!is_dir($rootdir)) {
6991 // Must be a directory.
6992 return 0;
6995 if (!$dir = @opendir($rootdir)) {
6996 // Can't open it for some reason.
6997 return 0;
7000 $size = 0;
7002 while (false !== ($file = readdir($dir))) {
7003 $firstchar = substr($file, 0, 1);
7004 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
7005 continue;
7007 $fullfile = $rootdir .'/'. $file;
7008 if (filetype($fullfile) == 'dir') {
7009 $size += get_directory_size($fullfile, $excludefile);
7010 } else {
7011 $size += filesize($fullfile);
7014 closedir($dir);
7016 return $size;
7020 * Converts bytes into display form
7022 * @param int $size The size to convert to human readable form
7023 * @param int $decimalplaces If specified, uses fixed number of decimal places
7024 * @param string $fixedunits If specified, uses fixed units (e.g. 'KB')
7025 * @return string Display version of size
7027 function display_size($size, int $decimalplaces = 1, string $fixedunits = ''): string {
7029 static $units;
7031 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
7032 return get_string('unlimited');
7035 if (empty($units)) {
7036 $units[] = get_string('sizeb');
7037 $units[] = get_string('sizekb');
7038 $units[] = get_string('sizemb');
7039 $units[] = get_string('sizegb');
7040 $units[] = get_string('sizetb');
7041 $units[] = get_string('sizepb');
7044 switch ($fixedunits) {
7045 case 'PB' :
7046 $magnitude = 5;
7047 break;
7048 case 'TB' :
7049 $magnitude = 4;
7050 break;
7051 case 'GB' :
7052 $magnitude = 3;
7053 break;
7054 case 'MB' :
7055 $magnitude = 2;
7056 break;
7057 case 'KB' :
7058 $magnitude = 1;
7059 break;
7060 case 'B' :
7061 $magnitude = 0;
7062 break;
7063 case '':
7064 $magnitude = floor(log($size, 1024));
7065 $magnitude = max(0, min(5, $magnitude));
7066 break;
7067 default:
7068 throw new coding_exception('Unknown fixed units value: ' . $fixedunits);
7071 // Special case for magnitude 0 (bytes) - never use decimal places.
7072 $nbsp = "\xc2\xa0";
7073 if ($magnitude === 0) {
7074 return round($size) . $nbsp . $units[$magnitude];
7077 // Convert to specified units.
7078 $sizeinunit = $size / 1024 ** $magnitude;
7080 // Fixed decimal places.
7081 return sprintf('%.' . $decimalplaces . 'f', $sizeinunit) . $nbsp . $units[$magnitude];
7085 * Cleans a given filename by removing suspicious or troublesome characters
7087 * @see clean_param()
7088 * @param string $string file name
7089 * @return string cleaned file name
7091 function clean_filename($string) {
7092 return clean_param($string, PARAM_FILE);
7095 // STRING TRANSLATION.
7098 * Returns the code for the current language
7100 * @category string
7101 * @return string
7103 function current_language() {
7104 global $CFG, $PAGE, $SESSION, $USER;
7106 if (!empty($SESSION->forcelang)) {
7107 // Allows overriding course-forced language (useful for admins to check
7108 // issues in courses whose language they don't understand).
7109 // Also used by some code to temporarily get language-related information in a
7110 // specific language (see force_current_language()).
7111 $return = $SESSION->forcelang;
7113 } else if (!empty($PAGE->cm->lang)) {
7114 // Activity language, if set.
7115 $return = $PAGE->cm->lang;
7117 } else if (!empty($PAGE->course->id) && $PAGE->course->id != SITEID && !empty($PAGE->course->lang)) {
7118 // Course language can override all other settings for this page.
7119 $return = $PAGE->course->lang;
7121 } else if (!empty($SESSION->lang)) {
7122 // Session language can override other settings.
7123 $return = $SESSION->lang;
7125 } else if (!empty($USER->lang)) {
7126 $return = $USER->lang;
7128 } else if (isset($CFG->lang)) {
7129 $return = $CFG->lang;
7131 } else {
7132 $return = 'en';
7135 // Just in case this slipped in from somewhere by accident.
7136 $return = str_replace('_utf8', '', $return);
7138 return $return;
7142 * Returns parent language of current active language if defined
7144 * @category string
7145 * @param string $lang null means current language
7146 * @return string
7148 function get_parent_language($lang=null) {
7150 $parentlang = get_string_manager()->get_string('parentlanguage', 'langconfig', null, $lang);
7152 if ($parentlang === 'en') {
7153 $parentlang = '';
7156 return $parentlang;
7160 * Force the current language to get strings and dates localised in the given language.
7162 * After calling this function, all strings will be provided in the given language
7163 * until this function is called again, or equivalent code is run.
7165 * @param string $language
7166 * @return string previous $SESSION->forcelang value
7168 function force_current_language($language) {
7169 global $SESSION;
7170 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
7171 if ($language !== $sessionforcelang) {
7172 // Setting forcelang to null or an empty string disables its effect.
7173 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
7174 $SESSION->forcelang = $language;
7175 moodle_setlocale();
7178 return $sessionforcelang;
7182 * Returns current string_manager instance.
7184 * The param $forcereload is needed for CLI installer only where the string_manager instance
7185 * must be replaced during the install.php script life time.
7187 * @category string
7188 * @param bool $forcereload shall the singleton be released and new instance created instead?
7189 * @return core_string_manager
7191 function get_string_manager($forcereload=false) {
7192 global $CFG;
7194 static $singleton = null;
7196 if ($forcereload) {
7197 $singleton = null;
7199 if ($singleton === null) {
7200 if (empty($CFG->early_install_lang)) {
7202 $transaliases = array();
7203 if (empty($CFG->langlist)) {
7204 $translist = array();
7205 } else {
7206 $translist = explode(',', $CFG->langlist);
7207 $translist = array_map('trim', $translist);
7208 // Each language in the $CFG->langlist can has an "alias" that would substitute the default language name.
7209 foreach ($translist as $i => $value) {
7210 $parts = preg_split('/\s*\|\s*/', $value, 2);
7211 if (count($parts) == 2) {
7212 $transaliases[$parts[0]] = $parts[1];
7213 $translist[$i] = $parts[0];
7218 if (!empty($CFG->config_php_settings['customstringmanager'])) {
7219 $classname = $CFG->config_php_settings['customstringmanager'];
7221 if (class_exists($classname)) {
7222 $implements = class_implements($classname);
7224 if (isset($implements['core_string_manager'])) {
7225 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7226 return $singleton;
7228 } else {
7229 debugging('Unable to instantiate custom string manager: class '.$classname.
7230 ' does not implement the core_string_manager interface.');
7233 } else {
7234 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7238 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7240 } else {
7241 $singleton = new core_string_manager_install();
7245 return $singleton;
7249 * Returns a localized string.
7251 * Returns the translated string specified by $identifier as
7252 * for $module. Uses the same format files as STphp.
7253 * $a is an object, string or number that can be used
7254 * within translation strings
7256 * eg 'hello {$a->firstname} {$a->lastname}'
7257 * or 'hello {$a}'
7259 * If you would like to directly echo the localized string use
7260 * the function {@link print_string()}
7262 * Example usage of this function involves finding the string you would
7263 * like a local equivalent of and using its identifier and module information
7264 * to retrieve it.<br/>
7265 * If you open moodle/lang/en/moodle.php and look near line 278
7266 * you will find a string to prompt a user for their word for 'course'
7267 * <code>
7268 * $string['course'] = 'Course';
7269 * </code>
7270 * So if you want to display the string 'Course'
7271 * in any language that supports it on your site
7272 * you just need to use the identifier 'course'
7273 * <code>
7274 * $mystring = '<strong>'. get_string('course') .'</strong>';
7275 * or
7276 * </code>
7277 * If the string you want is in another file you'd take a slightly
7278 * different approach. Looking in moodle/lang/en/calendar.php you find
7279 * around line 75:
7280 * <code>
7281 * $string['typecourse'] = 'Course event';
7282 * </code>
7283 * If you want to display the string "Course event" in any language
7284 * supported you would use the identifier 'typecourse' and the module 'calendar'
7285 * (because it is in the file calendar.php):
7286 * <code>
7287 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7288 * </code>
7290 * As a last resort, should the identifier fail to map to a string
7291 * the returned string will be [[ $identifier ]]
7293 * In Moodle 2.3 there is a new argument to this function $lazyload.
7294 * Setting $lazyload to true causes get_string to return a lang_string object
7295 * rather than the string itself. The fetching of the string is then put off until
7296 * the string object is first used. The object can be used by calling it's out
7297 * method or by casting the object to a string, either directly e.g.
7298 * (string)$stringobject
7299 * or indirectly by using the string within another string or echoing it out e.g.
7300 * echo $stringobject
7301 * return "<p>{$stringobject}</p>";
7302 * It is worth noting that using $lazyload and attempting to use the string as an
7303 * array key will cause a fatal error as objects cannot be used as array keys.
7304 * But you should never do that anyway!
7305 * For more information {@link lang_string}
7307 * @category string
7308 * @param string $identifier The key identifier for the localized string
7309 * @param string $component The module where the key identifier is stored,
7310 * usually expressed as the filename in the language pack without the
7311 * .php on the end but can also be written as mod/forum or grade/export/xls.
7312 * If none is specified then moodle.php is used.
7313 * @param string|object|array $a An object, string or number that can be used
7314 * within translation strings
7315 * @param bool $lazyload If set to true a string object is returned instead of
7316 * the string itself. The string then isn't calculated until it is first used.
7317 * @return string The localized string.
7318 * @throws coding_exception
7320 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7321 global $CFG;
7323 // If the lazy load argument has been supplied return a lang_string object
7324 // instead.
7325 // We need to make sure it is true (and a bool) as you will see below there
7326 // used to be a forth argument at one point.
7327 if ($lazyload === true) {
7328 return new lang_string($identifier, $component, $a);
7331 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7332 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7335 // There is now a forth argument again, this time it is a boolean however so
7336 // we can still check for the old extralocations parameter.
7337 if (!is_bool($lazyload) && !empty($lazyload)) {
7338 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7341 if (strpos((string)$component, '/') !== false) {
7342 debugging('The module name you passed to get_string is the deprecated format ' .
7343 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7344 $componentpath = explode('/', $component);
7346 switch ($componentpath[0]) {
7347 case 'mod':
7348 $component = $componentpath[1];
7349 break;
7350 case 'blocks':
7351 case 'block':
7352 $component = 'block_'.$componentpath[1];
7353 break;
7354 case 'enrol':
7355 $component = 'enrol_'.$componentpath[1];
7356 break;
7357 case 'format':
7358 $component = 'format_'.$componentpath[1];
7359 break;
7360 case 'grade':
7361 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7362 break;
7366 $result = get_string_manager()->get_string($identifier, $component, $a);
7368 // Debugging feature lets you display string identifier and component.
7369 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7370 $result .= ' {' . $identifier . '/' . $component . '}';
7372 return $result;
7376 * Converts an array of strings to their localized value.
7378 * @param array $array An array of strings
7379 * @param string $component The language module that these strings can be found in.
7380 * @return stdClass translated strings.
7382 function get_strings($array, $component = '') {
7383 $string = new stdClass;
7384 foreach ($array as $item) {
7385 $string->$item = get_string($item, $component);
7387 return $string;
7391 * Prints out a translated string.
7393 * Prints out a translated string using the return value from the {@link get_string()} function.
7395 * Example usage of this function when the string is in the moodle.php file:<br/>
7396 * <code>
7397 * echo '<strong>';
7398 * print_string('course');
7399 * echo '</strong>';
7400 * </code>
7402 * Example usage of this function when the string is not in the moodle.php file:<br/>
7403 * <code>
7404 * echo '<h1>';
7405 * print_string('typecourse', 'calendar');
7406 * echo '</h1>';
7407 * </code>
7409 * @category string
7410 * @param string $identifier The key identifier for the localized string
7411 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7412 * @param string|object|array $a An object, string or number that can be used within translation strings
7414 function print_string($identifier, $component = '', $a = null) {
7415 echo get_string($identifier, $component, $a);
7419 * Returns a list of charset codes
7421 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7422 * (checking that such charset is supported by the texlib library!)
7424 * @return array And associative array with contents in the form of charset => charset
7426 function get_list_of_charsets() {
7428 $charsets = array(
7429 'EUC-JP' => 'EUC-JP',
7430 'ISO-2022-JP'=> 'ISO-2022-JP',
7431 'ISO-8859-1' => 'ISO-8859-1',
7432 'SHIFT-JIS' => 'SHIFT-JIS',
7433 'GB2312' => 'GB2312',
7434 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7435 'UTF-8' => 'UTF-8');
7437 asort($charsets);
7439 return $charsets;
7443 * Returns a list of valid and compatible themes
7445 * @return array
7447 function get_list_of_themes() {
7448 global $CFG;
7450 $themes = array();
7452 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7453 $themelist = explode(',', $CFG->themelist);
7454 } else {
7455 $themelist = array_keys(core_component::get_plugin_list("theme"));
7458 foreach ($themelist as $key => $themename) {
7459 $theme = theme_config::load($themename);
7460 $themes[$themename] = $theme;
7463 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7465 return $themes;
7469 * Factory function for emoticon_manager
7471 * @return emoticon_manager singleton
7473 function get_emoticon_manager() {
7474 static $singleton = null;
7476 if (is_null($singleton)) {
7477 $singleton = new emoticon_manager();
7480 return $singleton;
7484 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7486 * Whenever this manager mentiones 'emoticon object', the following data
7487 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7488 * altidentifier and altcomponent
7490 * @see admin_setting_emoticons
7492 * @copyright 2010 David Mudrak
7493 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7495 class emoticon_manager {
7498 * Returns the currently enabled emoticons
7500 * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
7501 * @return array of emoticon objects
7503 public function get_emoticons($selectable = false) {
7504 global $CFG;
7505 $notselectable = ['martin', 'egg'];
7507 if (empty($CFG->emoticons)) {
7508 return array();
7511 $emoticons = $this->decode_stored_config($CFG->emoticons);
7513 if (!is_array($emoticons)) {
7514 // Something is wrong with the format of stored setting.
7515 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7516 return array();
7518 if ($selectable) {
7519 foreach ($emoticons as $index => $emote) {
7520 if (in_array($emote->altidentifier, $notselectable)) {
7521 // Skip this one.
7522 unset($emoticons[$index]);
7527 return $emoticons;
7531 * Converts emoticon object into renderable pix_emoticon object
7533 * @param stdClass $emoticon emoticon object
7534 * @param array $attributes explicit HTML attributes to set
7535 * @return pix_emoticon
7537 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7538 $stringmanager = get_string_manager();
7539 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7540 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7541 } else {
7542 $alt = s($emoticon->text);
7544 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7548 * Encodes the array of emoticon objects into a string storable in config table
7550 * @see self::decode_stored_config()
7551 * @param array $emoticons array of emtocion objects
7552 * @return string
7554 public function encode_stored_config(array $emoticons) {
7555 return json_encode($emoticons);
7559 * Decodes the string into an array of emoticon objects
7561 * @see self::encode_stored_config()
7562 * @param string $encoded
7563 * @return string|null
7565 public function decode_stored_config($encoded) {
7566 $decoded = json_decode($encoded);
7567 if (!is_array($decoded)) {
7568 return null;
7570 return $decoded;
7574 * Returns default set of emoticons supported by Moodle
7576 * @return array of sdtClasses
7578 public function default_emoticons() {
7579 return array(
7580 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7581 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7582 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7583 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7584 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7585 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7586 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7587 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7588 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7589 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7590 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7591 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7592 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7593 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7594 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7595 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7596 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7597 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7598 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7599 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7600 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7601 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7602 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7603 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7604 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7605 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7606 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7607 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7608 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7609 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7614 * Helper method preparing the stdClass with the emoticon properties
7616 * @param string|array $text or array of strings
7617 * @param string $imagename to be used by {@link pix_emoticon}
7618 * @param string $altidentifier alternative string identifier, null for no alt
7619 * @param string $altcomponent where the alternative string is defined
7620 * @param string $imagecomponent to be used by {@link pix_emoticon}
7621 * @return stdClass
7623 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7624 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7625 return (object)array(
7626 'text' => $text,
7627 'imagename' => $imagename,
7628 'imagecomponent' => $imagecomponent,
7629 'altidentifier' => $altidentifier,
7630 'altcomponent' => $altcomponent,
7635 // ENCRYPTION.
7638 * rc4encrypt
7640 * @param string $data Data to encrypt.
7641 * @return string The now encrypted data.
7643 function rc4encrypt($data) {
7644 return endecrypt(get_site_identifier(), $data, '');
7648 * rc4decrypt
7650 * @param string $data Data to decrypt.
7651 * @return string The now decrypted data.
7653 function rc4decrypt($data) {
7654 return endecrypt(get_site_identifier(), $data, 'de');
7658 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7660 * @todo Finish documenting this function
7662 * @param string $pwd The password to use when encrypting or decrypting
7663 * @param string $data The data to be decrypted/encrypted
7664 * @param string $case Either 'de' for decrypt or '' for encrypt
7665 * @return string
7667 function endecrypt ($pwd, $data, $case) {
7669 if ($case == 'de') {
7670 $data = urldecode($data);
7673 $key[] = '';
7674 $box[] = '';
7675 $pwdlength = strlen($pwd);
7677 for ($i = 0; $i <= 255; $i++) {
7678 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7679 $box[$i] = $i;
7682 $x = 0;
7684 for ($i = 0; $i <= 255; $i++) {
7685 $x = ($x + $box[$i] + $key[$i]) % 256;
7686 $tempswap = $box[$i];
7687 $box[$i] = $box[$x];
7688 $box[$x] = $tempswap;
7691 $cipher = '';
7693 $a = 0;
7694 $j = 0;
7696 for ($i = 0; $i < strlen($data); $i++) {
7697 $a = ($a + 1) % 256;
7698 $j = ($j + $box[$a]) % 256;
7699 $temp = $box[$a];
7700 $box[$a] = $box[$j];
7701 $box[$j] = $temp;
7702 $k = $box[(($box[$a] + $box[$j]) % 256)];
7703 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7704 $cipher .= chr($cipherby);
7707 if ($case == 'de') {
7708 $cipher = urldecode(urlencode($cipher));
7709 } else {
7710 $cipher = urlencode($cipher);
7713 return $cipher;
7716 // ENVIRONMENT CHECKING.
7719 * This method validates a plug name. It is much faster than calling clean_param.
7721 * @param string $name a string that might be a plugin name.
7722 * @return bool if this string is a valid plugin name.
7724 function is_valid_plugin_name($name) {
7725 // This does not work for 'mod', bad luck, use any other type.
7726 return core_component::is_valid_plugin_name('tool', $name);
7730 * Get a list of all the plugins of a given type that define a certain API function
7731 * in a certain file. The plugin component names and function names are returned.
7733 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7734 * @param string $function the part of the name of the function after the
7735 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7736 * names like report_courselist_hook.
7737 * @param string $file the name of file within the plugin that defines the
7738 * function. Defaults to lib.php.
7739 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7740 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7742 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7743 global $CFG;
7745 // We don't include here as all plugin types files would be included.
7746 $plugins = get_plugins_with_function($function, $file, false);
7748 if (empty($plugins[$plugintype])) {
7749 return array();
7752 $allplugins = core_component::get_plugin_list($plugintype);
7754 // Reformat the array and include the files.
7755 $pluginfunctions = array();
7756 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7758 // Check that it has not been removed and the file is still available.
7759 if (!empty($allplugins[$pluginname])) {
7761 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7762 if (file_exists($filepath)) {
7763 include_once($filepath);
7765 // Now that the file is loaded, we must verify the function still exists.
7766 if (function_exists($functionname)) {
7767 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7768 } else {
7769 // Invalidate the cache for next run.
7770 \cache_helper::invalidate_by_definition('core', 'plugin_functions');
7776 return $pluginfunctions;
7780 * Get a list of all the plugins that define a certain API function in a certain file.
7782 * @param string $function the part of the name of the function after the
7783 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7784 * names like report_courselist_hook.
7785 * @param string $file the name of file within the plugin that defines the
7786 * function. Defaults to lib.php.
7787 * @param bool $include Whether to include the files that contain the functions or not.
7788 * @return array with [plugintype][plugin] = functionname
7790 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7791 global $CFG;
7793 if (during_initial_install() || isset($CFG->upgraderunning)) {
7794 // API functions _must not_ be called during an installation or upgrade.
7795 return [];
7798 $cache = \cache::make('core', 'plugin_functions');
7800 // Including both although I doubt that we will find two functions definitions with the same name.
7801 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7802 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7803 $pluginfunctions = $cache->get($key);
7804 $dirty = false;
7806 // Use the plugin manager to check that plugins are currently installed.
7807 $pluginmanager = \core_plugin_manager::instance();
7809 if ($pluginfunctions !== false) {
7811 // Checking that the files are still available.
7812 foreach ($pluginfunctions as $plugintype => $plugins) {
7814 $allplugins = \core_component::get_plugin_list($plugintype);
7815 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7816 foreach ($plugins as $plugin => $function) {
7817 if (!isset($installedplugins[$plugin])) {
7818 // Plugin code is still present on disk but it is not installed.
7819 $dirty = true;
7820 break 2;
7823 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7824 if (empty($allplugins[$plugin])) {
7825 $dirty = true;
7826 break 2;
7829 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7830 if ($include && $fileexists) {
7831 // Include the files if it was requested.
7832 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7833 } else if (!$fileexists) {
7834 // If the file is not available any more it should not be returned.
7835 $dirty = true;
7836 break 2;
7839 // Check if the function still exists in the file.
7840 if ($include && !function_exists($function)) {
7841 $dirty = true;
7842 break 2;
7847 // If the cache is dirty, we should fall through and let it rebuild.
7848 if (!$dirty) {
7849 return $pluginfunctions;
7853 $pluginfunctions = array();
7855 // To fill the cached. Also, everything should continue working with cache disabled.
7856 $plugintypes = \core_component::get_plugin_types();
7857 foreach ($plugintypes as $plugintype => $unused) {
7859 // We need to include files here.
7860 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7861 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7862 foreach ($pluginswithfile as $plugin => $notused) {
7864 if (!isset($installedplugins[$plugin])) {
7865 continue;
7868 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7870 $pluginfunction = false;
7871 if (function_exists($fullfunction)) {
7872 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7873 $pluginfunction = $fullfunction;
7875 } else if ($plugintype === 'mod') {
7876 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7877 $shortfunction = $plugin . '_' . $function;
7878 if (function_exists($shortfunction)) {
7879 $pluginfunction = $shortfunction;
7883 if ($pluginfunction) {
7884 if (empty($pluginfunctions[$plugintype])) {
7885 $pluginfunctions[$plugintype] = array();
7887 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7892 $cache->set($key, $pluginfunctions);
7894 return $pluginfunctions;
7899 * Lists plugin-like directories within specified directory
7901 * This function was originally used for standard Moodle plugins, please use
7902 * new core_component::get_plugin_list() now.
7904 * This function is used for general directory listing and backwards compatility.
7906 * @param string $directory relative directory from root
7907 * @param string $exclude dir name to exclude from the list (defaults to none)
7908 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7909 * @return array Sorted array of directory names found under the requested parameters
7911 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7912 global $CFG;
7914 $plugins = array();
7916 if (empty($basedir)) {
7917 $basedir = $CFG->dirroot .'/'. $directory;
7919 } else {
7920 $basedir = $basedir .'/'. $directory;
7923 if ($CFG->debugdeveloper and empty($exclude)) {
7924 // Make sure devs do not use this to list normal plugins,
7925 // this is intended for general directories that are not plugins!
7927 $subtypes = core_component::get_plugin_types();
7928 if (in_array($basedir, $subtypes)) {
7929 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7931 unset($subtypes);
7934 $ignorelist = array_flip(array_filter([
7935 'CVS',
7936 '_vti_cnf',
7937 'amd',
7938 'classes',
7939 'simpletest',
7940 'tests',
7941 'templates',
7942 'yui',
7943 $exclude,
7944 ]));
7946 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7947 if (!$dirhandle = opendir($basedir)) {
7948 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7949 return array();
7951 while (false !== ($dir = readdir($dirhandle))) {
7952 if (strpos($dir, '.') === 0) {
7953 // Ignore directories starting with .
7954 // These are treated as hidden directories.
7955 continue;
7957 if (array_key_exists($dir, $ignorelist)) {
7958 // This directory features on the ignore list.
7959 continue;
7961 if (filetype($basedir .'/'. $dir) != 'dir') {
7962 continue;
7964 $plugins[] = $dir;
7966 closedir($dirhandle);
7968 if ($plugins) {
7969 asort($plugins);
7971 return $plugins;
7975 * Invoke plugin's callback functions
7977 * @param string $type plugin type e.g. 'mod'
7978 * @param string $name plugin name
7979 * @param string $feature feature name
7980 * @param string $action feature's action
7981 * @param array $params parameters of callback function, should be an array
7982 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7983 * @return mixed
7985 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7987 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7988 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7992 * Invoke component's callback functions
7994 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7995 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7996 * @param array $params parameters of callback function
7997 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7998 * @return mixed
8000 function component_callback($component, $function, array $params = array(), $default = null) {
8002 $functionname = component_callback_exists($component, $function);
8004 if ($params && (array_keys($params) !== range(0, count($params) - 1))) {
8005 // PHP 8 allows to have associative arrays in the call_user_func_array() parameters but
8006 // PHP 7 does not. Using associative arrays can result in different behavior in different PHP versions.
8007 // See https://php.watch/versions/8.0/named-parameters#named-params-call_user_func_array
8008 // This check can be removed when minimum PHP version for Moodle is raised to 8.
8009 debugging('Parameters array can not be an associative array while Moodle supports both PHP 7 and PHP 8.',
8010 DEBUG_DEVELOPER);
8011 $params = array_values($params);
8014 if ($functionname) {
8015 // Function exists, so just return function result.
8016 $ret = call_user_func_array($functionname, $params);
8017 if (is_null($ret)) {
8018 return $default;
8019 } else {
8020 return $ret;
8023 return $default;
8027 * Determine if a component callback exists and return the function name to call. Note that this
8028 * function will include the required library files so that the functioname returned can be
8029 * called directly.
8031 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
8032 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
8033 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
8034 * @throws coding_exception if invalid component specfied
8036 function component_callback_exists($component, $function) {
8037 global $CFG; // This is needed for the inclusions.
8039 $cleancomponent = clean_param($component, PARAM_COMPONENT);
8040 if (empty($cleancomponent)) {
8041 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8043 $component = $cleancomponent;
8045 list($type, $name) = core_component::normalize_component($component);
8046 $component = $type . '_' . $name;
8048 $oldfunction = $name.'_'.$function;
8049 $function = $component.'_'.$function;
8051 $dir = core_component::get_component_directory($component);
8052 if (empty($dir)) {
8053 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8056 // Load library and look for function.
8057 if (file_exists($dir.'/lib.php')) {
8058 require_once($dir.'/lib.php');
8061 if (!function_exists($function) and function_exists($oldfunction)) {
8062 if ($type !== 'mod' and $type !== 'core') {
8063 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
8065 $function = $oldfunction;
8068 if (function_exists($function)) {
8069 return $function;
8071 return false;
8075 * Call the specified callback method on the provided class.
8077 * If the callback returns null, then the default value is returned instead.
8078 * If the class does not exist, then the default value is returned.
8080 * @param string $classname The name of the class to call upon.
8081 * @param string $methodname The name of the staticically defined method on the class.
8082 * @param array $params The arguments to pass into the method.
8083 * @param mixed $default The default value.
8084 * @return mixed The return value.
8086 function component_class_callback($classname, $methodname, array $params, $default = null) {
8087 if (!class_exists($classname)) {
8088 return $default;
8091 if (!method_exists($classname, $methodname)) {
8092 return $default;
8095 $fullfunction = $classname . '::' . $methodname;
8096 $result = call_user_func_array($fullfunction, $params);
8098 if (null === $result) {
8099 return $default;
8100 } else {
8101 return $result;
8106 * Checks whether a plugin supports a specified feature.
8108 * @param string $type Plugin type e.g. 'mod'
8109 * @param string $name Plugin name e.g. 'forum'
8110 * @param string $feature Feature code (FEATURE_xx constant)
8111 * @param mixed $default default value if feature support unknown
8112 * @return mixed Feature result (false if not supported, null if feature is unknown,
8113 * otherwise usually true but may have other feature-specific value such as array)
8114 * @throws coding_exception
8116 function plugin_supports($type, $name, $feature, $default = null) {
8117 global $CFG;
8119 if ($type === 'mod' and $name === 'NEWMODULE') {
8120 // Somebody forgot to rename the module template.
8121 return false;
8124 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
8125 if (empty($component)) {
8126 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8129 $function = null;
8131 if ($type === 'mod') {
8132 // We need this special case because we support subplugins in modules,
8133 // otherwise it would end up in infinite loop.
8134 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8135 include_once("$CFG->dirroot/mod/$name/lib.php");
8136 $function = $component.'_supports';
8137 if (!function_exists($function)) {
8138 // Legacy non-frankenstyle function name.
8139 $function = $name.'_supports';
8143 } else {
8144 if (!$path = core_component::get_plugin_directory($type, $name)) {
8145 // Non existent plugin type.
8146 return false;
8148 if (file_exists("$path/lib.php")) {
8149 include_once("$path/lib.php");
8150 $function = $component.'_supports';
8154 if ($function and function_exists($function)) {
8155 $supports = $function($feature);
8156 if (is_null($supports)) {
8157 // Plugin does not know - use default.
8158 return $default;
8159 } else {
8160 return $supports;
8164 // Plugin does not care, so use default.
8165 return $default;
8169 * Returns true if the current version of PHP is greater that the specified one.
8171 * @todo Check PHP version being required here is it too low?
8173 * @param string $version The version of php being tested.
8174 * @return bool
8176 function check_php_version($version='5.2.4') {
8177 return (version_compare(phpversion(), $version) >= 0);
8181 * Determine if moodle installation requires update.
8183 * Checks version numbers of main code and all plugins to see
8184 * if there are any mismatches.
8186 * @return bool
8188 function moodle_needs_upgrading() {
8189 global $CFG;
8191 if (empty($CFG->version)) {
8192 return true;
8195 // There is no need to purge plugininfo caches here because
8196 // these caches are not used during upgrade and they are purged after
8197 // every upgrade.
8199 if (empty($CFG->allversionshash)) {
8200 return true;
8203 $hash = core_component::get_all_versions_hash();
8205 return ($hash !== $CFG->allversionshash);
8209 * Returns the major version of this site
8211 * Moodle version numbers consist of three numbers separated by a dot, for
8212 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
8213 * called major version. This function extracts the major version from either
8214 * $CFG->release (default) or eventually from the $release variable defined in
8215 * the main version.php.
8217 * @param bool $fromdisk should the version if source code files be used
8218 * @return string|false the major version like '2.3', false if could not be determined
8220 function moodle_major_version($fromdisk = false) {
8221 global $CFG;
8223 if ($fromdisk) {
8224 $release = null;
8225 require($CFG->dirroot.'/version.php');
8226 if (empty($release)) {
8227 return false;
8230 } else {
8231 if (empty($CFG->release)) {
8232 return false;
8234 $release = $CFG->release;
8237 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8238 return $matches[0];
8239 } else {
8240 return false;
8244 // MISCELLANEOUS.
8247 * Gets the system locale
8249 * @return string Retuns the current locale.
8251 function moodle_getlocale() {
8252 global $CFG;
8254 // Fetch the correct locale based on ostype.
8255 if ($CFG->ostype == 'WINDOWS') {
8256 $stringtofetch = 'localewin';
8257 } else {
8258 $stringtofetch = 'locale';
8261 if (!empty($CFG->locale)) { // Override locale for all language packs.
8262 return $CFG->locale;
8265 return get_string($stringtofetch, 'langconfig');
8269 * Sets the system locale
8271 * @category string
8272 * @param string $locale Can be used to force a locale
8274 function moodle_setlocale($locale='') {
8275 global $CFG;
8277 static $currentlocale = ''; // Last locale caching.
8279 $oldlocale = $currentlocale;
8281 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8282 if (!empty($locale)) {
8283 $currentlocale = $locale;
8284 } else {
8285 $currentlocale = moodle_getlocale();
8288 // Do nothing if locale already set up.
8289 if ($oldlocale == $currentlocale) {
8290 return;
8293 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8294 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8295 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8297 // Get current values.
8298 $monetary= setlocale (LC_MONETARY, 0);
8299 $numeric = setlocale (LC_NUMERIC, 0);
8300 $ctype = setlocale (LC_CTYPE, 0);
8301 if ($CFG->ostype != 'WINDOWS') {
8302 $messages= setlocale (LC_MESSAGES, 0);
8304 // Set locale to all.
8305 $result = setlocale (LC_ALL, $currentlocale);
8306 // If setting of locale fails try the other utf8 or utf-8 variant,
8307 // some operating systems support both (Debian), others just one (OSX).
8308 if ($result === false) {
8309 if (stripos($currentlocale, '.UTF-8') !== false) {
8310 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8311 setlocale (LC_ALL, $newlocale);
8312 } else if (stripos($currentlocale, '.UTF8') !== false) {
8313 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8314 setlocale (LC_ALL, $newlocale);
8317 // Set old values.
8318 setlocale (LC_MONETARY, $monetary);
8319 setlocale (LC_NUMERIC, $numeric);
8320 if ($CFG->ostype != 'WINDOWS') {
8321 setlocale (LC_MESSAGES, $messages);
8323 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8324 // To workaround a well-known PHP problem with Turkish letter Ii.
8325 setlocale (LC_CTYPE, $ctype);
8330 * Count words in a string.
8332 * Words are defined as things between whitespace.
8334 * @category string
8335 * @param string $string The text to be searched for words. May be HTML.
8336 * @return int The count of words in the specified string
8338 function count_words($string) {
8339 // Before stripping tags, add a space after the close tag of anything that is not obviously inline.
8340 // Also, br is a special case because it definitely delimits a word, but has no close tag.
8341 $string = preg_replace('~
8342 ( # Capture the tag we match.
8343 </ # Start of close tag.
8344 (?! # Do not match any of these specific close tag names.
8345 a> | b> | del> | em> | i> |
8346 ins> | s> | small> |
8347 strong> | sub> | sup> | u>
8349 \w+ # But, apart from those execptions, match any tag name.
8350 > # End of close tag.
8352 <br> | <br\s*/> # Special cases that are not close tags.
8354 ~x', '$1 ', $string); // Add a space after the close tag.
8355 // Now remove HTML tags.
8356 $string = strip_tags($string);
8357 // Decode HTML entities.
8358 $string = html_entity_decode($string);
8360 // Now, the word count is the number of blocks of characters separated
8361 // by any sort of space. That seems to be the definition used by all other systems.
8362 // To be precise about what is considered to separate words:
8363 // * Anything that Unicode considers a 'Separator'
8364 // * Anything that Unicode considers a 'Control character'
8365 // * An em- or en- dash.
8366 return count(preg_split('~[\p{Z}\p{Cc}—–]+~u', $string, -1, PREG_SPLIT_NO_EMPTY));
8370 * Count letters in a string.
8372 * Letters are defined as chars not in tags and different from whitespace.
8374 * @category string
8375 * @param string $string The text to be searched for letters. May be HTML.
8376 * @return int The count of letters in the specified text.
8378 function count_letters($string) {
8379 $string = strip_tags($string); // Tags are out now.
8380 $string = html_entity_decode($string);
8381 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8383 return core_text::strlen($string);
8387 * Generate and return a random string of the specified length.
8389 * @param int $length The length of the string to be created.
8390 * @return string
8392 function random_string($length=15) {
8393 $randombytes = random_bytes_emulate($length);
8394 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8395 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8396 $pool .= '0123456789';
8397 $poollen = strlen($pool);
8398 $string = '';
8399 for ($i = 0; $i < $length; $i++) {
8400 $rand = ord($randombytes[$i]);
8401 $string .= substr($pool, ($rand%($poollen)), 1);
8403 return $string;
8407 * Generate a complex random string (useful for md5 salts)
8409 * This function is based on the above {@link random_string()} however it uses a
8410 * larger pool of characters and generates a string between 24 and 32 characters
8412 * @param int $length Optional if set generates a string to exactly this length
8413 * @return string
8415 function complex_random_string($length=null) {
8416 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8417 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8418 $poollen = strlen($pool);
8419 if ($length===null) {
8420 $length = floor(rand(24, 32));
8422 $randombytes = random_bytes_emulate($length);
8423 $string = '';
8424 for ($i = 0; $i < $length; $i++) {
8425 $rand = ord($randombytes[$i]);
8426 $string .= $pool[($rand%$poollen)];
8428 return $string;
8432 * Try to generates cryptographically secure pseudo-random bytes.
8434 * Note this is achieved by fallbacking between:
8435 * - PHP 7 random_bytes().
8436 * - OpenSSL openssl_random_pseudo_bytes().
8437 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8439 * @param int $length requested length in bytes
8440 * @return string binary data
8442 function random_bytes_emulate($length) {
8443 global $CFG;
8444 if ($length <= 0) {
8445 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8446 return '';
8448 if (function_exists('random_bytes')) {
8449 // Use PHP 7 goodness.
8450 $hash = @random_bytes($length);
8451 if ($hash !== false) {
8452 return $hash;
8455 if (function_exists('openssl_random_pseudo_bytes')) {
8456 // If you have the openssl extension enabled.
8457 $hash = openssl_random_pseudo_bytes($length);
8458 if ($hash !== false) {
8459 return $hash;
8463 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8464 $staticdata = serialize($CFG) . serialize($_SERVER);
8465 $hash = '';
8466 do {
8467 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8468 } while (strlen($hash) < $length);
8470 return substr($hash, 0, $length);
8474 * Given some text (which may contain HTML) and an ideal length,
8475 * this function truncates the text neatly on a word boundary if possible
8477 * @category string
8478 * @param string $text text to be shortened
8479 * @param int $ideal ideal string length
8480 * @param boolean $exact if false, $text will not be cut mid-word
8481 * @param string $ending The string to append if the passed string is truncated
8482 * @return string $truncate shortened string
8484 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8485 // If the plain text is shorter than the maximum length, return the whole text.
8486 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8487 return $text;
8490 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8491 // and only tag in its 'line'.
8492 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8494 $totallength = core_text::strlen($ending);
8495 $truncate = '';
8497 // This array stores information about open and close tags and their position
8498 // in the truncated string. Each item in the array is an object with fields
8499 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8500 // (byte position in truncated text).
8501 $tagdetails = array();
8503 foreach ($lines as $linematchings) {
8504 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8505 if (!empty($linematchings[1])) {
8506 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8507 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8508 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8509 // Record closing tag.
8510 $tagdetails[] = (object) array(
8511 'open' => false,
8512 'tag' => core_text::strtolower($tagmatchings[1]),
8513 'pos' => core_text::strlen($truncate),
8516 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8517 // Record opening tag.
8518 $tagdetails[] = (object) array(
8519 'open' => true,
8520 'tag' => core_text::strtolower($tagmatchings[1]),
8521 'pos' => core_text::strlen($truncate),
8523 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8524 $tagdetails[] = (object) array(
8525 'open' => true,
8526 'tag' => core_text::strtolower('if'),
8527 'pos' => core_text::strlen($truncate),
8529 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8530 $tagdetails[] = (object) array(
8531 'open' => false,
8532 'tag' => core_text::strtolower('if'),
8533 'pos' => core_text::strlen($truncate),
8537 // Add html-tag to $truncate'd text.
8538 $truncate .= $linematchings[1];
8541 // Calculate the length of the plain text part of the line; handle entities as one character.
8542 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8543 if ($totallength + $contentlength > $ideal) {
8544 // The number of characters which are left.
8545 $left = $ideal - $totallength;
8546 $entitieslength = 0;
8547 // Search for html entities.
8548 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)) {
8549 // Calculate the real length of all entities in the legal range.
8550 foreach ($entities[0] as $entity) {
8551 if ($entity[1]+1-$entitieslength <= $left) {
8552 $left--;
8553 $entitieslength += core_text::strlen($entity[0]);
8554 } else {
8555 // No more characters left.
8556 break;
8560 $breakpos = $left + $entitieslength;
8562 // If the words shouldn't be cut in the middle...
8563 if (!$exact) {
8564 // Search the last occurence of a space.
8565 for (; $breakpos > 0; $breakpos--) {
8566 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8567 if ($char === '.' or $char === ' ') {
8568 $breakpos += 1;
8569 break;
8570 } else if (strlen($char) > 2) {
8571 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8572 $breakpos += 1;
8573 break;
8578 if ($breakpos == 0) {
8579 // This deals with the test_shorten_text_no_spaces case.
8580 $breakpos = $left + $entitieslength;
8581 } else if ($breakpos > $left + $entitieslength) {
8582 // This deals with the previous for loop breaking on the first char.
8583 $breakpos = $left + $entitieslength;
8586 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8587 // Maximum length is reached, so get off the loop.
8588 break;
8589 } else {
8590 $truncate .= $linematchings[2];
8591 $totallength += $contentlength;
8594 // If the maximum length is reached, get off the loop.
8595 if ($totallength >= $ideal) {
8596 break;
8600 // Add the defined ending to the text.
8601 $truncate .= $ending;
8603 // Now calculate the list of open html tags based on the truncate position.
8604 $opentags = array();
8605 foreach ($tagdetails as $taginfo) {
8606 if ($taginfo->open) {
8607 // Add tag to the beginning of $opentags list.
8608 array_unshift($opentags, $taginfo->tag);
8609 } else {
8610 // Can have multiple exact same open tags, close the last one.
8611 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8612 if ($pos !== false) {
8613 unset($opentags[$pos]);
8618 // Close all unclosed html-tags.
8619 foreach ($opentags as $tag) {
8620 if ($tag === 'if') {
8621 $truncate .= '<!--<![endif]-->';
8622 } else {
8623 $truncate .= '</' . $tag . '>';
8627 return $truncate;
8631 * Shortens a given filename by removing characters positioned after the ideal string length.
8632 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8633 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8635 * @param string $filename file name
8636 * @param int $length ideal string length
8637 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8638 * @return string $shortened shortened file name
8640 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8641 $shortened = $filename;
8642 // Extract a part of the filename if it's char size exceeds the ideal string length.
8643 if (core_text::strlen($filename) > $length) {
8644 // Exclude extension if present in filename.
8645 $mimetypes = get_mimetypes_array();
8646 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8647 if ($extension && !empty($mimetypes[$extension])) {
8648 $basename = pathinfo($filename, PATHINFO_FILENAME);
8649 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8650 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8651 $shortened .= '.' . $extension;
8652 } else {
8653 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8654 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8657 return $shortened;
8661 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8663 * @param array $path The paths to reduce the length.
8664 * @param int $length Ideal string length
8665 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8666 * @return array $result Shortened paths in array.
8668 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8669 $result = null;
8671 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8672 $carry[] = shorten_filename($singlepath, $length, $includehash);
8673 return $carry;
8674 }, []);
8676 return $result;
8680 * Given dates in seconds, how many weeks is the date from startdate
8681 * The first week is 1, the second 2 etc ...
8683 * @param int $startdate Timestamp for the start date
8684 * @param int $thedate Timestamp for the end date
8685 * @return string
8687 function getweek ($startdate, $thedate) {
8688 if ($thedate < $startdate) {
8689 return 0;
8692 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8696 * Returns a randomly generated password of length $maxlen. inspired by
8698 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8699 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8701 * @param int $maxlen The maximum size of the password being generated.
8702 * @return string
8704 function generate_password($maxlen=10) {
8705 global $CFG;
8707 if (empty($CFG->passwordpolicy)) {
8708 $fillers = PASSWORD_DIGITS;
8709 $wordlist = file($CFG->wordlist);
8710 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8711 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8712 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8713 $password = $word1 . $filler1 . $word2;
8714 } else {
8715 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8716 $digits = $CFG->minpassworddigits;
8717 $lower = $CFG->minpasswordlower;
8718 $upper = $CFG->minpasswordupper;
8719 $nonalphanum = $CFG->minpasswordnonalphanum;
8720 $total = $lower + $upper + $digits + $nonalphanum;
8721 // Var minlength should be the greater one of the two ( $minlen and $total ).
8722 $minlen = $minlen < $total ? $total : $minlen;
8723 // Var maxlen can never be smaller than minlen.
8724 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8725 $additional = $maxlen - $total;
8727 // Make sure we have enough characters to fulfill
8728 // complexity requirements.
8729 $passworddigits = PASSWORD_DIGITS;
8730 while ($digits > strlen($passworddigits)) {
8731 $passworddigits .= PASSWORD_DIGITS;
8733 $passwordlower = PASSWORD_LOWER;
8734 while ($lower > strlen($passwordlower)) {
8735 $passwordlower .= PASSWORD_LOWER;
8737 $passwordupper = PASSWORD_UPPER;
8738 while ($upper > strlen($passwordupper)) {
8739 $passwordupper .= PASSWORD_UPPER;
8741 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8742 while ($nonalphanum > strlen($passwordnonalphanum)) {
8743 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8746 // Now mix and shuffle it all.
8747 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8748 substr(str_shuffle ($passwordupper), 0, $upper) .
8749 substr(str_shuffle ($passworddigits), 0, $digits) .
8750 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8751 substr(str_shuffle ($passwordlower .
8752 $passwordupper .
8753 $passworddigits .
8754 $passwordnonalphanum), 0 , $additional));
8757 return substr ($password, 0, $maxlen);
8761 * Given a float, prints it nicely.
8762 * Localized floats must not be used in calculations!
8764 * The stripzeros feature is intended for making numbers look nicer in small
8765 * areas where it is not necessary to indicate the degree of accuracy by showing
8766 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8767 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8769 * @param float $float The float to print
8770 * @param int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision).
8771 * @param bool $localized use localized decimal separator
8772 * @param bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after
8773 * the decimal point are always striped if $decimalpoints is -1.
8774 * @return string locale float
8776 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8777 if (is_null($float)) {
8778 return '';
8780 if ($localized) {
8781 $separator = get_string('decsep', 'langconfig');
8782 } else {
8783 $separator = '.';
8785 if ($decimalpoints == -1) {
8786 // The following counts the number of decimals.
8787 // It is safe as both floatval() and round() functions have same behaviour when non-numeric values are provided.
8788 $floatval = floatval($float);
8789 for ($decimalpoints = 0; $floatval != round($float, $decimalpoints); $decimalpoints++);
8792 $result = number_format($float, $decimalpoints, $separator, '');
8793 if ($stripzeros && $decimalpoints > 0) {
8794 // Remove zeros and final dot if not needed.
8795 // However, only do this if there is a decimal point!
8796 $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
8798 return $result;
8802 * Converts locale specific floating point/comma number back to standard PHP float value
8803 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8805 * @param string $localefloat locale aware float representation
8806 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8807 * @return mixed float|bool - false or the parsed float.
8809 function unformat_float($localefloat, $strict = false) {
8810 $localefloat = trim((string)$localefloat);
8812 if ($localefloat == '') {
8813 return null;
8816 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8817 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8819 if ($strict && !is_numeric($localefloat)) {
8820 return false;
8823 return (float)$localefloat;
8827 * Given a simple array, this shuffles it up just like shuffle()
8828 * Unlike PHP's shuffle() this function works on any machine.
8830 * @param array $array The array to be rearranged
8831 * @return array
8833 function swapshuffle($array) {
8835 $last = count($array) - 1;
8836 for ($i = 0; $i <= $last; $i++) {
8837 $from = rand(0, $last);
8838 $curr = $array[$i];
8839 $array[$i] = $array[$from];
8840 $array[$from] = $curr;
8842 return $array;
8846 * Like {@link swapshuffle()}, but works on associative arrays
8848 * @param array $array The associative array to be rearranged
8849 * @return array
8851 function swapshuffle_assoc($array) {
8853 $newarray = array();
8854 $newkeys = swapshuffle(array_keys($array));
8856 foreach ($newkeys as $newkey) {
8857 $newarray[$newkey] = $array[$newkey];
8859 return $newarray;
8863 * Given an arbitrary array, and a number of draws,
8864 * this function returns an array with that amount
8865 * of items. The indexes are retained.
8867 * @todo Finish documenting this function
8869 * @param array $array
8870 * @param int $draws
8871 * @return array
8873 function draw_rand_array($array, $draws) {
8875 $return = array();
8877 $last = count($array);
8879 if ($draws > $last) {
8880 $draws = $last;
8883 while ($draws > 0) {
8884 $last--;
8886 $keys = array_keys($array);
8887 $rand = rand(0, $last);
8889 $return[$keys[$rand]] = $array[$keys[$rand]];
8890 unset($array[$keys[$rand]]);
8892 $draws--;
8895 return $return;
8899 * Calculate the difference between two microtimes
8901 * @param string $a The first Microtime
8902 * @param string $b The second Microtime
8903 * @return string
8905 function microtime_diff($a, $b) {
8906 list($adec, $asec) = explode(' ', $a);
8907 list($bdec, $bsec) = explode(' ', $b);
8908 return $bsec - $asec + $bdec - $adec;
8912 * Given a list (eg a,b,c,d,e) this function returns
8913 * an array of 1->a, 2->b, 3->c etc
8915 * @param string $list The string to explode into array bits
8916 * @param string $separator The separator used within the list string
8917 * @return array The now assembled array
8919 function make_menu_from_list($list, $separator=',') {
8921 $array = array_reverse(explode($separator, $list), true);
8922 foreach ($array as $key => $item) {
8923 $outarray[$key+1] = trim($item);
8925 return $outarray;
8929 * Creates an array that represents all the current grades that
8930 * can be chosen using the given grading type.
8932 * Negative numbers
8933 * are scales, zero is no grade, and positive numbers are maximum
8934 * grades.
8936 * @todo Finish documenting this function or better deprecated this completely!
8938 * @param int $gradingtype
8939 * @return array
8941 function make_grades_menu($gradingtype) {
8942 global $DB;
8944 $grades = array();
8945 if ($gradingtype < 0) {
8946 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8947 return make_menu_from_list($scale->scale);
8949 } else if ($gradingtype > 0) {
8950 for ($i=$gradingtype; $i>=0; $i--) {
8951 $grades[$i] = $i .' / '. $gradingtype;
8953 return $grades;
8955 return $grades;
8959 * make_unique_id_code
8961 * @todo Finish documenting this function
8963 * @uses $_SERVER
8964 * @param string $extra Extra string to append to the end of the code
8965 * @return string
8967 function make_unique_id_code($extra = '') {
8969 $hostname = 'unknownhost';
8970 if (!empty($_SERVER['HTTP_HOST'])) {
8971 $hostname = $_SERVER['HTTP_HOST'];
8972 } else if (!empty($_ENV['HTTP_HOST'])) {
8973 $hostname = $_ENV['HTTP_HOST'];
8974 } else if (!empty($_SERVER['SERVER_NAME'])) {
8975 $hostname = $_SERVER['SERVER_NAME'];
8976 } else if (!empty($_ENV['SERVER_NAME'])) {
8977 $hostname = $_ENV['SERVER_NAME'];
8980 $date = gmdate("ymdHis");
8982 $random = random_string(6);
8984 if ($extra) {
8985 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8986 } else {
8987 return $hostname .'+'. $date .'+'. $random;
8993 * Function to check the passed address is within the passed subnet
8995 * The parameter is a comma separated string of subnet definitions.
8996 * Subnet strings can be in one of three formats:
8997 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8998 * 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)
8999 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
9000 * Code for type 1 modified from user posted comments by mediator at
9001 * {@link http://au.php.net/manual/en/function.ip2long.php}
9003 * @param string $addr The address you are checking
9004 * @param string $subnetstr The string of subnet addresses
9005 * @return bool
9007 function address_in_subnet($addr, $subnetstr) {
9009 if ($addr == '0.0.0.0') {
9010 return false;
9012 $subnets = explode(',', $subnetstr);
9013 $found = false;
9014 $addr = trim($addr);
9015 $addr = cleanremoteaddr($addr, false); // Normalise.
9016 if ($addr === null) {
9017 return false;
9019 $addrparts = explode(':', $addr);
9021 $ipv6 = strpos($addr, ':');
9023 foreach ($subnets as $subnet) {
9024 $subnet = trim($subnet);
9025 if ($subnet === '') {
9026 continue;
9029 if (strpos($subnet, '/') !== false) {
9030 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
9031 list($ip, $mask) = explode('/', $subnet);
9032 $mask = trim($mask);
9033 if (!is_number($mask)) {
9034 continue; // Incorect mask number, eh?
9036 $ip = cleanremoteaddr($ip, false); // Normalise.
9037 if ($ip === null) {
9038 continue;
9040 if (strpos($ip, ':') !== false) {
9041 // IPv6.
9042 if (!$ipv6) {
9043 continue;
9045 if ($mask > 128 or $mask < 0) {
9046 continue; // Nonsense.
9048 if ($mask == 0) {
9049 return true; // Any address.
9051 if ($mask == 128) {
9052 if ($ip === $addr) {
9053 return true;
9055 continue;
9057 $ipparts = explode(':', $ip);
9058 $modulo = $mask % 16;
9059 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
9060 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
9061 if (implode(':', $ipnet) === implode(':', $addrnet)) {
9062 if ($modulo == 0) {
9063 return true;
9065 $pos = ($mask-$modulo)/16;
9066 $ipnet = hexdec($ipparts[$pos]);
9067 $addrnet = hexdec($addrparts[$pos]);
9068 $mask = 0xffff << (16 - $modulo);
9069 if (($addrnet & $mask) == ($ipnet & $mask)) {
9070 return true;
9074 } else {
9075 // IPv4.
9076 if ($ipv6) {
9077 continue;
9079 if ($mask > 32 or $mask < 0) {
9080 continue; // Nonsense.
9082 if ($mask == 0) {
9083 return true;
9085 if ($mask == 32) {
9086 if ($ip === $addr) {
9087 return true;
9089 continue;
9091 $mask = 0xffffffff << (32 - $mask);
9092 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
9093 return true;
9097 } else if (strpos($subnet, '-') !== false) {
9098 // 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.
9099 $parts = explode('-', $subnet);
9100 if (count($parts) != 2) {
9101 continue;
9104 if (strpos($subnet, ':') !== false) {
9105 // IPv6.
9106 if (!$ipv6) {
9107 continue;
9109 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9110 if ($ipstart === null) {
9111 continue;
9113 $ipparts = explode(':', $ipstart);
9114 $start = hexdec(array_pop($ipparts));
9115 $ipparts[] = trim($parts[1]);
9116 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
9117 if ($ipend === null) {
9118 continue;
9120 $ipparts[7] = '';
9121 $ipnet = implode(':', $ipparts);
9122 if (strpos($addr, $ipnet) !== 0) {
9123 continue;
9125 $ipparts = explode(':', $ipend);
9126 $end = hexdec($ipparts[7]);
9128 $addrend = hexdec($addrparts[7]);
9130 if (($addrend >= $start) and ($addrend <= $end)) {
9131 return true;
9134 } else {
9135 // IPv4.
9136 if ($ipv6) {
9137 continue;
9139 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9140 if ($ipstart === null) {
9141 continue;
9143 $ipparts = explode('.', $ipstart);
9144 $ipparts[3] = trim($parts[1]);
9145 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
9146 if ($ipend === null) {
9147 continue;
9150 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9151 return true;
9155 } else {
9156 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9157 if (strpos($subnet, ':') !== false) {
9158 // IPv6.
9159 if (!$ipv6) {
9160 continue;
9162 $parts = explode(':', $subnet);
9163 $count = count($parts);
9164 if ($parts[$count-1] === '') {
9165 unset($parts[$count-1]); // Trim trailing :'s.
9166 $count--;
9167 $subnet = implode('.', $parts);
9169 $isip = cleanremoteaddr($subnet, false); // Normalise.
9170 if ($isip !== null) {
9171 if ($isip === $addr) {
9172 return true;
9174 continue;
9175 } else if ($count > 8) {
9176 continue;
9178 $zeros = array_fill(0, 8-$count, '0');
9179 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9180 if (address_in_subnet($addr, $subnet)) {
9181 return true;
9184 } else {
9185 // IPv4.
9186 if ($ipv6) {
9187 continue;
9189 $parts = explode('.', $subnet);
9190 $count = count($parts);
9191 if ($parts[$count-1] === '') {
9192 unset($parts[$count-1]); // Trim trailing .
9193 $count--;
9194 $subnet = implode('.', $parts);
9196 if ($count == 4) {
9197 $subnet = cleanremoteaddr($subnet, false); // Normalise.
9198 if ($subnet === $addr) {
9199 return true;
9201 continue;
9202 } else if ($count > 4) {
9203 continue;
9205 $zeros = array_fill(0, 4-$count, '0');
9206 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9207 if (address_in_subnet($addr, $subnet)) {
9208 return true;
9214 return false;
9218 * For outputting debugging info
9220 * @param string $string The string to write
9221 * @param string $eol The end of line char(s) to use
9222 * @param string $sleep Period to make the application sleep
9223 * This ensures any messages have time to display before redirect
9225 function mtrace($string, $eol="\n", $sleep=0) {
9226 global $CFG;
9228 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
9229 $fn = $CFG->mtrace_wrapper;
9230 $fn($string, $eol);
9231 return;
9232 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
9233 // We must explicitly call the add_line function here.
9234 // Uses of fwrite to STDOUT are not picked up by ob_start.
9235 if ($output = \core\task\logmanager::add_line("{$string}{$eol}")) {
9236 fwrite(STDOUT, $output);
9238 } else {
9239 echo $string . $eol;
9242 // Flush again.
9243 flush();
9245 // Delay to keep message on user's screen in case of subsequent redirect.
9246 if ($sleep) {
9247 sleep($sleep);
9252 * Replace 1 or more slashes or backslashes to 1 slash
9254 * @param string $path The path to strip
9255 * @return string the path with double slashes removed
9257 function cleardoubleslashes ($path) {
9258 return preg_replace('/(\/|\\\){1,}/', '/', $path);
9262 * Is the current ip in a given list?
9264 * @param string $list
9265 * @return bool
9267 function remoteip_in_list($list) {
9268 $clientip = getremoteaddr(null);
9270 if (!$clientip) {
9271 // Ensure access on cli.
9272 return true;
9274 return \core\ip_utils::is_ip_in_subnet_list($clientip, $list);
9278 * Returns most reliable client address
9280 * @param string $default If an address can't be determined, then return this
9281 * @return string The remote IP address
9283 function getremoteaddr($default='0.0.0.0') {
9284 global $CFG;
9286 if (!isset($CFG->getremoteaddrconf)) {
9287 // This will happen, for example, before just after the upgrade, as the
9288 // user is redirected to the admin screen.
9289 $variablestoskip = GETREMOTEADDR_SKIP_DEFAULT;
9290 } else {
9291 $variablestoskip = $CFG->getremoteaddrconf;
9293 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
9294 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9295 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9296 return $address ? $address : $default;
9299 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
9300 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9301 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9303 $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
9304 global $CFG;
9305 return !\core\ip_utils::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore ?? '', ',');
9308 // Multiple proxies can append values to this header including an
9309 // untrusted original request header so we must only trust the last ip.
9310 $address = end($forwardedaddresses);
9312 if (substr_count($address, ":") > 1) {
9313 // Remove port and brackets from IPv6.
9314 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9315 $address = $matches[1];
9317 } else {
9318 // Remove port from IPv4.
9319 if (substr_count($address, ":") == 1) {
9320 $parts = explode(":", $address);
9321 $address = $parts[0];
9325 $address = cleanremoteaddr($address);
9326 return $address ? $address : $default;
9329 if (!empty($_SERVER['REMOTE_ADDR'])) {
9330 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9331 return $address ? $address : $default;
9332 } else {
9333 return $default;
9338 * Cleans an ip address. Internal addresses are now allowed.
9339 * (Originally local addresses were not allowed.)
9341 * @param string $addr IPv4 or IPv6 address
9342 * @param bool $compress use IPv6 address compression
9343 * @return string normalised ip address string, null if error
9345 function cleanremoteaddr($addr, $compress=false) {
9346 $addr = trim($addr);
9348 if (strpos($addr, ':') !== false) {
9349 // Can be only IPv6.
9350 $parts = explode(':', $addr);
9351 $count = count($parts);
9353 if (strpos($parts[$count-1], '.') !== false) {
9354 // Legacy ipv4 notation.
9355 $last = array_pop($parts);
9356 $ipv4 = cleanremoteaddr($last, true);
9357 if ($ipv4 === null) {
9358 return null;
9360 $bits = explode('.', $ipv4);
9361 $parts[] = dechex($bits[0]).dechex($bits[1]);
9362 $parts[] = dechex($bits[2]).dechex($bits[3]);
9363 $count = count($parts);
9364 $addr = implode(':', $parts);
9367 if ($count < 3 or $count > 8) {
9368 return null; // Severly malformed.
9371 if ($count != 8) {
9372 if (strpos($addr, '::') === false) {
9373 return null; // Malformed.
9375 // Uncompress.
9376 $insertat = array_search('', $parts, true);
9377 $missing = array_fill(0, 1 + 8 - $count, '0');
9378 array_splice($parts, $insertat, 1, $missing);
9379 foreach ($parts as $key => $part) {
9380 if ($part === '') {
9381 $parts[$key] = '0';
9386 $adr = implode(':', $parts);
9387 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9388 return null; // Incorrect format - sorry.
9391 // Normalise 0s and case.
9392 $parts = array_map('hexdec', $parts);
9393 $parts = array_map('dechex', $parts);
9395 $result = implode(':', $parts);
9397 if (!$compress) {
9398 return $result;
9401 if ($result === '0:0:0:0:0:0:0:0') {
9402 return '::'; // All addresses.
9405 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9406 if ($compressed !== $result) {
9407 return $compressed;
9410 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9411 if ($compressed !== $result) {
9412 return $compressed;
9415 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9416 if ($compressed !== $result) {
9417 return $compressed;
9420 return $result;
9423 // First get all things that look like IPv4 addresses.
9424 $parts = array();
9425 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9426 return null;
9428 unset($parts[0]);
9430 foreach ($parts as $key => $match) {
9431 if ($match > 255) {
9432 return null;
9434 $parts[$key] = (int)$match; // Normalise 0s.
9437 return implode('.', $parts);
9442 * Is IP address a public address?
9444 * @param string $ip The ip to check
9445 * @return bool true if the ip is public
9447 function ip_is_public($ip) {
9448 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9452 * This function will make a complete copy of anything it's given,
9453 * regardless of whether it's an object or not.
9455 * @param mixed $thing Something you want cloned
9456 * @return mixed What ever it is you passed it
9458 function fullclone($thing) {
9459 return unserialize(serialize($thing));
9463 * Used to make sure that $min <= $value <= $max
9465 * Make sure that value is between min, and max
9467 * @param int $min The minimum value
9468 * @param int $value The value to check
9469 * @param int $max The maximum value
9470 * @return int
9472 function bounded_number($min, $value, $max) {
9473 if ($value < $min) {
9474 return $min;
9476 if ($value > $max) {
9477 return $max;
9479 return $value;
9483 * Check if there is a nested array within the passed array
9485 * @param array $array
9486 * @return bool true if there is a nested array false otherwise
9488 function array_is_nested($array) {
9489 foreach ($array as $value) {
9490 if (is_array($value)) {
9491 return true;
9494 return false;
9498 * get_performance_info() pairs up with init_performance_info()
9499 * loaded in setup.php. Returns an array with 'html' and 'txt'
9500 * values ready for use, and each of the individual stats provided
9501 * separately as well.
9503 * @return array
9505 function get_performance_info() {
9506 global $CFG, $PERF, $DB, $PAGE;
9508 $info = array();
9509 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9511 $info['html'] = '';
9512 if (!empty($CFG->themedesignermode)) {
9513 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9514 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9516 $info['html'] .= '<ul class="list-unstyled row mx-md-0">'; // Holds userfriendly HTML representation.
9518 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9520 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9521 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9523 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9524 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9526 if (function_exists('memory_get_usage')) {
9527 $info['memory_total'] = memory_get_usage();
9528 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9529 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9530 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9531 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9534 if (function_exists('memory_get_peak_usage')) {
9535 $info['memory_peak'] = memory_get_peak_usage();
9536 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9537 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9540 $info['html'] .= '</ul><ul class="list-unstyled row mx-md-0">';
9541 $inc = get_included_files();
9542 $info['includecount'] = count($inc);
9543 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9544 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9546 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9547 // We can not track more performance before installation or before PAGE init, sorry.
9548 return $info;
9551 $filtermanager = filter_manager::instance();
9552 if (method_exists($filtermanager, 'get_performance_summary')) {
9553 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9554 $info = array_merge($filterinfo, $info);
9555 foreach ($filterinfo as $key => $value) {
9556 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9557 $info['txt'] .= "$key: $value ";
9561 $stringmanager = get_string_manager();
9562 if (method_exists($stringmanager, 'get_performance_summary')) {
9563 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9564 $info = array_merge($filterinfo, $info);
9565 foreach ($filterinfo as $key => $value) {
9566 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9567 $info['txt'] .= "$key: $value ";
9571 if (!empty($PERF->logwrites)) {
9572 $info['logwrites'] = $PERF->logwrites;
9573 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9574 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9577 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9578 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9579 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9581 if ($DB->want_read_slave()) {
9582 $info['dbreads_slave'] = $DB->perf_get_reads_slave();
9583 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads from slave: '.$info['dbreads_slave'].'</li> ';
9584 $info['txt'] .= 'db reads from slave: '.$info['dbreads_slave'].' ';
9587 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9588 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9589 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9591 if (function_exists('posix_times')) {
9592 $ptimes = posix_times();
9593 if (is_array($ptimes)) {
9594 foreach ($ptimes as $key => $val) {
9595 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9597 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9598 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9599 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9603 // Grab the load average for the last minute.
9604 // /proc will only work under some linux configurations
9605 // while uptime is there under MacOSX/Darwin and other unices.
9606 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9607 list($serverload) = explode(' ', $loadavg[0]);
9608 unset($loadavg);
9609 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9610 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9611 $serverload = $matches[1];
9612 } else {
9613 trigger_error('Could not parse uptime output!');
9616 if (!empty($serverload)) {
9617 $info['serverload'] = $serverload;
9618 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9619 $info['txt'] .= "serverload: {$info['serverload']} ";
9622 // Display size of session if session started.
9623 if ($si = \core\session\manager::get_performance_info()) {
9624 $info['sessionsize'] = $si['size'];
9625 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9626 $info['txt'] .= $si['txt'];
9629 // Display time waiting for session if applicable.
9630 if (!empty($PERF->sessionlock['wait'])) {
9631 $sessionwait = number_format($PERF->sessionlock['wait'], 3) . ' secs';
9632 $info['html'] .= html_writer::tag('li', 'Session wait: ' . $sessionwait, [
9633 'class' => 'sessionwait col-sm-4'
9635 $info['txt'] .= 'sessionwait: ' . $sessionwait . ' ';
9638 $info['html'] .= '</ul>';
9639 $html = '';
9640 if ($stats = cache_helper::get_stats()) {
9642 $table = new html_table();
9643 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9644 $table->head = ['Mode', 'Cache item', 'Static', 'H', 'M', get_string('mappingprimary', 'cache'), 'H', 'M', 'S', 'I/O'];
9645 $table->data = [];
9646 $table->align = ['left', 'left', 'left', 'right', 'right', 'left', 'right', 'right', 'right', 'right'];
9648 $text = 'Caches used (hits/misses/sets): ';
9649 $hits = 0;
9650 $misses = 0;
9651 $sets = 0;
9652 $maxstores = 0;
9654 // We want to align static caches into their own column.
9655 $hasstatic = false;
9656 foreach ($stats as $definition => $details) {
9657 $numstores = count($details['stores']);
9658 $first = key($details['stores']);
9659 if ($first !== cache_store::STATIC_ACCEL) {
9660 $numstores++; // Add a blank space for the missing static store.
9662 $maxstores = max($maxstores, $numstores);
9665 $storec = 0;
9667 while ($storec++ < ($maxstores - 2)) {
9668 if ($storec == ($maxstores - 2)) {
9669 $table->head[] = get_string('mappingfinal', 'cache');
9670 } else {
9671 $table->head[] = "Store $storec";
9673 $table->align[] = 'left';
9674 $table->align[] = 'right';
9675 $table->align[] = 'right';
9676 $table->align[] = 'right';
9677 $table->align[] = 'right';
9678 $table->head[] = 'H';
9679 $table->head[] = 'M';
9680 $table->head[] = 'S';
9681 $table->head[] = 'I/O';
9684 ksort($stats);
9686 foreach ($stats as $definition => $details) {
9687 switch ($details['mode']) {
9688 case cache_store::MODE_APPLICATION:
9689 $modeclass = 'application';
9690 $mode = ' <span title="application cache">App</span>';
9691 break;
9692 case cache_store::MODE_SESSION:
9693 $modeclass = 'session';
9694 $mode = ' <span title="session cache">Ses</span>';
9695 break;
9696 case cache_store::MODE_REQUEST:
9697 $modeclass = 'request';
9698 $mode = ' <span title="request cache">Req</span>';
9699 break;
9701 $row = [$mode, $definition];
9703 $text .= "$definition {";
9705 $storec = 0;
9706 foreach ($details['stores'] as $store => $data) {
9708 if ($storec == 0 && $store !== cache_store::STATIC_ACCEL) {
9709 $row[] = '';
9710 $row[] = '';
9711 $row[] = '';
9712 $storec++;
9715 $hits += $data['hits'];
9716 $misses += $data['misses'];
9717 $sets += $data['sets'];
9718 if ($data['hits'] == 0 and $data['misses'] > 0) {
9719 $cachestoreclass = 'nohits bg-danger';
9720 } else if ($data['hits'] < $data['misses']) {
9721 $cachestoreclass = 'lowhits bg-warning text-dark';
9722 } else {
9723 $cachestoreclass = 'hihits';
9725 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9726 $cell = new html_table_cell($store);
9727 $cell->attributes = ['class' => $cachestoreclass];
9728 $row[] = $cell;
9729 $cell = new html_table_cell($data['hits']);
9730 $cell->attributes = ['class' => $cachestoreclass];
9731 $row[] = $cell;
9732 $cell = new html_table_cell($data['misses']);
9733 $cell->attributes = ['class' => $cachestoreclass];
9734 $row[] = $cell;
9736 if ($store !== cache_store::STATIC_ACCEL) {
9737 // The static cache is never set.
9738 $cell = new html_table_cell($data['sets']);
9739 $cell->attributes = ['class' => $cachestoreclass];
9740 $row[] = $cell;
9742 if ($data['hits'] || $data['sets']) {
9743 if ($data['iobytes'] === cache_store::IO_BYTES_NOT_SUPPORTED) {
9744 $size = '-';
9745 } else {
9746 $size = display_size($data['iobytes'], 1, 'KB');
9747 if ($data['iobytes'] >= 10 * 1024) {
9748 $cachestoreclass = ' bg-warning text-dark';
9751 } else {
9752 $size = '';
9754 $cell = new html_table_cell($size);
9755 $cell->attributes = ['class' => $cachestoreclass];
9756 $row[] = $cell;
9758 $storec++;
9760 while ($storec++ < $maxstores) {
9761 $row[] = '';
9762 $row[] = '';
9763 $row[] = '';
9764 $row[] = '';
9765 $row[] = '';
9767 $text .= '} ';
9769 $table->data[] = $row;
9772 $html .= html_writer::table($table);
9774 // Now lets also show sub totals for each cache store.
9775 $storetotals = [];
9776 $storetotal = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9777 foreach ($stats as $definition => $details) {
9778 foreach ($details['stores'] as $store => $data) {
9779 if (!array_key_exists($store, $storetotals)) {
9780 $storetotals[$store] = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9782 $storetotals[$store]['class'] = $data['class'];
9783 $storetotals[$store]['hits'] += $data['hits'];
9784 $storetotals[$store]['misses'] += $data['misses'];
9785 $storetotals[$store]['sets'] += $data['sets'];
9786 $storetotal['hits'] += $data['hits'];
9787 $storetotal['misses'] += $data['misses'];
9788 $storetotal['sets'] += $data['sets'];
9789 if ($data['iobytes'] !== cache_store::IO_BYTES_NOT_SUPPORTED) {
9790 $storetotals[$store]['iobytes'] += $data['iobytes'];
9791 $storetotal['iobytes'] += $data['iobytes'];
9796 $table = new html_table();
9797 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9798 $table->head = [get_string('storename', 'cache'), get_string('type_cachestore', 'plugin'), 'H', 'M', 'S', 'I/O'];
9799 $table->data = [];
9800 $table->align = ['left', 'left', 'right', 'right', 'right', 'right'];
9802 ksort($storetotals);
9804 foreach ($storetotals as $store => $data) {
9805 $row = [];
9806 if ($data['hits'] == 0 and $data['misses'] > 0) {
9807 $cachestoreclass = 'nohits bg-danger';
9808 } else if ($data['hits'] < $data['misses']) {
9809 $cachestoreclass = 'lowhits bg-warning text-dark';
9810 } else {
9811 $cachestoreclass = 'hihits';
9813 $cell = new html_table_cell($store);
9814 $cell->attributes = ['class' => $cachestoreclass];
9815 $row[] = $cell;
9816 $cell = new html_table_cell($data['class']);
9817 $cell->attributes = ['class' => $cachestoreclass];
9818 $row[] = $cell;
9819 $cell = new html_table_cell($data['hits']);
9820 $cell->attributes = ['class' => $cachestoreclass];
9821 $row[] = $cell;
9822 $cell = new html_table_cell($data['misses']);
9823 $cell->attributes = ['class' => $cachestoreclass];
9824 $row[] = $cell;
9825 $cell = new html_table_cell($data['sets']);
9826 $cell->attributes = ['class' => $cachestoreclass];
9827 $row[] = $cell;
9828 if ($data['hits'] || $data['sets']) {
9829 if ($data['iobytes']) {
9830 $size = display_size($data['iobytes'], 1, 'KB');
9831 } else {
9832 $size = '-';
9834 } else {
9835 $size = '';
9837 $cell = new html_table_cell($size);
9838 $cell->attributes = ['class' => $cachestoreclass];
9839 $row[] = $cell;
9840 $table->data[] = $row;
9842 if (!empty($storetotal['iobytes'])) {
9843 $size = display_size($storetotal['iobytes'], 1, 'KB');
9844 } else if (!empty($storetotal['hits']) || !empty($storetotal['sets'])) {
9845 $size = '-';
9846 } else {
9847 $size = '';
9849 $row = [
9850 get_string('total'),
9852 $storetotal['hits'],
9853 $storetotal['misses'],
9854 $storetotal['sets'],
9855 $size,
9857 $table->data[] = $row;
9859 $html .= html_writer::table($table);
9861 $info['cachesused'] = "$hits / $misses / $sets";
9862 $info['html'] .= $html;
9863 $info['txt'] .= $text.'. ';
9864 } else {
9865 $info['cachesused'] = '0 / 0 / 0';
9866 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9867 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9870 // Display lock information if any.
9871 if (!empty($PERF->locks)) {
9872 $table = new html_table();
9873 $table->attributes['class'] = 'locktimings table table-dark table-sm w-auto table-bordered';
9874 $table->head = ['Lock', 'Waited (s)', 'Obtained', 'Held for (s)'];
9875 $table->align = ['left', 'right', 'center', 'right'];
9876 $table->data = [];
9877 $text = 'Locks (waited/obtained/held):';
9878 foreach ($PERF->locks as $locktiming) {
9879 $row = [];
9880 $row[] = s($locktiming->type . '/' . $locktiming->resource);
9881 $text .= ' ' . $locktiming->type . '/' . $locktiming->resource . ' (';
9883 // The time we had to wait to get the lock.
9884 $roundedtime = number_format($locktiming->wait, 1);
9885 $cell = new html_table_cell($roundedtime);
9886 if ($locktiming->wait > 0.5) {
9887 $cell->attributes = ['class' => 'bg-warning text-dark'];
9889 $row[] = $cell;
9890 $text .= $roundedtime . '/';
9892 // Show a tick or cross for success.
9893 $row[] = $locktiming->success ? '&#x2713;' : '&#x274c;';
9894 $text .= ($locktiming->success ? 'y' : 'n') . '/';
9896 // If applicable, show how long we held the lock before releasing it.
9897 if (property_exists($locktiming, 'held')) {
9898 $roundedtime = number_format($locktiming->held, 1);
9899 $cell = new html_table_cell($roundedtime);
9900 if ($locktiming->held > 0.5) {
9901 $cell->attributes = ['class' => 'bg-warning text-dark'];
9903 $row[] = $cell;
9904 $text .= $roundedtime;
9905 } else {
9906 $row[] = '-';
9907 $text .= '-';
9909 $text .= ')';
9911 $table->data[] = $row;
9913 $info['html'] .= html_writer::table($table);
9914 $info['txt'] .= $text . '. ';
9917 $info['html'] = '<div class="performanceinfo siteinfo container-fluid px-md-0 overflow-auto pt-3">'.$info['html'].'</div>';
9918 return $info;
9922 * Renames a file or directory to a unique name within the same directory.
9924 * This function is designed to avoid any potential race conditions, and select an unused name.
9926 * @param string $filepath Original filepath
9927 * @param string $prefix Prefix to use for the temporary name
9928 * @return string|bool New file path or false if failed
9929 * @since Moodle 3.10
9931 function rename_to_unused_name(string $filepath, string $prefix = '_temp_') {
9932 $dir = dirname($filepath);
9933 $basename = $dir . '/' . $prefix;
9934 $limit = 0;
9935 while ($limit < 100) {
9936 // Select a new name based on a random number.
9937 $newfilepath = $basename . md5(mt_rand());
9939 // Attempt a rename to that new name.
9940 if (@rename($filepath, $newfilepath)) {
9941 return $newfilepath;
9944 // The first time, do some sanity checks, maybe it is failing for a good reason and there
9945 // is no point trying 100 times if so.
9946 if ($limit === 0 && (!file_exists($filepath) || !is_writable($dir))) {
9947 return false;
9949 $limit++;
9951 return false;
9955 * Delete directory or only its content
9957 * @param string $dir directory path
9958 * @param bool $contentonly
9959 * @return bool success, true also if dir does not exist
9961 function remove_dir($dir, $contentonly=false) {
9962 if (!is_dir($dir)) {
9963 // Nothing to do.
9964 return true;
9967 if (!$contentonly) {
9968 // Start by renaming the directory; this will guarantee that other processes don't write to it
9969 // while it is in the process of being deleted.
9970 $tempdir = rename_to_unused_name($dir);
9971 if ($tempdir) {
9972 // If the rename was successful then delete the $tempdir instead.
9973 $dir = $tempdir;
9975 // If the rename fails, we will continue through and attempt to delete the directory
9976 // without renaming it since that is likely to at least delete most of the files.
9979 if (!$handle = opendir($dir)) {
9980 return false;
9982 $result = true;
9983 while (false!==($item = readdir($handle))) {
9984 if ($item != '.' && $item != '..') {
9985 if (is_dir($dir.'/'.$item)) {
9986 $result = remove_dir($dir.'/'.$item) && $result;
9987 } else {
9988 $result = unlink($dir.'/'.$item) && $result;
9992 closedir($handle);
9993 if ($contentonly) {
9994 clearstatcache(); // Make sure file stat cache is properly invalidated.
9995 return $result;
9997 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9998 clearstatcache(); // Make sure file stat cache is properly invalidated.
9999 return $result;
10003 * Detect if an object or a class contains a given property
10004 * will take an actual object or the name of a class
10006 * @param mix $obj Name of class or real object to test
10007 * @param string $property name of property to find
10008 * @return bool true if property exists
10010 function object_property_exists( $obj, $property ) {
10011 if (is_string( $obj )) {
10012 $properties = get_class_vars( $obj );
10013 } else {
10014 $properties = get_object_vars( $obj );
10016 return array_key_exists( $property, $properties );
10020 * Converts an object into an associative array
10022 * This function converts an object into an associative array by iterating
10023 * over its public properties. Because this function uses the foreach
10024 * construct, Iterators are respected. It works recursively on arrays of objects.
10025 * Arrays and simple values are returned as is.
10027 * If class has magic properties, it can implement IteratorAggregate
10028 * and return all available properties in getIterator()
10030 * @param mixed $var
10031 * @return array
10033 function convert_to_array($var) {
10034 $result = array();
10036 // Loop over elements/properties.
10037 foreach ($var as $key => $value) {
10038 // Recursively convert objects.
10039 if (is_object($value) || is_array($value)) {
10040 $result[$key] = convert_to_array($value);
10041 } else {
10042 // Simple values are untouched.
10043 $result[$key] = $value;
10046 return $result;
10050 * Detect a custom script replacement in the data directory that will
10051 * replace an existing moodle script
10053 * @return string|bool full path name if a custom script exists, false if no custom script exists
10055 function custom_script_path() {
10056 global $CFG, $SCRIPT;
10058 if ($SCRIPT === null) {
10059 // Probably some weird external script.
10060 return false;
10063 $scriptpath = $CFG->customscripts . $SCRIPT;
10065 // Check the custom script exists.
10066 if (file_exists($scriptpath) and is_file($scriptpath)) {
10067 return $scriptpath;
10068 } else {
10069 return false;
10074 * Returns whether or not the user object is a remote MNET user. This function
10075 * is in moodlelib because it does not rely on loading any of the MNET code.
10077 * @param object $user A valid user object
10078 * @return bool True if the user is from a remote Moodle.
10080 function is_mnet_remote_user($user) {
10081 global $CFG;
10083 if (!isset($CFG->mnet_localhost_id)) {
10084 include_once($CFG->dirroot . '/mnet/lib.php');
10085 $env = new mnet_environment();
10086 $env->init();
10087 unset($env);
10090 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
10094 * This function will search for browser prefereed languages, setting Moodle
10095 * to use the best one available if $SESSION->lang is undefined
10097 function setup_lang_from_browser() {
10098 global $CFG, $SESSION, $USER;
10100 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
10101 // Lang is defined in session or user profile, nothing to do.
10102 return;
10105 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
10106 return;
10109 // Extract and clean langs from headers.
10110 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
10111 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
10112 $rawlangs = explode(',', $rawlangs); // Convert to array.
10113 $langs = array();
10115 $order = 1.0;
10116 foreach ($rawlangs as $lang) {
10117 if (strpos($lang, ';') === false) {
10118 $langs[(string)$order] = $lang;
10119 $order = $order-0.01;
10120 } else {
10121 $parts = explode(';', $lang);
10122 $pos = strpos($parts[1], '=');
10123 $langs[substr($parts[1], $pos+1)] = $parts[0];
10126 krsort($langs, SORT_NUMERIC);
10128 // Look for such langs under standard locations.
10129 foreach ($langs as $lang) {
10130 // Clean it properly for include.
10131 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
10132 if (get_string_manager()->translation_exists($lang, false)) {
10133 // Lang exists, set it in session.
10134 $SESSION->lang = $lang;
10135 // We have finished. Go out.
10136 break;
10139 return;
10143 * Check if $url matches anything in proxybypass list
10145 * Any errors just result in the proxy being used (least bad)
10147 * @param string $url url to check
10148 * @return boolean true if we should bypass the proxy
10150 function is_proxybypass( $url ) {
10151 global $CFG;
10153 // Sanity check.
10154 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
10155 return false;
10158 // Get the host part out of the url.
10159 if (!$host = parse_url( $url, PHP_URL_HOST )) {
10160 return false;
10163 // Get the possible bypass hosts into an array.
10164 $matches = explode( ',', $CFG->proxybypass );
10166 // Check for a match.
10167 // (IPs need to match the left hand side and hosts the right of the url,
10168 // but we can recklessly check both as there can't be a false +ve).
10169 foreach ($matches as $match) {
10170 $match = trim($match);
10172 // Try for IP match (Left side).
10173 $lhs = substr($host, 0, strlen($match));
10174 if (strcasecmp($match, $lhs)==0) {
10175 return true;
10178 // Try for host match (Right side).
10179 $rhs = substr($host, -strlen($match));
10180 if (strcasecmp($match, $rhs)==0) {
10181 return true;
10185 // Nothing matched.
10186 return false;
10190 * Check if the passed navigation is of the new style
10192 * @param mixed $navigation
10193 * @return bool true for yes false for no
10195 function is_newnav($navigation) {
10196 if (is_array($navigation) && !empty($navigation['newnav'])) {
10197 return true;
10198 } else {
10199 return false;
10204 * Checks whether the given variable name is defined as a variable within the given object.
10206 * This will NOT work with stdClass objects, which have no class variables.
10208 * @param string $var The variable name
10209 * @param object $object The object to check
10210 * @return boolean
10212 function in_object_vars($var, $object) {
10213 $classvars = get_class_vars(get_class($object));
10214 $classvars = array_keys($classvars);
10215 return in_array($var, $classvars);
10219 * Returns an array without repeated objects.
10220 * This function is similar to array_unique, but for arrays that have objects as values
10222 * @param array $array
10223 * @param bool $keepkeyassoc
10224 * @return array
10226 function object_array_unique($array, $keepkeyassoc = true) {
10227 $duplicatekeys = array();
10228 $tmp = array();
10230 foreach ($array as $key => $val) {
10231 // Convert objects to arrays, in_array() does not support objects.
10232 if (is_object($val)) {
10233 $val = (array)$val;
10236 if (!in_array($val, $tmp)) {
10237 $tmp[] = $val;
10238 } else {
10239 $duplicatekeys[] = $key;
10243 foreach ($duplicatekeys as $key) {
10244 unset($array[$key]);
10247 return $keepkeyassoc ? $array : array_values($array);
10251 * Is a userid the primary administrator?
10253 * @param int $userid int id of user to check
10254 * @return boolean
10256 function is_primary_admin($userid) {
10257 $primaryadmin = get_admin();
10259 if ($userid == $primaryadmin->id) {
10260 return true;
10261 } else {
10262 return false;
10267 * Returns the site identifier
10269 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
10271 function get_site_identifier() {
10272 global $CFG;
10273 // Check to see if it is missing. If so, initialise it.
10274 if (empty($CFG->siteidentifier)) {
10275 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
10277 // Return it.
10278 return $CFG->siteidentifier;
10282 * Check whether the given password has no more than the specified
10283 * number of consecutive identical characters.
10285 * @param string $password password to be checked against the password policy
10286 * @param integer $maxchars maximum number of consecutive identical characters
10287 * @return bool
10289 function check_consecutive_identical_characters($password, $maxchars) {
10291 if ($maxchars < 1) {
10292 return true; // Zero 0 is to disable this check.
10294 if (strlen($password) <= $maxchars) {
10295 return true; // Too short to fail this test.
10298 $previouschar = '';
10299 $consecutivecount = 1;
10300 foreach (str_split($password) as $char) {
10301 if ($char != $previouschar) {
10302 $consecutivecount = 1;
10303 } else {
10304 $consecutivecount++;
10305 if ($consecutivecount > $maxchars) {
10306 return false; // Check failed already.
10310 $previouschar = $char;
10313 return true;
10317 * Helper function to do partial function binding.
10318 * so we can use it for preg_replace_callback, for example
10319 * this works with php functions, user functions, static methods and class methods
10320 * it returns you a callback that you can pass on like so:
10322 * $callback = partial('somefunction', $arg1, $arg2);
10323 * or
10324 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
10325 * or even
10326 * $obj = new someclass();
10327 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
10329 * and then the arguments that are passed through at calltime are appended to the argument list.
10331 * @param mixed $function a php callback
10332 * @param mixed $arg1,... $argv arguments to partially bind with
10333 * @return array Array callback
10335 function partial() {
10336 if (!class_exists('partial')) {
10338 * Used to manage function binding.
10339 * @copyright 2009 Penny Leach
10340 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10342 class partial{
10343 /** @var array */
10344 public $values = array();
10345 /** @var string The function to call as a callback. */
10346 public $func;
10348 * Constructor
10349 * @param string $func
10350 * @param array $args
10352 public function __construct($func, $args) {
10353 $this->values = $args;
10354 $this->func = $func;
10357 * Calls the callback function.
10358 * @return mixed
10360 public function method() {
10361 $args = func_get_args();
10362 return call_user_func_array($this->func, array_merge($this->values, $args));
10366 $args = func_get_args();
10367 $func = array_shift($args);
10368 $p = new partial($func, $args);
10369 return array($p, 'method');
10373 * helper function to load up and initialise the mnet environment
10374 * this must be called before you use mnet functions.
10376 * @return mnet_environment the equivalent of old $MNET global
10378 function get_mnet_environment() {
10379 global $CFG;
10380 require_once($CFG->dirroot . '/mnet/lib.php');
10381 static $instance = null;
10382 if (empty($instance)) {
10383 $instance = new mnet_environment();
10384 $instance->init();
10386 return $instance;
10390 * during xmlrpc server code execution, any code wishing to access
10391 * information about the remote peer must use this to get it.
10393 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
10395 function get_mnet_remote_client() {
10396 if (!defined('MNET_SERVER')) {
10397 debugging(get_string('notinxmlrpcserver', 'mnet'));
10398 return false;
10400 global $MNET_REMOTE_CLIENT;
10401 if (isset($MNET_REMOTE_CLIENT)) {
10402 return $MNET_REMOTE_CLIENT;
10404 return false;
10408 * during the xmlrpc server code execution, this will be called
10409 * to setup the object returned by {@link get_mnet_remote_client}
10411 * @param mnet_remote_client $client the client to set up
10412 * @throws moodle_exception
10414 function set_mnet_remote_client($client) {
10415 if (!defined('MNET_SERVER')) {
10416 throw new moodle_exception('notinxmlrpcserver', 'mnet');
10418 global $MNET_REMOTE_CLIENT;
10419 $MNET_REMOTE_CLIENT = $client;
10423 * return the jump url for a given remote user
10424 * this is used for rewriting forum post links in emails, etc
10426 * @param stdclass $user the user to get the idp url for
10428 function mnet_get_idp_jump_url($user) {
10429 global $CFG;
10431 static $mnetjumps = array();
10432 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
10433 $idp = mnet_get_peer_host($user->mnethostid);
10434 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
10435 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
10437 return $mnetjumps[$user->mnethostid];
10441 * Gets the homepage to use for the current user
10443 * @return int One of HOMEPAGE_*
10445 function get_home_page() {
10446 global $CFG;
10448 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
10449 // If dashboard is disabled, home will be set to default page.
10450 $defaultpage = get_default_home_page();
10451 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
10452 if (!empty($CFG->enabledashboard)) {
10453 return HOMEPAGE_MY;
10454 } else {
10455 return $defaultpage;
10457 } else if ($CFG->defaulthomepage == HOMEPAGE_MYCOURSES) {
10458 return HOMEPAGE_MYCOURSES;
10459 } else {
10460 $userhomepage = (int) get_user_preferences('user_home_page_preference', $defaultpage);
10461 if (empty($CFG->enabledashboard) && $userhomepage == HOMEPAGE_MY) {
10462 // If the user was using the dashboard but it's disabled, return the default home page.
10463 $userhomepage = $defaultpage;
10465 return $userhomepage;
10468 return HOMEPAGE_SITE;
10472 * Returns the default home page to display if current one is not defined or can't be applied.
10473 * The default behaviour is to return Dashboard if it's enabled or My courses page if it isn't.
10475 * @return int The default home page.
10477 function get_default_home_page(): int {
10478 global $CFG;
10480 return !empty($CFG->enabledashboard) ? HOMEPAGE_MY : HOMEPAGE_MYCOURSES;
10484 * Gets the name of a course to be displayed when showing a list of courses.
10485 * By default this is just $course->fullname but user can configure it. The
10486 * result of this function should be passed through print_string.
10487 * @param stdClass|core_course_list_element $course Moodle course object
10488 * @return string Display name of course (either fullname or short + fullname)
10490 function get_course_display_name_for_list($course) {
10491 global $CFG;
10492 if (!empty($CFG->courselistshortnames)) {
10493 if (!($course instanceof stdClass)) {
10494 $course = (object)convert_to_array($course);
10496 return get_string('courseextendednamedisplay', '', $course);
10497 } else {
10498 return $course->fullname;
10503 * Safe analogue of unserialize() that can only parse arrays
10505 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
10506 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
10507 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
10509 * @param string $expression
10510 * @return array|bool either parsed array or false if parsing was impossible.
10512 function unserialize_array($expression) {
10513 $subs = [];
10514 // Find nested arrays, parse them and store in $subs , substitute with special string.
10515 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
10516 $key = '--SUB' . count($subs) . '--';
10517 $subs[$key] = unserialize_array($matches[2]);
10518 if ($subs[$key] === false) {
10519 return false;
10521 $expression = str_replace($matches[2], $key . ';', $expression);
10524 // Check the expression is an array.
10525 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
10526 return false;
10528 // Get the size and elements of an array (key;value;key;value;....).
10529 $parts = explode(';', $matches1[2]);
10530 $size = intval($matches1[1]);
10531 if (count($parts) < $size * 2 + 1) {
10532 return false;
10534 // Analyze each part and make sure it is an integer or string or a substitute.
10535 $value = [];
10536 for ($i = 0; $i < $size * 2; $i++) {
10537 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
10538 $parts[$i] = (int)$matches2[1];
10539 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
10540 $parts[$i] = $matches3[2];
10541 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
10542 $parts[$i] = $subs[$parts[$i]];
10543 } else {
10544 return false;
10547 // Combine keys and values.
10548 for ($i = 0; $i < $size * 2; $i += 2) {
10549 $value[$parts[$i]] = $parts[$i+1];
10551 return $value;
10555 * Safe method for unserializing given input that is expected to contain only a serialized instance of an stdClass object
10557 * If any class type other than stdClass is included in the input string, it will not be instantiated and will be cast to an
10558 * stdClass object. The initial cast to array, then back to object is to ensure we are always returning the correct type,
10559 * otherwise we would return an instances of {@see __PHP_Incomplete_class} for malformed strings
10561 * @param string $input
10562 * @return stdClass
10564 function unserialize_object(string $input): stdClass {
10565 $instance = (array) unserialize($input, ['allowed_classes' => [stdClass::class]]);
10566 return (object) $instance;
10570 * The lang_string class
10572 * This special class is used to create an object representation of a string request.
10573 * It is special because processing doesn't occur until the object is first used.
10574 * The class was created especially to aid performance in areas where strings were
10575 * required to be generated but were not necessarily used.
10576 * As an example the admin tree when generated uses over 1500 strings, of which
10577 * normally only 1/3 are ever actually printed at any time.
10578 * The performance advantage is achieved by not actually processing strings that
10579 * arn't being used, as such reducing the processing required for the page.
10581 * How to use the lang_string class?
10582 * There are two methods of using the lang_string class, first through the
10583 * forth argument of the get_string function, and secondly directly.
10584 * The following are examples of both.
10585 * 1. Through get_string calls e.g.
10586 * $string = get_string($identifier, $component, $a, true);
10587 * $string = get_string('yes', 'moodle', null, true);
10588 * 2. Direct instantiation
10589 * $string = new lang_string($identifier, $component, $a, $lang);
10590 * $string = new lang_string('yes');
10592 * How do I use a lang_string object?
10593 * The lang_string object makes use of a magic __toString method so that you
10594 * are able to use the object exactly as you would use a string in most cases.
10595 * This means you are able to collect it into a variable and then directly
10596 * echo it, or concatenate it into another string, or similar.
10597 * The other thing you can do is manually get the string by calling the
10598 * lang_strings out method e.g.
10599 * $string = new lang_string('yes');
10600 * $string->out();
10601 * Also worth noting is that the out method can take one argument, $lang which
10602 * allows the developer to change the language on the fly.
10604 * When should I use a lang_string object?
10605 * The lang_string object is designed to be used in any situation where a
10606 * string may not be needed, but needs to be generated.
10607 * The admin tree is a good example of where lang_string objects should be
10608 * used.
10609 * A more practical example would be any class that requries strings that may
10610 * not be printed (after all classes get renderer by renderers and who knows
10611 * what they will do ;))
10613 * When should I not use a lang_string object?
10614 * Don't use lang_strings when you are going to use a string immediately.
10615 * There is no need as it will be processed immediately and there will be no
10616 * advantage, and in fact perhaps a negative hit as a class has to be
10617 * instantiated for a lang_string object, however get_string won't require
10618 * that.
10620 * Limitations:
10621 * 1. You cannot use a lang_string object as an array offset. Doing so will
10622 * result in PHP throwing an error. (You can use it as an object property!)
10624 * @package core
10625 * @category string
10626 * @copyright 2011 Sam Hemelryk
10627 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10629 class lang_string {
10631 /** @var string The strings identifier */
10632 protected $identifier;
10633 /** @var string The strings component. Default '' */
10634 protected $component = '';
10635 /** @var array|stdClass Any arguments required for the string. Default null */
10636 protected $a = null;
10637 /** @var string The language to use when processing the string. Default null */
10638 protected $lang = null;
10640 /** @var string The processed string (once processed) */
10641 protected $string = null;
10644 * A special boolean. If set to true then the object has been woken up and
10645 * cannot be regenerated. If this is set then $this->string MUST be used.
10646 * @var bool
10648 protected $forcedstring = false;
10651 * Constructs a lang_string object
10653 * This function should do as little processing as possible to ensure the best
10654 * performance for strings that won't be used.
10656 * @param string $identifier The strings identifier
10657 * @param string $component The strings component
10658 * @param stdClass|array $a Any arguments the string requires
10659 * @param string $lang The language to use when processing the string.
10660 * @throws coding_exception
10662 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10663 if (empty($component)) {
10664 $component = 'moodle';
10667 $this->identifier = $identifier;
10668 $this->component = $component;
10669 $this->lang = $lang;
10671 // We MUST duplicate $a to ensure that it if it changes by reference those
10672 // changes are not carried across.
10673 // To do this we always ensure $a or its properties/values are strings
10674 // and that any properties/values that arn't convertable are forgotten.
10675 if ($a !== null) {
10676 if (is_scalar($a)) {
10677 $this->a = $a;
10678 } else if ($a instanceof lang_string) {
10679 $this->a = $a->out();
10680 } else if (is_object($a) or is_array($a)) {
10681 $a = (array)$a;
10682 $this->a = array();
10683 foreach ($a as $key => $value) {
10684 // Make sure conversion errors don't get displayed (results in '').
10685 if (is_array($value)) {
10686 $this->a[$key] = '';
10687 } else if (is_object($value)) {
10688 if (method_exists($value, '__toString')) {
10689 $this->a[$key] = $value->__toString();
10690 } else {
10691 $this->a[$key] = '';
10693 } else {
10694 $this->a[$key] = (string)$value;
10700 if (debugging(false, DEBUG_DEVELOPER)) {
10701 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10702 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10704 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10705 throw new coding_exception('Invalid string compontent. Please check your string definition');
10707 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10708 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10714 * Processes the string.
10716 * This function actually processes the string, stores it in the string property
10717 * and then returns it.
10718 * You will notice that this function is VERY similar to the get_string method.
10719 * That is because it is pretty much doing the same thing.
10720 * However as this function is an upgrade it isn't as tolerant to backwards
10721 * compatibility.
10723 * @return string
10724 * @throws coding_exception
10726 protected function get_string() {
10727 global $CFG;
10729 // Check if we need to process the string.
10730 if ($this->string === null) {
10731 // Check the quality of the identifier.
10732 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10733 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);
10736 // Process the string.
10737 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10738 // Debugging feature lets you display string identifier and component.
10739 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10740 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10743 // Return the string.
10744 return $this->string;
10748 * Returns the string
10750 * @param string $lang The langauge to use when processing the string
10751 * @return string
10753 public function out($lang = null) {
10754 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10755 if ($this->forcedstring) {
10756 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10757 return $this->get_string();
10759 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10760 return $translatedstring->out();
10762 return $this->get_string();
10766 * Magic __toString method for printing a string
10768 * @return string
10770 public function __toString() {
10771 return $this->get_string();
10775 * Magic __set_state method used for var_export
10777 * @param array $array
10778 * @return self
10780 public static function __set_state(array $array): self {
10781 $tmp = new lang_string($array['identifier'], $array['component'], $array['a'], $array['lang']);
10782 $tmp->string = $array['string'];
10783 $tmp->forcedstring = $array['forcedstring'];
10784 return $tmp;
10788 * Prepares the lang_string for sleep and stores only the forcedstring and
10789 * string properties... the string cannot be regenerated so we need to ensure
10790 * it is generated for this.
10792 * @return string
10794 public function __sleep() {
10795 $this->get_string();
10796 $this->forcedstring = true;
10797 return array('forcedstring', 'string', 'lang');
10801 * Returns the identifier.
10803 * @return string
10805 public function get_identifier() {
10806 return $this->identifier;
10810 * Returns the component.
10812 * @return string
10814 public function get_component() {
10815 return $this->component;
10820 * Get human readable name describing the given callable.
10822 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10823 * It does not check if the callable actually exists.
10825 * @param callable|string|array $callable
10826 * @return string|bool Human readable name of callable, or false if not a valid callable.
10828 function get_callable_name($callable) {
10830 if (!is_callable($callable, true, $name)) {
10831 return false;
10833 } else {
10834 return $name;
10839 * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10840 * Never put your faith on this function and rely on its accuracy as there might be false positives.
10841 * It just performs some simple checks, and mainly is used for places where we want to hide some options
10842 * such as site registration when $CFG->wwwroot is not publicly accessible.
10843 * Good thing is there is no false negative.
10844 * Note that it's possible to force the result of this check by specifying $CFG->site_is_public in config.php
10846 * @return bool
10848 function site_is_public() {
10849 global $CFG;
10851 // Return early if site admin has forced this setting.
10852 if (isset($CFG->site_is_public)) {
10853 return (bool)$CFG->site_is_public;
10856 $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
10858 if ($host === 'localhost' || preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10859 $ispublic = false;
10860 } else if (\core\ip_utils::is_ip_address($host) && !ip_is_public($host)) {
10861 $ispublic = false;
10862 } else if (($address = \core\ip_utils::get_ip_address($host)) && !ip_is_public($address)) {
10863 $ispublic = false;
10864 } else {
10865 $ispublic = true;
10868 return $ispublic;