Merge branch 'MDL-73076-master' of https://github.com/lameze/moodle
[moodle.git] / lib / moodlelib.php
blobd555ca6f7a87fc0ca957a5e54caef91c92f1059a
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 $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 = null, $type, $recursive = false) {
796 // Convert null to empty array.
797 $param = (array)$param;
798 foreach ($param as $key => $value) {
799 if (is_array($value)) {
800 if ($recursive) {
801 $param[$key] = clean_param_array($value, $type, true);
802 } else {
803 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
805 } else {
806 $param[$key] = clean_param($value, $type);
809 return $param;
813 * Used by {@link optional_param()} and {@link required_param()} to
814 * clean the variables and/or cast to specific types, based on
815 * an options field.
816 * <code>
817 * $course->format = clean_param($course->format, PARAM_ALPHA);
818 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
819 * </code>
821 * @param mixed $param the variable we are cleaning
822 * @param string $type expected format of param after cleaning.
823 * @return mixed
824 * @throws coding_exception
826 function clean_param($param, $type) {
827 global $CFG;
829 if (is_array($param)) {
830 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
831 } else if (is_object($param)) {
832 if (method_exists($param, '__toString')) {
833 $param = $param->__toString();
834 } else {
835 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
839 switch ($type) {
840 case PARAM_RAW:
841 // No cleaning at all.
842 $param = fix_utf8($param);
843 return $param;
845 case PARAM_RAW_TRIMMED:
846 // No cleaning, but strip leading and trailing whitespace.
847 $param = fix_utf8($param);
848 return trim($param);
850 case PARAM_CLEAN:
851 // General HTML cleaning, try to use more specific type if possible this is deprecated!
852 // Please use more specific type instead.
853 if (is_numeric($param)) {
854 return $param;
856 $param = fix_utf8($param);
857 // Sweep for scripts, etc.
858 return clean_text($param);
860 case PARAM_CLEANHTML:
861 // Clean html fragment.
862 $param = fix_utf8($param);
863 // Sweep for scripts, etc.
864 $param = clean_text($param, FORMAT_HTML);
865 return trim($param);
867 case PARAM_INT:
868 // Convert to integer.
869 return (int)$param;
871 case PARAM_FLOAT:
872 // Convert to float.
873 return (float)$param;
875 case PARAM_LOCALISEDFLOAT:
876 // Convert to float.
877 return unformat_float($param, true);
879 case PARAM_ALPHA:
880 // Remove everything not `a-z`.
881 return preg_replace('/[^a-zA-Z]/i', '', $param);
883 case PARAM_ALPHAEXT:
884 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
885 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
887 case PARAM_ALPHANUM:
888 // Remove everything not `a-zA-Z0-9`.
889 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
891 case PARAM_ALPHANUMEXT:
892 // Remove everything not `a-zA-Z0-9_-`.
893 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
895 case PARAM_SEQUENCE:
896 // Remove everything not `0-9,`.
897 return preg_replace('/[^0-9,]/i', '', $param);
899 case PARAM_BOOL:
900 // Convert to 1 or 0.
901 $tempstr = strtolower($param);
902 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
903 $param = 1;
904 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
905 $param = 0;
906 } else {
907 $param = empty($param) ? 0 : 1;
909 return $param;
911 case PARAM_NOTAGS:
912 // Strip all tags.
913 $param = fix_utf8($param);
914 return strip_tags($param);
916 case PARAM_TEXT:
917 // Leave only tags needed for multilang.
918 $param = fix_utf8($param);
919 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
920 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
921 do {
922 if (strpos($param, '</lang>') !== false) {
923 // Old and future mutilang syntax.
924 $param = strip_tags($param, '<lang>');
925 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
926 break;
928 $open = false;
929 foreach ($matches[0] as $match) {
930 if ($match === '</lang>') {
931 if ($open) {
932 $open = false;
933 continue;
934 } else {
935 break 2;
938 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
939 break 2;
940 } else {
941 $open = true;
944 if ($open) {
945 break;
947 return $param;
949 } else if (strpos($param, '</span>') !== false) {
950 // Current problematic multilang syntax.
951 $param = strip_tags($param, '<span>');
952 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
953 break;
955 $open = false;
956 foreach ($matches[0] as $match) {
957 if ($match === '</span>') {
958 if ($open) {
959 $open = false;
960 continue;
961 } else {
962 break 2;
965 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
966 break 2;
967 } else {
968 $open = true;
971 if ($open) {
972 break;
974 return $param;
976 } while (false);
977 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
978 return strip_tags($param);
980 case PARAM_COMPONENT:
981 // We do not want any guessing here, either the name is correct or not
982 // please note only normalised component names are accepted.
983 if (!preg_match('/^[a-z][a-z0-9]*(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
984 return '';
986 if (strpos($param, '__') !== false) {
987 return '';
989 if (strpos($param, 'mod_') === 0) {
990 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
991 if (substr_count($param, '_') != 1) {
992 return '';
995 return $param;
997 case PARAM_PLUGIN:
998 case PARAM_AREA:
999 // We do not want any guessing here, either the name is correct or not.
1000 if (!is_valid_plugin_name($param)) {
1001 return '';
1003 return $param;
1005 case PARAM_SAFEDIR:
1006 // Remove everything not a-zA-Z0-9_- .
1007 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
1009 case PARAM_SAFEPATH:
1010 // Remove everything not a-zA-Z0-9/_- .
1011 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
1013 case PARAM_FILE:
1014 // Strip all suspicious characters from filename.
1015 $param = fix_utf8($param);
1016 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
1017 if ($param === '.' || $param === '..') {
1018 $param = '';
1020 return $param;
1022 case PARAM_PATH:
1023 // Strip all suspicious characters from file path.
1024 $param = fix_utf8($param);
1025 $param = str_replace('\\', '/', $param);
1027 // Explode the path and clean each element using the PARAM_FILE rules.
1028 $breadcrumb = explode('/', $param);
1029 foreach ($breadcrumb as $key => $crumb) {
1030 if ($crumb === '.' && $key === 0) {
1031 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1032 } else {
1033 $crumb = clean_param($crumb, PARAM_FILE);
1035 $breadcrumb[$key] = $crumb;
1037 $param = implode('/', $breadcrumb);
1039 // Remove multiple current path (./././) and multiple slashes (///).
1040 $param = preg_replace('~//+~', '/', $param);
1041 $param = preg_replace('~/(\./)+~', '/', $param);
1042 return $param;
1044 case PARAM_HOST:
1045 // Allow FQDN or IPv4 dotted quad.
1046 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1047 // Match ipv4 dotted quad.
1048 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1049 // Confirm values are ok.
1050 if ( $match[0] > 255
1051 || $match[1] > 255
1052 || $match[3] > 255
1053 || $match[4] > 255 ) {
1054 // Hmmm, what kind of dotted quad is this?
1055 $param = '';
1057 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1058 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1059 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1061 // All is ok - $param is respected.
1062 } else {
1063 // All is not ok...
1064 $param='';
1066 return $param;
1068 case PARAM_URL:
1069 // Allow safe urls.
1070 $param = fix_utf8($param);
1071 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1072 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1073 // All is ok, param is respected.
1074 } else {
1075 // Not really ok.
1076 $param ='';
1078 return $param;
1080 case PARAM_LOCALURL:
1081 // Allow http absolute, root relative and relative URLs within wwwroot.
1082 $param = clean_param($param, PARAM_URL);
1083 if (!empty($param)) {
1085 if ($param === $CFG->wwwroot) {
1086 // Exact match;
1087 } else if (preg_match(':^/:', $param)) {
1088 // Root-relative, ok!
1089 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1090 // Absolute, and matches our wwwroot.
1091 } else {
1092 // Relative - let's make sure there are no tricks.
1093 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1094 // Looks ok.
1095 } else {
1096 $param = '';
1100 return $param;
1102 case PARAM_PEM:
1103 $param = trim($param);
1104 // PEM formatted strings may contain letters/numbers and the symbols:
1105 // forward slash: /
1106 // plus sign: +
1107 // equal sign: =
1108 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1109 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1110 list($wholething, $body) = $matches;
1111 unset($wholething, $matches);
1112 $b64 = clean_param($body, PARAM_BASE64);
1113 if (!empty($b64)) {
1114 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1115 } else {
1116 return '';
1119 return '';
1121 case PARAM_BASE64:
1122 if (!empty($param)) {
1123 // PEM formatted strings may contain letters/numbers and the symbols
1124 // forward slash: /
1125 // plus sign: +
1126 // equal sign: =.
1127 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1128 return '';
1130 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1131 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1132 // than (or equal to) 64 characters long.
1133 for ($i=0, $j=count($lines); $i < $j; $i++) {
1134 if ($i + 1 == $j) {
1135 if (64 < strlen($lines[$i])) {
1136 return '';
1138 continue;
1141 if (64 != strlen($lines[$i])) {
1142 return '';
1145 return implode("\n", $lines);
1146 } else {
1147 return '';
1150 case PARAM_TAG:
1151 $param = fix_utf8($param);
1152 // Please note it is not safe to use the tag name directly anywhere,
1153 // it must be processed with s(), urlencode() before embedding anywhere.
1154 // Remove some nasties.
1155 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1156 // Convert many whitespace chars into one.
1157 $param = preg_replace('/\s+/u', ' ', $param);
1158 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1159 return $param;
1161 case PARAM_TAGLIST:
1162 $param = fix_utf8($param);
1163 $tags = explode(',', $param);
1164 $result = array();
1165 foreach ($tags as $tag) {
1166 $res = clean_param($tag, PARAM_TAG);
1167 if ($res !== '') {
1168 $result[] = $res;
1171 if ($result) {
1172 return implode(',', $result);
1173 } else {
1174 return '';
1177 case PARAM_CAPABILITY:
1178 if (get_capability_info($param)) {
1179 return $param;
1180 } else {
1181 return '';
1184 case PARAM_PERMISSION:
1185 $param = (int)$param;
1186 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1187 return $param;
1188 } else {
1189 return CAP_INHERIT;
1192 case PARAM_AUTH:
1193 $param = clean_param($param, PARAM_PLUGIN);
1194 if (empty($param)) {
1195 return '';
1196 } else if (exists_auth_plugin($param)) {
1197 return $param;
1198 } else {
1199 return '';
1202 case PARAM_LANG:
1203 $param = clean_param($param, PARAM_SAFEDIR);
1204 if (get_string_manager()->translation_exists($param)) {
1205 return $param;
1206 } else {
1207 // Specified language is not installed or param malformed.
1208 return '';
1211 case PARAM_THEME:
1212 $param = clean_param($param, PARAM_PLUGIN);
1213 if (empty($param)) {
1214 return '';
1215 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1216 return $param;
1217 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1218 return $param;
1219 } else {
1220 // Specified theme is not installed.
1221 return '';
1224 case PARAM_USERNAME:
1225 $param = fix_utf8($param);
1226 $param = trim($param);
1227 // Convert uppercase to lowercase MDL-16919.
1228 $param = core_text::strtolower($param);
1229 if (empty($CFG->extendedusernamechars)) {
1230 $param = str_replace(" " , "", $param);
1231 // Regular expression, eliminate all chars EXCEPT:
1232 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1233 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1235 return $param;
1237 case PARAM_EMAIL:
1238 $param = fix_utf8($param);
1239 if (validate_email($param)) {
1240 return $param;
1241 } else {
1242 return '';
1245 case PARAM_STRINGID:
1246 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1247 return $param;
1248 } else {
1249 return '';
1252 case PARAM_TIMEZONE:
1253 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1254 $param = fix_utf8($param);
1255 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1256 if (preg_match($timezonepattern, $param)) {
1257 return $param;
1258 } else {
1259 return '';
1262 default:
1263 // Doh! throw error, switched parameters in optional_param or another serious problem.
1264 throw new \moodle_exception("unknownparamtype", '', '', $type);
1269 * Whether the PARAM_* type is compatible in RTL.
1271 * Being compatible with RTL means that the data they contain can flow
1272 * from right-to-left or left-to-right without compromising the user experience.
1274 * Take URLs for example, they are not RTL compatible as they should always
1275 * flow from the left to the right. This also applies to numbers, email addresses,
1276 * configuration snippets, base64 strings, etc...
1278 * This function tries to best guess which parameters can contain localised strings.
1280 * @param string $paramtype Constant PARAM_*.
1281 * @return bool
1283 function is_rtl_compatible($paramtype) {
1284 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1288 * Makes sure the data is using valid utf8, invalid characters are discarded.
1290 * Note: this function is not intended for full objects with methods and private properties.
1292 * @param mixed $value
1293 * @return mixed with proper utf-8 encoding
1295 function fix_utf8($value) {
1296 if (is_null($value) or $value === '') {
1297 return $value;
1299 } else if (is_string($value)) {
1300 if ((string)(int)$value === $value) {
1301 // Shortcut.
1302 return $value;
1304 // No null bytes expected in our data, so let's remove it.
1305 $value = str_replace("\0", '', $value);
1307 // Note: this duplicates min_fix_utf8() intentionally.
1308 static $buggyiconv = null;
1309 if ($buggyiconv === null) {
1310 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1313 if ($buggyiconv) {
1314 if (function_exists('mb_convert_encoding')) {
1315 $subst = mb_substitute_character();
1316 mb_substitute_character('none');
1317 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1318 mb_substitute_character($subst);
1320 } else {
1321 // Warn admins on admin/index.php page.
1322 $result = $value;
1325 } else {
1326 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1329 return $result;
1331 } else if (is_array($value)) {
1332 foreach ($value as $k => $v) {
1333 $value[$k] = fix_utf8($v);
1335 return $value;
1337 } else if (is_object($value)) {
1338 // Do not modify original.
1339 $value = clone($value);
1340 foreach ($value as $k => $v) {
1341 $value->$k = fix_utf8($v);
1343 return $value;
1345 } else {
1346 // This is some other type, no utf-8 here.
1347 return $value;
1352 * Return true if given value is integer or string with integer value
1354 * @param mixed $value String or Int
1355 * @return bool true if number, false if not
1357 function is_number($value) {
1358 if (is_int($value)) {
1359 return true;
1360 } else if (is_string($value)) {
1361 return ((string)(int)$value) === $value;
1362 } else {
1363 return false;
1368 * Returns host part from url.
1370 * @param string $url full url
1371 * @return string host, null if not found
1373 function get_host_from_url($url) {
1374 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1375 if ($matches) {
1376 return $matches[1];
1378 return null;
1382 * Tests whether anything was returned by text editor
1384 * This function is useful for testing whether something you got back from
1385 * the HTML editor actually contains anything. Sometimes the HTML editor
1386 * appear to be empty, but actually you get back a <br> tag or something.
1388 * @param string $string a string containing HTML.
1389 * @return boolean does the string contain any actual content - that is text,
1390 * images, objects, etc.
1392 function html_is_blank($string) {
1393 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1397 * Set a key in global configuration
1399 * Set a key/value pair in both this session's {@link $CFG} global variable
1400 * and in the 'config' database table for future sessions.
1402 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1403 * In that case it doesn't affect $CFG.
1405 * A NULL value will delete the entry.
1407 * NOTE: this function is called from lib/db/upgrade.php
1409 * @param string $name the key to set
1410 * @param string $value the value to set (without magic quotes)
1411 * @param string $plugin (optional) the plugin scope, default null
1412 * @return bool true or exception
1414 function set_config($name, $value, $plugin = null) {
1415 global $CFG, $DB;
1417 // Redirect to appropriate handler when value is null.
1418 if ($value === null) {
1419 return unset_config($name, $plugin);
1422 // Set variables determining conditions and where to store the new config.
1423 // Plugin config goes to {config_plugins}, core config goes to {config}.
1424 $iscore = empty($plugin);
1425 if ($iscore) {
1426 // If it's for core config.
1427 $table = 'config';
1428 $conditions = ['name' => $name];
1429 $invalidatecachekey = 'core';
1430 } else {
1431 // If it's a plugin.
1432 $table = 'config_plugins';
1433 $conditions = ['name' => $name, 'plugin' => $plugin];
1434 $invalidatecachekey = $plugin;
1437 // DB handling - checks for existing config, updating or inserting only if necessary.
1438 $invalidatecache = true;
1439 $inserted = false;
1440 $record = $DB->get_record($table, $conditions, 'id, value');
1441 if ($record === false) {
1442 // Inserts a new config record.
1443 $config = new stdClass();
1444 $config->name = $name;
1445 $config->value = $value;
1446 if (!$iscore) {
1447 $config->plugin = $plugin;
1449 $inserted = $DB->insert_record($table, $config, false);
1450 } else if ($invalidatecache = ($record->value !== $value)) {
1451 // Record exists - Check and only set new value if it has changed.
1452 $DB->set_field($table, 'value', $value, ['id' => $record->id]);
1455 if ($iscore && !isset($CFG->config_php_settings[$name])) {
1456 // So it's defined for this invocation at least.
1457 // Settings from db are always strings.
1458 $CFG->$name = (string) $value;
1461 // When setting config during a Behat test (in the CLI script, not in the web browser
1462 // requests), remember which ones are set so that we can clear them later.
1463 if ($iscore && $inserted && defined('BEHAT_TEST')) {
1464 $CFG->behat_cli_added_config[$name] = true;
1467 // Update siteidentifier cache, if required.
1468 if ($iscore && $name === 'siteidentifier') {
1469 cache_helper::update_site_identifier($value);
1472 // Invalidate cache, if required.
1473 if ($invalidatecache) {
1474 cache_helper::invalidate_by_definition('core', 'config', [], $invalidatecachekey);
1477 return true;
1481 * Get configuration values from the global config table
1482 * or the config_plugins table.
1484 * If called with one parameter, it will load all the config
1485 * variables for one plugin, and return them as an object.
1487 * If called with 2 parameters it will return a string single
1488 * value or false if the value is not found.
1490 * NOTE: this function is called from lib/db/upgrade.php
1492 * @param string $plugin full component name
1493 * @param string $name default null
1494 * @return mixed hash-like object or single value, return false no config found
1495 * @throws dml_exception
1497 function get_config($plugin, $name = null) {
1498 global $CFG, $DB;
1500 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1501 $forced =& $CFG->config_php_settings;
1502 $iscore = true;
1503 $plugin = 'core';
1504 } else {
1505 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1506 $forced =& $CFG->forced_plugin_settings[$plugin];
1507 } else {
1508 $forced = array();
1510 $iscore = false;
1513 if (!isset($CFG->siteidentifier)) {
1514 try {
1515 // This may throw an exception during installation, which is how we detect the
1516 // need to install the database. For more details see {@see initialise_cfg()}.
1517 $CFG->siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1518 } catch (dml_exception $ex) {
1519 // Set siteidentifier to false. We don't want to trip this continually.
1520 $siteidentifier = false;
1521 throw $ex;
1525 if (!empty($name)) {
1526 if (array_key_exists($name, $forced)) {
1527 return (string)$forced[$name];
1528 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1529 return $CFG->siteidentifier;
1533 $cache = cache::make('core', 'config');
1534 $result = $cache->get($plugin);
1535 if ($result === false) {
1536 // The user is after a recordset.
1537 if (!$iscore) {
1538 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1539 } else {
1540 // This part is not really used any more, but anyway...
1541 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1543 $cache->set($plugin, $result);
1546 if (!empty($name)) {
1547 if (array_key_exists($name, $result)) {
1548 return $result[$name];
1550 return false;
1553 if ($plugin === 'core') {
1554 $result['siteidentifier'] = $CFG->siteidentifier;
1557 foreach ($forced as $key => $value) {
1558 if (is_null($value) or is_array($value) or is_object($value)) {
1559 // We do not want any extra mess here, just real settings that could be saved in db.
1560 unset($result[$key]);
1561 } else {
1562 // Convert to string as if it went through the DB.
1563 $result[$key] = (string)$value;
1567 return (object)$result;
1571 * Removes a key from global configuration.
1573 * NOTE: this function is called from lib/db/upgrade.php
1575 * @param string $name the key to set
1576 * @param string $plugin (optional) the plugin scope
1577 * @return boolean whether the operation succeeded.
1579 function unset_config($name, $plugin=null) {
1580 global $CFG, $DB;
1582 if (empty($plugin)) {
1583 unset($CFG->$name);
1584 $DB->delete_records('config', array('name' => $name));
1585 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1586 } else {
1587 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1588 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1591 return true;
1595 * Remove all the config variables for a given plugin.
1597 * NOTE: this function is called from lib/db/upgrade.php
1599 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1600 * @return boolean whether the operation succeeded.
1602 function unset_all_config_for_plugin($plugin) {
1603 global $DB;
1604 // Delete from the obvious config_plugins first.
1605 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1606 // Next delete any suspect settings from config.
1607 $like = $DB->sql_like('name', '?', true, true, false, '|');
1608 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1609 $DB->delete_records_select('config', $like, $params);
1610 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1611 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1613 return true;
1617 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1619 * All users are verified if they still have the necessary capability.
1621 * @param string $value the value of the config setting.
1622 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1623 * @param bool $includeadmins include administrators.
1624 * @return array of user objects.
1626 function get_users_from_config($value, $capability, $includeadmins = true) {
1627 if (empty($value) or $value === '$@NONE@$') {
1628 return array();
1631 // We have to make sure that users still have the necessary capability,
1632 // it should be faster to fetch them all first and then test if they are present
1633 // instead of validating them one-by-one.
1634 $users = get_users_by_capability(context_system::instance(), $capability);
1635 if ($includeadmins) {
1636 $admins = get_admins();
1637 foreach ($admins as $admin) {
1638 $users[$admin->id] = $admin;
1642 if ($value === '$@ALL@$') {
1643 return $users;
1646 $result = array(); // Result in correct order.
1647 $allowed = explode(',', $value);
1648 foreach ($allowed as $uid) {
1649 if (isset($users[$uid])) {
1650 $user = $users[$uid];
1651 $result[$user->id] = $user;
1655 return $result;
1660 * Invalidates browser caches and cached data in temp.
1662 * @return void
1664 function purge_all_caches() {
1665 purge_caches();
1669 * Selectively invalidate different types of cache.
1671 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1672 * areas alone or in combination.
1674 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1675 * 'muc' Purge MUC caches?
1676 * 'theme' Purge theme cache?
1677 * 'lang' Purge language string cache?
1678 * 'js' Purge javascript cache?
1679 * 'filter' Purge text filter cache?
1680 * 'other' Purge all other caches?
1682 function purge_caches($options = []) {
1683 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1684 if (empty(array_filter($options))) {
1685 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1686 } else {
1687 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1689 if ($options['muc']) {
1690 cache_helper::purge_all();
1692 if ($options['theme']) {
1693 theme_reset_all_caches();
1695 if ($options['lang']) {
1696 get_string_manager()->reset_caches();
1698 if ($options['js']) {
1699 js_reset_all_caches();
1701 if ($options['template']) {
1702 template_reset_all_caches();
1704 if ($options['filter']) {
1705 reset_text_filters_cache();
1707 if ($options['other']) {
1708 purge_other_caches();
1713 * Purge all non-MUC caches not otherwise purged in purge_caches.
1715 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1716 * {@link phpunit_util::reset_dataroot()}
1718 function purge_other_caches() {
1719 global $DB, $CFG;
1720 if (class_exists('core_plugin_manager')) {
1721 core_plugin_manager::reset_caches();
1724 // Bump up cacherev field for all courses.
1725 try {
1726 increment_revision_number('course', 'cacherev', '');
1727 } catch (moodle_exception $e) {
1728 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1731 $DB->reset_caches();
1733 // Purge all other caches: rss, simplepie, etc.
1734 clearstatcache();
1735 remove_dir($CFG->cachedir.'', true);
1737 // Make sure cache dir is writable, throws exception if not.
1738 make_cache_directory('');
1740 // This is the only place where we purge local caches, we are only adding files there.
1741 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1742 remove_dir($CFG->localcachedir, true);
1743 set_config('localcachedirpurged', time());
1744 make_localcache_directory('', true);
1745 \core\task\manager::clear_static_caches();
1749 * Get volatile flags
1751 * @param string $type
1752 * @param int $changedsince default null
1753 * @return array records array
1755 function get_cache_flags($type, $changedsince = null) {
1756 global $DB;
1758 $params = array('type' => $type, 'expiry' => time());
1759 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1760 if ($changedsince !== null) {
1761 $params['changedsince'] = $changedsince;
1762 $sqlwhere .= " AND timemodified > :changedsince";
1764 $cf = array();
1765 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1766 foreach ($flags as $flag) {
1767 $cf[$flag->name] = $flag->value;
1770 return $cf;
1774 * Get volatile flags
1776 * @param string $type
1777 * @param string $name
1778 * @param int $changedsince default null
1779 * @return string|false The cache flag value or false
1781 function get_cache_flag($type, $name, $changedsince=null) {
1782 global $DB;
1784 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1786 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1787 if ($changedsince !== null) {
1788 $params['changedsince'] = $changedsince;
1789 $sqlwhere .= " AND timemodified > :changedsince";
1792 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1796 * Set a volatile flag
1798 * @param string $type the "type" namespace for the key
1799 * @param string $name the key to set
1800 * @param string $value the value to set (without magic quotes) - null will remove the flag
1801 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1802 * @return bool Always returns true
1804 function set_cache_flag($type, $name, $value, $expiry = null) {
1805 global $DB;
1807 $timemodified = time();
1808 if ($expiry === null || $expiry < $timemodified) {
1809 $expiry = $timemodified + 24 * 60 * 60;
1810 } else {
1811 $expiry = (int)$expiry;
1814 if ($value === null) {
1815 unset_cache_flag($type, $name);
1816 return true;
1819 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1820 // This is a potential problem in DEBUG_DEVELOPER.
1821 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1822 return true; // No need to update.
1824 $f->value = $value;
1825 $f->expiry = $expiry;
1826 $f->timemodified = $timemodified;
1827 $DB->update_record('cache_flags', $f);
1828 } else {
1829 $f = new stdClass();
1830 $f->flagtype = $type;
1831 $f->name = $name;
1832 $f->value = $value;
1833 $f->expiry = $expiry;
1834 $f->timemodified = $timemodified;
1835 $DB->insert_record('cache_flags', $f);
1837 return true;
1841 * Removes a single volatile flag
1843 * @param string $type the "type" namespace for the key
1844 * @param string $name the key to set
1845 * @return bool
1847 function unset_cache_flag($type, $name) {
1848 global $DB;
1849 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1850 return true;
1854 * Garbage-collect volatile flags
1856 * @return bool Always returns true
1858 function gc_cache_flags() {
1859 global $DB;
1860 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1861 return true;
1864 // USER PREFERENCE API.
1867 * Refresh user preference cache. This is used most often for $USER
1868 * object that is stored in session, but it also helps with performance in cron script.
1870 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1872 * @package core
1873 * @category preference
1874 * @access public
1875 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1876 * @param int $cachelifetime Cache life time on the current page (in seconds)
1877 * @throws coding_exception
1878 * @return null
1880 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1881 global $DB;
1882 // Static cache, we need to check on each page load, not only every 2 minutes.
1883 static $loadedusers = array();
1885 if (!isset($user->id)) {
1886 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1889 if (empty($user->id) or isguestuser($user->id)) {
1890 // No permanent storage for not-logged-in users and guest.
1891 if (!isset($user->preference)) {
1892 $user->preference = array();
1894 return;
1897 $timenow = time();
1899 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1900 // Already loaded at least once on this page. Are we up to date?
1901 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1902 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1903 return;
1905 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1906 // No change since the lastcheck on this page.
1907 $user->preference['_lastloaded'] = $timenow;
1908 return;
1912 // OK, so we have to reload all preferences.
1913 $loadedusers[$user->id] = true;
1914 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1915 $user->preference['_lastloaded'] = $timenow;
1919 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1921 * NOTE: internal function, do not call from other code.
1923 * @package core
1924 * @access private
1925 * @param integer $userid the user whose prefs were changed.
1927 function mark_user_preferences_changed($userid) {
1928 global $CFG;
1930 if (empty($userid) or isguestuser($userid)) {
1931 // No cache flags for guest and not-logged-in users.
1932 return;
1935 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1939 * Sets a preference for the specified user.
1941 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1943 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1945 * @package core
1946 * @category preference
1947 * @access public
1948 * @param string $name The key to set as preference for the specified user
1949 * @param string $value The value to set for the $name key in the specified user's
1950 * record, null means delete current value.
1951 * @param stdClass|int|null $user A moodle user object or id, null means current user
1952 * @throws coding_exception
1953 * @return bool Always true or exception
1955 function set_user_preference($name, $value, $user = null) {
1956 global $USER, $DB;
1958 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1959 throw new coding_exception('Invalid preference name in set_user_preference() call');
1962 if (is_null($value)) {
1963 // Null means delete current.
1964 return unset_user_preference($name, $user);
1965 } else if (is_object($value)) {
1966 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1967 } else if (is_array($value)) {
1968 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1970 // Value column maximum length is 1333 characters.
1971 $value = (string)$value;
1972 if (core_text::strlen($value) > 1333) {
1973 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1976 if (is_null($user)) {
1977 $user = $USER;
1978 } else if (isset($user->id)) {
1979 // It is a valid object.
1980 } else if (is_numeric($user)) {
1981 $user = (object)array('id' => (int)$user);
1982 } else {
1983 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1986 check_user_preferences_loaded($user);
1988 if (empty($user->id) or isguestuser($user->id)) {
1989 // No permanent storage for not-logged-in users and guest.
1990 $user->preference[$name] = $value;
1991 return true;
1994 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1995 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1996 // Preference already set to this value.
1997 return true;
1999 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
2001 } else {
2002 $preference = new stdClass();
2003 $preference->userid = $user->id;
2004 $preference->name = $name;
2005 $preference->value = $value;
2006 $DB->insert_record('user_preferences', $preference);
2009 // Update value in cache.
2010 $user->preference[$name] = $value;
2011 // Update the $USER in case where we've not a direct reference to $USER.
2012 if ($user !== $USER && $user->id == $USER->id) {
2013 $USER->preference[$name] = $value;
2016 // Set reload flag for other sessions.
2017 mark_user_preferences_changed($user->id);
2019 return true;
2023 * Sets a whole array of preferences for the current user
2025 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2027 * @package core
2028 * @category preference
2029 * @access public
2030 * @param array $prefarray An array of key/value pairs to be set
2031 * @param stdClass|int|null $user A moodle user object or id, null means current user
2032 * @return bool Always true or exception
2034 function set_user_preferences(array $prefarray, $user = null) {
2035 foreach ($prefarray as $name => $value) {
2036 set_user_preference($name, $value, $user);
2038 return true;
2042 * Unsets a preference completely by deleting it from the database
2044 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2046 * @package core
2047 * @category preference
2048 * @access public
2049 * @param string $name The key to unset as preference for the specified user
2050 * @param stdClass|int|null $user A moodle user object or id, null means current user
2051 * @throws coding_exception
2052 * @return bool Always true or exception
2054 function unset_user_preference($name, $user = null) {
2055 global $USER, $DB;
2057 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2058 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2061 if (is_null($user)) {
2062 $user = $USER;
2063 } else if (isset($user->id)) {
2064 // It is a valid object.
2065 } else if (is_numeric($user)) {
2066 $user = (object)array('id' => (int)$user);
2067 } else {
2068 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2071 check_user_preferences_loaded($user);
2073 if (empty($user->id) or isguestuser($user->id)) {
2074 // No permanent storage for not-logged-in user and guest.
2075 unset($user->preference[$name]);
2076 return true;
2079 // Delete from DB.
2080 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2082 // Delete the preference from cache.
2083 unset($user->preference[$name]);
2084 // Update the $USER in case where we've not a direct reference to $USER.
2085 if ($user !== $USER && $user->id == $USER->id) {
2086 unset($USER->preference[$name]);
2089 // Set reload flag for other sessions.
2090 mark_user_preferences_changed($user->id);
2092 return true;
2096 * Used to fetch user preference(s)
2098 * If no arguments are supplied this function will return
2099 * all of the current user preferences as an array.
2101 * If a name is specified then this function
2102 * attempts to return that particular preference value. If
2103 * none is found, then the optional value $default is returned,
2104 * otherwise null.
2106 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2108 * @package core
2109 * @category preference
2110 * @access public
2111 * @param string $name Name of the key to use in finding a preference value
2112 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2113 * @param stdClass|int|null $user A moodle user object or id, null means current user
2114 * @throws coding_exception
2115 * @return string|mixed|null A string containing the value of a single preference. An
2116 * array with all of the preferences or null
2118 function get_user_preferences($name = null, $default = null, $user = null) {
2119 global $USER;
2121 if (is_null($name)) {
2122 // All prefs.
2123 } else if (is_numeric($name) or $name === '_lastloaded') {
2124 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2127 if (is_null($user)) {
2128 $user = $USER;
2129 } else if (isset($user->id)) {
2130 // Is a valid object.
2131 } else if (is_numeric($user)) {
2132 if ($USER->id == $user) {
2133 $user = $USER;
2134 } else {
2135 $user = (object)array('id' => (int)$user);
2137 } else {
2138 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2141 check_user_preferences_loaded($user);
2143 if (empty($name)) {
2144 // All values.
2145 return $user->preference;
2146 } else if (isset($user->preference[$name])) {
2147 // The single string value.
2148 return $user->preference[$name];
2149 } else {
2150 // Default value (null if not specified).
2151 return $default;
2155 // FUNCTIONS FOR HANDLING TIME.
2158 * Given Gregorian date parts in user time produce a GMT timestamp.
2160 * @package core
2161 * @category time
2162 * @param int $year The year part to create timestamp of
2163 * @param int $month The month part to create timestamp of
2164 * @param int $day The day part to create timestamp of
2165 * @param int $hour The hour part to create timestamp of
2166 * @param int $minute The minute part to create timestamp of
2167 * @param int $second The second part to create timestamp of
2168 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2169 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2170 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2171 * applied only if timezone is 99 or string.
2172 * @return int GMT timestamp
2174 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2175 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2176 $date->setDate((int)$year, (int)$month, (int)$day);
2177 $date->setTime((int)$hour, (int)$minute, (int)$second);
2179 $time = $date->getTimestamp();
2181 if ($time === false) {
2182 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2183 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2186 // Moodle BC DST stuff.
2187 if (!$applydst) {
2188 $time += dst_offset_on($time, $timezone);
2191 return $time;
2196 * Format a date/time (seconds) as weeks, days, hours etc as needed
2198 * Given an amount of time in seconds, returns string
2199 * formatted nicely as years, days, hours etc as needed
2201 * @package core
2202 * @category time
2203 * @uses MINSECS
2204 * @uses HOURSECS
2205 * @uses DAYSECS
2206 * @uses YEARSECS
2207 * @param int $totalsecs Time in seconds
2208 * @param stdClass $str Should be a time object
2209 * @return string A nicely formatted date/time string
2211 function format_time($totalsecs, $str = null) {
2213 $totalsecs = abs($totalsecs);
2215 if (!$str) {
2216 // Create the str structure the slow way.
2217 $str = new stdClass();
2218 $str->day = get_string('day');
2219 $str->days = get_string('days');
2220 $str->hour = get_string('hour');
2221 $str->hours = get_string('hours');
2222 $str->min = get_string('min');
2223 $str->mins = get_string('mins');
2224 $str->sec = get_string('sec');
2225 $str->secs = get_string('secs');
2226 $str->year = get_string('year');
2227 $str->years = get_string('years');
2230 $years = floor($totalsecs/YEARSECS);
2231 $remainder = $totalsecs - ($years*YEARSECS);
2232 $days = floor($remainder/DAYSECS);
2233 $remainder = $totalsecs - ($days*DAYSECS);
2234 $hours = floor($remainder/HOURSECS);
2235 $remainder = $remainder - ($hours*HOURSECS);
2236 $mins = floor($remainder/MINSECS);
2237 $secs = $remainder - ($mins*MINSECS);
2239 $ss = ($secs == 1) ? $str->sec : $str->secs;
2240 $sm = ($mins == 1) ? $str->min : $str->mins;
2241 $sh = ($hours == 1) ? $str->hour : $str->hours;
2242 $sd = ($days == 1) ? $str->day : $str->days;
2243 $sy = ($years == 1) ? $str->year : $str->years;
2245 $oyears = '';
2246 $odays = '';
2247 $ohours = '';
2248 $omins = '';
2249 $osecs = '';
2251 if ($years) {
2252 $oyears = $years .' '. $sy;
2254 if ($days) {
2255 $odays = $days .' '. $sd;
2257 if ($hours) {
2258 $ohours = $hours .' '. $sh;
2260 if ($mins) {
2261 $omins = $mins .' '. $sm;
2263 if ($secs) {
2264 $osecs = $secs .' '. $ss;
2267 if ($years) {
2268 return trim($oyears .' '. $odays);
2270 if ($days) {
2271 return trim($odays .' '. $ohours);
2273 if ($hours) {
2274 return trim($ohours .' '. $omins);
2276 if ($mins) {
2277 return trim($omins .' '. $osecs);
2279 if ($secs) {
2280 return $osecs;
2282 return get_string('now');
2286 * Returns a formatted string that represents a date in user time.
2288 * @package core
2289 * @category time
2290 * @param int $date the timestamp in UTC, as obtained from the database.
2291 * @param string $format strftime format. You should probably get this using
2292 * get_string('strftime...', 'langconfig');
2293 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2294 * not 99 then daylight saving will not be added.
2295 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2296 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2297 * If false then the leading zero is maintained.
2298 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2299 * @return string the formatted date/time.
2301 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2302 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2303 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2307 * Returns a html "time" tag with both the exact user date with timezone information
2308 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2310 * @package core
2311 * @category time
2312 * @param int $date the timestamp in UTC, as obtained from the database.
2313 * @param string $format strftime format. You should probably get this using
2314 * get_string('strftime...', 'langconfig');
2315 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2316 * not 99 then daylight saving will not be added.
2317 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2318 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2319 * If false then the leading zero is maintained.
2320 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2321 * @return string the formatted date/time.
2323 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2324 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2325 if (CLI_SCRIPT && !PHPUNIT_TEST) {
2326 return $userdatestr;
2328 $machinedate = new DateTime();
2329 $machinedate->setTimestamp(intval($date));
2330 $machinedate->setTimezone(core_date::get_user_timezone_object());
2332 return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2336 * Returns a formatted date ensuring it is UTF-8.
2338 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2339 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2341 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2342 * @param string $format strftime format.
2343 * @param int|float|string $tz the user timezone
2344 * @return string the formatted date/time.
2345 * @since Moodle 2.3.3
2347 function date_format_string($date, $format, $tz = 99) {
2348 global $CFG;
2350 $localewincharset = null;
2351 // Get the calendar type user is using.
2352 if ($CFG->ostype == 'WINDOWS') {
2353 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2354 $localewincharset = $calendartype->locale_win_charset();
2357 if ($localewincharset) {
2358 $format = core_text::convert($format, 'utf-8', $localewincharset);
2361 date_default_timezone_set(core_date::get_user_timezone($tz));
2363 if (strftime('%p', 0) === strftime('%p', HOURSECS * 18)) {
2364 $datearray = getdate($date);
2365 $format = str_replace([
2366 '%P',
2367 '%p',
2368 ], [
2369 $datearray['hours'] < 12 ? get_string('am', 'langconfig') : get_string('pm', 'langconfig'),
2370 $datearray['hours'] < 12 ? get_string('amcaps', 'langconfig') : get_string('pmcaps', 'langconfig'),
2371 ], $format);
2374 $datestring = strftime($format, $date);
2375 core_date::set_default_server_timezone();
2377 if ($localewincharset) {
2378 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2381 return $datestring;
2385 * Given a $time timestamp in GMT (seconds since epoch),
2386 * returns an array that represents the Gregorian date in user time
2388 * @package core
2389 * @category time
2390 * @param int $time Timestamp in GMT
2391 * @param float|int|string $timezone user timezone
2392 * @return array An array that represents the date in user time
2394 function usergetdate($time, $timezone=99) {
2395 if ($time === null) {
2396 // PHP8 and PHP7 return different results when getdate(null) is called.
2397 // Display warning and cast to 0 to make sure the usergetdate() behaves consistently on all versions of PHP.
2398 // In the future versions of Moodle we may consider adding a strict typehint.
2399 debugging('usergetdate() expects parameter $time to be int, null given', DEBUG_DEVELOPER);
2400 $time = 0;
2403 date_default_timezone_set(core_date::get_user_timezone($timezone));
2404 $result = getdate($time);
2405 core_date::set_default_server_timezone();
2407 return $result;
2411 * Given a GMT timestamp (seconds since epoch), offsets it by
2412 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2414 * NOTE: this function does not include DST properly,
2415 * you should use the PHP date stuff instead!
2417 * @package core
2418 * @category time
2419 * @param int $date Timestamp in GMT
2420 * @param float|int|string $timezone user timezone
2421 * @return int
2423 function usertime($date, $timezone=99) {
2424 $userdate = new DateTime('@' . $date);
2425 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2426 $dst = dst_offset_on($date, $timezone);
2428 return $date - $userdate->getOffset() + $dst;
2432 * Get a formatted string representation of an interval between two unix timestamps.
2434 * E.g.
2435 * $intervalstring = get_time_interval_string(12345600, 12345660);
2436 * Will produce the string:
2437 * '0d 0h 1m'
2439 * @param int $time1 unix timestamp
2440 * @param int $time2 unix timestamp
2441 * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2442 * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2444 function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
2445 $dtdate = new DateTime();
2446 $dtdate->setTimeStamp($time1);
2447 $dtdate2 = new DateTime();
2448 $dtdate2->setTimeStamp($time2);
2449 $interval = $dtdate2->diff($dtdate);
2450 $format = empty($format) ? get_string('dateintervaldayshoursmins', 'langconfig') : $format;
2451 return $interval->format($format);
2455 * Given a time, return the GMT timestamp of the most recent midnight
2456 * for the current user.
2458 * @package core
2459 * @category time
2460 * @param int $date Timestamp in GMT
2461 * @param float|int|string $timezone user timezone
2462 * @return int Returns a GMT timestamp
2464 function usergetmidnight($date, $timezone=99) {
2466 $userdate = usergetdate($date, $timezone);
2468 // Time of midnight of this user's day, in GMT.
2469 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2474 * Returns a string that prints the user's timezone
2476 * @package core
2477 * @category time
2478 * @param float|int|string $timezone user timezone
2479 * @return string
2481 function usertimezone($timezone=99) {
2482 $tz = core_date::get_user_timezone($timezone);
2483 return core_date::get_localised_timezone($tz);
2487 * Returns a float or a string which denotes the user's timezone
2488 * 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)
2489 * means that for this timezone there are also DST rules to be taken into account
2490 * Checks various settings and picks the most dominant of those which have a value
2492 * @package core
2493 * @category time
2494 * @param float|int|string $tz timezone to calculate GMT time offset before
2495 * calculating user timezone, 99 is default user timezone
2496 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2497 * @return float|string
2499 function get_user_timezone($tz = 99) {
2500 global $USER, $CFG;
2502 $timezones = array(
2503 $tz,
2504 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2505 isset($USER->timezone) ? $USER->timezone : 99,
2506 isset($CFG->timezone) ? $CFG->timezone : 99,
2509 $tz = 99;
2511 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2512 foreach ($timezones as $nextvalue) {
2513 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2514 $tz = $nextvalue;
2517 return is_numeric($tz) ? (float) $tz : $tz;
2521 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2522 * - Note: Daylight saving only works for string timezones and not for float.
2524 * @package core
2525 * @category time
2526 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2527 * @param int|float|string $strtimezone user timezone
2528 * @return int
2530 function dst_offset_on($time, $strtimezone = null) {
2531 $tz = core_date::get_user_timezone($strtimezone);
2532 $date = new DateTime('@' . $time);
2533 $date->setTimezone(new DateTimeZone($tz));
2534 if ($date->format('I') == '1') {
2535 if ($tz === 'Australia/Lord_Howe') {
2536 return 1800;
2538 return 3600;
2540 return 0;
2544 * Calculates when the day appears in specific month
2546 * @package core
2547 * @category time
2548 * @param int $startday starting day of the month
2549 * @param int $weekday The day when week starts (normally taken from user preferences)
2550 * @param int $month The month whose day is sought
2551 * @param int $year The year of the month whose day is sought
2552 * @return int
2554 function find_day_in_month($startday, $weekday, $month, $year) {
2555 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2557 $daysinmonth = days_in_month($month, $year);
2558 $daysinweek = count($calendartype->get_weekdays());
2560 if ($weekday == -1) {
2561 // Don't care about weekday, so return:
2562 // abs($startday) if $startday != -1
2563 // $daysinmonth otherwise.
2564 return ($startday == -1) ? $daysinmonth : abs($startday);
2567 // From now on we 're looking for a specific weekday.
2568 // Give "end of month" its actual value, since we know it.
2569 if ($startday == -1) {
2570 $startday = -1 * $daysinmonth;
2573 // Starting from day $startday, the sign is the direction.
2574 if ($startday < 1) {
2575 $startday = abs($startday);
2576 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2578 // This is the last such weekday of the month.
2579 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2580 if ($lastinmonth > $daysinmonth) {
2581 $lastinmonth -= $daysinweek;
2584 // Find the first such weekday <= $startday.
2585 while ($lastinmonth > $startday) {
2586 $lastinmonth -= $daysinweek;
2589 return $lastinmonth;
2590 } else {
2591 $indexweekday = dayofweek($startday, $month, $year);
2593 $diff = $weekday - $indexweekday;
2594 if ($diff < 0) {
2595 $diff += $daysinweek;
2598 // This is the first such weekday of the month equal to or after $startday.
2599 $firstfromindex = $startday + $diff;
2601 return $firstfromindex;
2606 * Calculate the number of days in a given month
2608 * @package core
2609 * @category time
2610 * @param int $month The month whose day count is sought
2611 * @param int $year The year of the month whose day count is sought
2612 * @return int
2614 function days_in_month($month, $year) {
2615 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2616 return $calendartype->get_num_days_in_month($year, $month);
2620 * Calculate the position in the week of a specific calendar day
2622 * @package core
2623 * @category time
2624 * @param int $day The day of the date whose position in the week is sought
2625 * @param int $month The month of the date whose position in the week is sought
2626 * @param int $year The year of the date whose position in the week is sought
2627 * @return int
2629 function dayofweek($day, $month, $year) {
2630 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2631 return $calendartype->get_weekday($year, $month, $day);
2634 // USER AUTHENTICATION AND LOGIN.
2637 * Returns full login url.
2639 * Any form submissions for authentication to this URL must include username,
2640 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2642 * @return string login url
2644 function get_login_url() {
2645 global $CFG;
2647 return "$CFG->wwwroot/login/index.php";
2651 * This function checks that the current user is logged in and has the
2652 * required privileges
2654 * This function checks that the current user is logged in, and optionally
2655 * whether they are allowed to be in a particular course and view a particular
2656 * course module.
2657 * If they are not logged in, then it redirects them to the site login unless
2658 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2659 * case they are automatically logged in as guests.
2660 * If $courseid is given and the user is not enrolled in that course then the
2661 * user is redirected to the course enrolment page.
2662 * If $cm is given and the course module is hidden and the user is not a teacher
2663 * in the course then the user is redirected to the course home page.
2665 * When $cm parameter specified, this function sets page layout to 'module'.
2666 * You need to change it manually later if some other layout needed.
2668 * @package core_access
2669 * @category access
2671 * @param mixed $courseorid id of the course or course object
2672 * @param bool $autologinguest default true
2673 * @param object $cm course module object
2674 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2675 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2676 * in order to keep redirects working properly. MDL-14495
2677 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2678 * @return mixed Void, exit, and die depending on path
2679 * @throws coding_exception
2680 * @throws require_login_exception
2681 * @throws moodle_exception
2683 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2684 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2686 // Must not redirect when byteserving already started.
2687 if (!empty($_SERVER['HTTP_RANGE'])) {
2688 $preventredirect = true;
2691 if (AJAX_SCRIPT) {
2692 // We cannot redirect for AJAX scripts either.
2693 $preventredirect = true;
2696 // Setup global $COURSE, themes, language and locale.
2697 if (!empty($courseorid)) {
2698 if (is_object($courseorid)) {
2699 $course = $courseorid;
2700 } else if ($courseorid == SITEID) {
2701 $course = clone($SITE);
2702 } else {
2703 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2705 if ($cm) {
2706 if ($cm->course != $course->id) {
2707 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2709 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2710 if (!($cm instanceof cm_info)) {
2711 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2712 // db queries so this is not really a performance concern, however it is obviously
2713 // better if you use get_fast_modinfo to get the cm before calling this.
2714 $modinfo = get_fast_modinfo($course);
2715 $cm = $modinfo->get_cm($cm->id);
2718 } else {
2719 // Do not touch global $COURSE via $PAGE->set_course(),
2720 // the reasons is we need to be able to call require_login() at any time!!
2721 $course = $SITE;
2722 if ($cm) {
2723 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2727 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2728 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2729 // risk leading the user back to the AJAX request URL.
2730 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2731 $setwantsurltome = false;
2734 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2735 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2736 if ($preventredirect) {
2737 throw new require_login_session_timeout_exception();
2738 } else {
2739 if ($setwantsurltome) {
2740 $SESSION->wantsurl = qualified_me();
2742 redirect(get_login_url());
2746 // If the user is not even logged in yet then make sure they are.
2747 if (!isloggedin()) {
2748 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2749 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2750 // Misconfigured site guest, just redirect to login page.
2751 redirect(get_login_url());
2752 exit; // Never reached.
2754 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2755 complete_user_login($guest);
2756 $USER->autologinguest = true;
2757 $SESSION->lang = $lang;
2758 } else {
2759 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2760 if ($preventredirect) {
2761 throw new require_login_exception('You are not logged in');
2764 if ($setwantsurltome) {
2765 $SESSION->wantsurl = qualified_me();
2768 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2769 $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
2770 foreach($authsequence as $authname) {
2771 $authplugin = get_auth_plugin($authname);
2772 $authplugin->pre_loginpage_hook();
2773 if (isloggedin()) {
2774 if ($cm) {
2775 $modinfo = get_fast_modinfo($course);
2776 $cm = $modinfo->get_cm($cm->id);
2778 set_access_log_user();
2779 break;
2783 // If we're still not logged in then go to the login page
2784 if (!isloggedin()) {
2785 redirect(get_login_url());
2786 exit; // Never reached.
2791 // Loginas as redirection if needed.
2792 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2793 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2794 if ($USER->loginascontext->instanceid != $course->id) {
2795 throw new \moodle_exception('loginasonecourse', '',
2796 $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2801 // Check whether the user should be changing password (but only if it is REALLY them).
2802 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2803 $userauth = get_auth_plugin($USER->auth);
2804 if ($userauth->can_change_password() and !$preventredirect) {
2805 if ($setwantsurltome) {
2806 $SESSION->wantsurl = qualified_me();
2808 if ($changeurl = $userauth->change_password_url()) {
2809 // Use plugin custom url.
2810 redirect($changeurl);
2811 } else {
2812 // Use moodle internal method.
2813 redirect($CFG->wwwroot .'/login/change_password.php');
2815 } else if ($userauth->can_change_password()) {
2816 throw new moodle_exception('forcepasswordchangenotice');
2817 } else {
2818 throw new moodle_exception('nopasswordchangeforced', 'auth');
2822 // Check that the user account is properly set up. If we can't redirect to
2823 // edit their profile and this is not a WS request, perform just the lax check.
2824 // It will allow them to use filepicker on the profile edit page.
2826 if ($preventredirect && !WS_SERVER) {
2827 $usernotfullysetup = user_not_fully_set_up($USER, false);
2828 } else {
2829 $usernotfullysetup = user_not_fully_set_up($USER, true);
2832 if ($usernotfullysetup) {
2833 if ($preventredirect) {
2834 throw new moodle_exception('usernotfullysetup');
2836 if ($setwantsurltome) {
2837 $SESSION->wantsurl = qualified_me();
2839 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2842 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2843 sesskey();
2845 if (\core\session\manager::is_loggedinas()) {
2846 // During a "logged in as" session we should force all content to be cleaned because the
2847 // logged in user will be viewing potentially malicious user generated content.
2848 // See MDL-63786 for more details.
2849 $CFG->forceclean = true;
2852 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2854 // Do not bother admins with any formalities, except for activities pending deletion.
2855 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2856 // Set the global $COURSE.
2857 if ($cm) {
2858 $PAGE->set_cm($cm, $course);
2859 $PAGE->set_pagelayout('incourse');
2860 } else if (!empty($courseorid)) {
2861 $PAGE->set_course($course);
2863 // Set accesstime or the user will appear offline which messes up messaging.
2864 // Do not update access time for webservice or ajax requests.
2865 if (!WS_SERVER && !AJAX_SCRIPT) {
2866 user_accesstime_log($course->id);
2869 foreach ($afterlogins as $plugintype => $plugins) {
2870 foreach ($plugins as $pluginfunction) {
2871 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2874 return;
2877 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2878 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2879 if (!defined('NO_SITEPOLICY_CHECK')) {
2880 define('NO_SITEPOLICY_CHECK', false);
2883 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2884 // Do not test if the script explicitly asked for skipping the site policies check.
2885 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2886 $manager = new \core_privacy\local\sitepolicy\manager();
2887 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2888 if ($preventredirect) {
2889 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2891 if ($setwantsurltome) {
2892 $SESSION->wantsurl = qualified_me();
2894 redirect($policyurl);
2898 // Fetch the system context, the course context, and prefetch its child contexts.
2899 $sysctx = context_system::instance();
2900 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2901 if ($cm) {
2902 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2903 } else {
2904 $cmcontext = null;
2907 // If the site is currently under maintenance, then print a message.
2908 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2909 if ($preventredirect) {
2910 throw new require_login_exception('Maintenance in progress');
2912 $PAGE->set_context(null);
2913 print_maintenance_message();
2916 // Make sure the course itself is not hidden.
2917 if ($course->id == SITEID) {
2918 // Frontpage can not be hidden.
2919 } else {
2920 if (is_role_switched($course->id)) {
2921 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2922 } else {
2923 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2924 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2925 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2926 if ($preventredirect) {
2927 throw new require_login_exception('Course is hidden');
2929 $PAGE->set_context(null);
2930 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2931 // the navigation will mess up when trying to find it.
2932 navigation_node::override_active_url(new moodle_url('/'));
2933 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2938 // Is the user enrolled?
2939 if ($course->id == SITEID) {
2940 // Everybody is enrolled on the frontpage.
2941 } else {
2942 if (\core\session\manager::is_loggedinas()) {
2943 // Make sure the REAL person can access this course first.
2944 $realuser = \core\session\manager::get_realuser();
2945 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2946 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2947 if ($preventredirect) {
2948 throw new require_login_exception('Invalid course login-as access');
2950 $PAGE->set_context(null);
2951 echo $OUTPUT->header();
2952 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2956 $access = false;
2958 if (is_role_switched($course->id)) {
2959 // Ok, user had to be inside this course before the switch.
2960 $access = true;
2962 } else if (is_viewing($coursecontext, $USER)) {
2963 // Ok, no need to mess with enrol.
2964 $access = true;
2966 } else {
2967 if (isset($USER->enrol['enrolled'][$course->id])) {
2968 if ($USER->enrol['enrolled'][$course->id] > time()) {
2969 $access = true;
2970 if (isset($USER->enrol['tempguest'][$course->id])) {
2971 unset($USER->enrol['tempguest'][$course->id]);
2972 remove_temp_course_roles($coursecontext);
2974 } else {
2975 // Expired.
2976 unset($USER->enrol['enrolled'][$course->id]);
2979 if (isset($USER->enrol['tempguest'][$course->id])) {
2980 if ($USER->enrol['tempguest'][$course->id] == 0) {
2981 $access = true;
2982 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2983 $access = true;
2984 } else {
2985 // Expired.
2986 unset($USER->enrol['tempguest'][$course->id]);
2987 remove_temp_course_roles($coursecontext);
2991 if (!$access) {
2992 // Cache not ok.
2993 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2994 if ($until !== false) {
2995 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2996 if ($until == 0) {
2997 $until = ENROL_MAX_TIMESTAMP;
2999 $USER->enrol['enrolled'][$course->id] = $until;
3000 $access = true;
3002 } else if (core_course_category::can_view_course_info($course)) {
3003 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
3004 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3005 $enrols = enrol_get_plugins(true);
3006 // First ask all enabled enrol instances in course if they want to auto enrol user.
3007 foreach ($instances as $instance) {
3008 if (!isset($enrols[$instance->enrol])) {
3009 continue;
3011 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3012 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3013 if ($until !== false) {
3014 if ($until == 0) {
3015 $until = ENROL_MAX_TIMESTAMP;
3017 $USER->enrol['enrolled'][$course->id] = $until;
3018 $access = true;
3019 break;
3022 // If not enrolled yet try to gain temporary guest access.
3023 if (!$access) {
3024 foreach ($instances as $instance) {
3025 if (!isset($enrols[$instance->enrol])) {
3026 continue;
3028 // Get a duration for the guest access, a timestamp in the future or false.
3029 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3030 if ($until !== false and $until > time()) {
3031 $USER->enrol['tempguest'][$course->id] = $until;
3032 $access = true;
3033 break;
3037 } else {
3038 // User is not enrolled and is not allowed to browse courses here.
3039 if ($preventredirect) {
3040 throw new require_login_exception('Course is not available');
3042 $PAGE->set_context(null);
3043 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3044 // the navigation will mess up when trying to find it.
3045 navigation_node::override_active_url(new moodle_url('/'));
3046 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3051 if (!$access) {
3052 if ($preventredirect) {
3053 throw new require_login_exception('Not enrolled');
3055 if ($setwantsurltome) {
3056 $SESSION->wantsurl = qualified_me();
3058 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3062 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3063 if ($cm && $cm->deletioninprogress) {
3064 if ($preventredirect) {
3065 throw new moodle_exception('activityisscheduledfordeletion');
3067 require_once($CFG->dirroot . '/course/lib.php');
3068 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3071 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3072 if ($cm && !$cm->uservisible) {
3073 if ($preventredirect) {
3074 throw new require_login_exception('Activity is hidden');
3076 // Get the error message that activity is not available and why (if explanation can be shown to the user).
3077 $PAGE->set_course($course);
3078 $renderer = $PAGE->get_renderer('course');
3079 $message = $renderer->course_section_cm_unavailable_error_message($cm);
3080 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
3083 // Set the global $COURSE.
3084 if ($cm) {
3085 $PAGE->set_cm($cm, $course);
3086 $PAGE->set_pagelayout('incourse');
3087 } else if (!empty($courseorid)) {
3088 $PAGE->set_course($course);
3091 foreach ($afterlogins as $plugintype => $plugins) {
3092 foreach ($plugins as $pluginfunction) {
3093 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3097 // Finally access granted, update lastaccess times.
3098 // Do not update access time for webservice or ajax requests.
3099 if (!WS_SERVER && !AJAX_SCRIPT) {
3100 user_accesstime_log($course->id);
3105 * A convenience function for where we must be logged in as admin
3106 * @return void
3108 function require_admin() {
3109 require_login(null, false);
3110 require_capability('moodle/site:config', context_system::instance());
3114 * This function just makes sure a user is logged out.
3116 * @package core_access
3117 * @category access
3119 function require_logout() {
3120 global $USER, $DB;
3122 if (!isloggedin()) {
3123 // This should not happen often, no need for hooks or events here.
3124 \core\session\manager::terminate_current();
3125 return;
3128 // Execute hooks before action.
3129 $authplugins = array();
3130 $authsequence = get_enabled_auth_plugins();
3131 foreach ($authsequence as $authname) {
3132 $authplugins[$authname] = get_auth_plugin($authname);
3133 $authplugins[$authname]->prelogout_hook();
3136 // Store info that gets removed during logout.
3137 $sid = session_id();
3138 $event = \core\event\user_loggedout::create(
3139 array(
3140 'userid' => $USER->id,
3141 'objectid' => $USER->id,
3142 'other' => array('sessionid' => $sid),
3145 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3146 $event->add_record_snapshot('sessions', $session);
3149 // Clone of $USER object to be used by auth plugins.
3150 $user = fullclone($USER);
3152 // Delete session record and drop $_SESSION content.
3153 \core\session\manager::terminate_current();
3155 // Trigger event AFTER action.
3156 $event->trigger();
3158 // Hook to execute auth plugins redirection after event trigger.
3159 foreach ($authplugins as $authplugin) {
3160 $authplugin->postlogout_hook($user);
3165 * Weaker version of require_login()
3167 * This is a weaker version of {@link require_login()} which only requires login
3168 * when called from within a course rather than the site page, unless
3169 * the forcelogin option is turned on.
3170 * @see require_login()
3172 * @package core_access
3173 * @category access
3175 * @param mixed $courseorid The course object or id in question
3176 * @param bool $autologinguest Allow autologin guests if that is wanted
3177 * @param object $cm Course activity module if known
3178 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3179 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3180 * in order to keep redirects working properly. MDL-14495
3181 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3182 * @return void
3183 * @throws coding_exception
3185 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3186 global $CFG, $PAGE, $SITE;
3187 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3188 or (!is_object($courseorid) and $courseorid == SITEID));
3189 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3190 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3191 // db queries so this is not really a performance concern, however it is obviously
3192 // better if you use get_fast_modinfo to get the cm before calling this.
3193 if (is_object($courseorid)) {
3194 $course = $courseorid;
3195 } else {
3196 $course = clone($SITE);
3198 $modinfo = get_fast_modinfo($course);
3199 $cm = $modinfo->get_cm($cm->id);
3201 if (!empty($CFG->forcelogin)) {
3202 // Login required for both SITE and courses.
3203 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3205 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3206 // Always login for hidden activities.
3207 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3209 } else if (isloggedin() && !isguestuser()) {
3210 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3211 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3213 } else if ($issite) {
3214 // Login for SITE not required.
3215 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3216 if (!empty($courseorid)) {
3217 if (is_object($courseorid)) {
3218 $course = $courseorid;
3219 } else {
3220 $course = clone $SITE;
3222 if ($cm) {
3223 if ($cm->course != $course->id) {
3224 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3226 $PAGE->set_cm($cm, $course);
3227 $PAGE->set_pagelayout('incourse');
3228 } else {
3229 $PAGE->set_course($course);
3231 } else {
3232 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3233 $PAGE->set_course($PAGE->course);
3235 // Do not update access time for webservice or ajax requests.
3236 if (!WS_SERVER && !AJAX_SCRIPT) {
3237 user_accesstime_log(SITEID);
3239 return;
3241 } else {
3242 // Course login always required.
3243 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3248 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3250 * @param string $keyvalue the key value
3251 * @param string $script unique script identifier
3252 * @param int $instance instance id
3253 * @return stdClass the key entry in the user_private_key table
3254 * @since Moodle 3.2
3255 * @throws moodle_exception
3257 function validate_user_key($keyvalue, $script, $instance) {
3258 global $DB;
3260 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3261 throw new \moodle_exception('invalidkey');
3264 if (!empty($key->validuntil) and $key->validuntil < time()) {
3265 throw new \moodle_exception('expiredkey');
3268 if ($key->iprestriction) {
3269 $remoteaddr = getremoteaddr(null);
3270 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3271 throw new \moodle_exception('ipmismatch');
3274 return $key;
3278 * Require key login. Function terminates with error if key not found or incorrect.
3280 * @uses NO_MOODLE_COOKIES
3281 * @uses PARAM_ALPHANUM
3282 * @param string $script unique script identifier
3283 * @param int $instance optional instance id
3284 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3285 * @return int Instance ID
3287 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3288 global $DB;
3290 if (!NO_MOODLE_COOKIES) {
3291 throw new \moodle_exception('sessioncookiesdisable');
3294 // Extra safety.
3295 \core\session\manager::write_close();
3297 if (null === $keyvalue) {
3298 $keyvalue = required_param('key', PARAM_ALPHANUM);
3301 $key = validate_user_key($keyvalue, $script, $instance);
3303 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3304 throw new \moodle_exception('invaliduserid');
3307 core_user::require_active_user($user, true, true);
3309 // Emulate normal session.
3310 enrol_check_plugins($user, false);
3311 \core\session\manager::set_user($user);
3313 // Note we are not using normal login.
3314 if (!defined('USER_KEY_LOGIN')) {
3315 define('USER_KEY_LOGIN', true);
3318 // Return instance id - it might be empty.
3319 return $key->instance;
3323 * Creates a new private user access key.
3325 * @param string $script unique target identifier
3326 * @param int $userid
3327 * @param int $instance optional instance id
3328 * @param string $iprestriction optional ip restricted access
3329 * @param int $validuntil key valid only until given data
3330 * @return string access key value
3332 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3333 global $DB;
3335 $key = new stdClass();
3336 $key->script = $script;
3337 $key->userid = $userid;
3338 $key->instance = $instance;
3339 $key->iprestriction = $iprestriction;
3340 $key->validuntil = $validuntil;
3341 $key->timecreated = time();
3343 // Something long and unique.
3344 $key->value = md5($userid.'_'.time().random_string(40));
3345 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3346 // Must be unique.
3347 $key->value = md5($userid.'_'.time().random_string(40));
3349 $DB->insert_record('user_private_key', $key);
3350 return $key->value;
3354 * Delete the user's new private user access keys for a particular script.
3356 * @param string $script unique target identifier
3357 * @param int $userid
3358 * @return void
3360 function delete_user_key($script, $userid) {
3361 global $DB;
3362 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3366 * Gets a private user access key (and creates one if one doesn't exist).
3368 * @param string $script unique target identifier
3369 * @param int $userid
3370 * @param int $instance optional instance id
3371 * @param string $iprestriction optional ip restricted access
3372 * @param int $validuntil key valid only until given date
3373 * @return string access key value
3375 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3376 global $DB;
3378 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3379 'instance' => $instance, 'iprestriction' => $iprestriction,
3380 'validuntil' => $validuntil))) {
3381 return $key->value;
3382 } else {
3383 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3389 * Modify the user table by setting the currently logged in user's last login to now.
3391 * @return bool Always returns true
3393 function update_user_login_times() {
3394 global $USER, $DB, $SESSION;
3396 if (isguestuser()) {
3397 // Do not update guest access times/ips for performance.
3398 return true;
3401 $now = time();
3403 $user = new stdClass();
3404 $user->id = $USER->id;
3406 // Make sure all users that logged in have some firstaccess.
3407 if ($USER->firstaccess == 0) {
3408 $USER->firstaccess = $user->firstaccess = $now;
3411 // Store the previous current as lastlogin.
3412 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3414 $USER->currentlogin = $user->currentlogin = $now;
3416 // Function user_accesstime_log() may not update immediately, better do it here.
3417 $USER->lastaccess = $user->lastaccess = $now;
3418 $SESSION->userpreviousip = $USER->lastip;
3419 $USER->lastip = $user->lastip = getremoteaddr();
3421 // Note: do not call user_update_user() here because this is part of the login process,
3422 // the login event means that these fields were updated.
3423 $DB->update_record('user', $user);
3424 return true;
3428 * Determines if a user has completed setting up their account.
3430 * The lax mode (with $strict = false) has been introduced for special cases
3431 * only where we want to skip certain checks intentionally. This is valid in
3432 * certain mnet or ajax scenarios when the user cannot / should not be
3433 * redirected to edit their profile. In most cases, you should perform the
3434 * strict check.
3436 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3437 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3438 * @return bool
3440 function user_not_fully_set_up($user, $strict = true) {
3441 global $CFG;
3442 require_once($CFG->dirroot.'/user/profile/lib.php');
3444 if (isguestuser($user)) {
3445 return false;
3448 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3449 return true;
3452 if ($strict) {
3453 if (empty($user->id)) {
3454 // Strict mode can be used with existing accounts only.
3455 return true;
3457 if (!profile_has_required_custom_fields_set($user->id)) {
3458 return true;
3462 return false;
3466 * Check whether the user has exceeded the bounce threshold
3468 * @param stdClass $user A {@link $USER} object
3469 * @return bool true => User has exceeded bounce threshold
3471 function over_bounce_threshold($user) {
3472 global $CFG, $DB;
3474 if (empty($CFG->handlebounces)) {
3475 return false;
3478 if (empty($user->id)) {
3479 // No real (DB) user, nothing to do here.
3480 return false;
3483 // Set sensible defaults.
3484 if (empty($CFG->minbounces)) {
3485 $CFG->minbounces = 10;
3487 if (empty($CFG->bounceratio)) {
3488 $CFG->bounceratio = .20;
3490 $bouncecount = 0;
3491 $sendcount = 0;
3492 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3493 $bouncecount = $bounce->value;
3495 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3496 $sendcount = $send->value;
3498 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3502 * Used to increment or reset email sent count
3504 * @param stdClass $user object containing an id
3505 * @param bool $reset will reset the count to 0
3506 * @return void
3508 function set_send_count($user, $reset=false) {
3509 global $DB;
3511 if (empty($user->id)) {
3512 // No real (DB) user, nothing to do here.
3513 return;
3516 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3517 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3518 $DB->update_record('user_preferences', $pref);
3519 } else if (!empty($reset)) {
3520 // If it's not there and we're resetting, don't bother. Make a new one.
3521 $pref = new stdClass();
3522 $pref->name = 'email_send_count';
3523 $pref->value = 1;
3524 $pref->userid = $user->id;
3525 $DB->insert_record('user_preferences', $pref, false);
3530 * Increment or reset user's email bounce count
3532 * @param stdClass $user object containing an id
3533 * @param bool $reset will reset the count to 0
3535 function set_bounce_count($user, $reset=false) {
3536 global $DB;
3538 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3539 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3540 $DB->update_record('user_preferences', $pref);
3541 } else if (!empty($reset)) {
3542 // If it's not there and we're resetting, don't bother. Make a new one.
3543 $pref = new stdClass();
3544 $pref->name = 'email_bounce_count';
3545 $pref->value = 1;
3546 $pref->userid = $user->id;
3547 $DB->insert_record('user_preferences', $pref, false);
3552 * Determines if the logged in user is currently moving an activity
3554 * @param int $courseid The id of the course being tested
3555 * @return bool
3557 function ismoving($courseid) {
3558 global $USER;
3560 if (!empty($USER->activitycopy)) {
3561 return ($USER->activitycopycourse == $courseid);
3563 return false;
3567 * Returns a persons full name
3569 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3570 * The result may depend on system settings or language. 'override' will force the alternativefullnameformat to be used. In
3571 * English, fullname as well as alternativefullnameformat is set to 'firstname lastname' by default. But you could have
3572 * fullname set to 'firstname lastname' and alternativefullnameformat set to 'firstname middlename alternatename lastname'.
3574 * @param stdClass $user A {@link $USER} object to get full name of.
3575 * @param bool $override If true then the alternativefullnameformat format rather than fullnamedisplay format will be used.
3576 * @return string
3578 function fullname($user, $override=false) {
3579 global $CFG, $SESSION;
3581 if (!isset($user->firstname) and !isset($user->lastname)) {
3582 return '';
3585 // Get all of the name fields.
3586 $allnames = \core_user\fields::get_name_fields();
3587 if ($CFG->debugdeveloper) {
3588 foreach ($allnames as $allname) {
3589 if (!property_exists($user, $allname)) {
3590 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3591 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3592 // Message has been sent, no point in sending the message multiple times.
3593 break;
3598 if (!$override) {
3599 if (!empty($CFG->forcefirstname)) {
3600 $user->firstname = $CFG->forcefirstname;
3602 if (!empty($CFG->forcelastname)) {
3603 $user->lastname = $CFG->forcelastname;
3607 if (!empty($SESSION->fullnamedisplay)) {
3608 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3611 $template = null;
3612 // If the fullnamedisplay setting is available, set the template to that.
3613 if (isset($CFG->fullnamedisplay)) {
3614 $template = $CFG->fullnamedisplay;
3616 // If the template is empty, or set to language, return the language string.
3617 if ((empty($template) || $template == 'language') && !$override) {
3618 return get_string('fullnamedisplay', null, $user);
3621 // Check to see if we are displaying according to the alternative full name format.
3622 if ($override) {
3623 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3624 // Default to show just the user names according to the fullnamedisplay string.
3625 return get_string('fullnamedisplay', null, $user);
3626 } else {
3627 // If the override is true, then change the template to use the complete name.
3628 $template = $CFG->alternativefullnameformat;
3632 $requirednames = array();
3633 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3634 foreach ($allnames as $allname) {
3635 if (strpos($template, $allname) !== false) {
3636 $requirednames[] = $allname;
3640 $displayname = $template;
3641 // Switch in the actual data into the template.
3642 foreach ($requirednames as $altname) {
3643 if (isset($user->$altname)) {
3644 // Using empty() on the below if statement causes breakages.
3645 if ((string)$user->$altname == '') {
3646 $displayname = str_replace($altname, 'EMPTY', $displayname);
3647 } else {
3648 $displayname = str_replace($altname, $user->$altname, $displayname);
3650 } else {
3651 $displayname = str_replace($altname, 'EMPTY', $displayname);
3654 // Tidy up any misc. characters (Not perfect, but gets most characters).
3655 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3656 // katakana and parenthesis.
3657 $patterns = array();
3658 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3659 // filled in by a user.
3660 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3661 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3662 // This regular expression is to remove any double spaces in the display name.
3663 $patterns[] = '/\s{2,}/u';
3664 foreach ($patterns as $pattern) {
3665 $displayname = preg_replace($pattern, ' ', $displayname);
3668 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3669 $displayname = trim($displayname);
3670 if (empty($displayname)) {
3671 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3672 // people in general feel is a good setting to fall back on.
3673 $displayname = $user->firstname;
3675 return $displayname;
3679 * Reduces lines of duplicated code for getting user name fields.
3681 * See also {@link user_picture::unalias()}
3683 * @param object $addtoobject Object to add user name fields to.
3684 * @param object $secondobject Object that contains user name field information.
3685 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3686 * @param array $additionalfields Additional fields to be matched with data in the second object.
3687 * The key can be set to the user table field name.
3688 * @return object User name fields.
3690 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3691 $fields = [];
3692 foreach (\core_user\fields::get_name_fields() as $field) {
3693 $fields[$field] = $prefix . $field;
3695 if ($additionalfields) {
3696 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3697 // the key is a number and then sets the key to the array value.
3698 foreach ($additionalfields as $key => $value) {
3699 if (is_numeric($key)) {
3700 $additionalfields[$value] = $prefix . $value;
3701 unset($additionalfields[$key]);
3702 } else {
3703 $additionalfields[$key] = $prefix . $value;
3706 $fields = array_merge($fields, $additionalfields);
3708 foreach ($fields as $key => $field) {
3709 // Important that we have all of the user name fields present in the object that we are sending back.
3710 $addtoobject->$key = '';
3711 if (isset($secondobject->$field)) {
3712 $addtoobject->$key = $secondobject->$field;
3715 return $addtoobject;
3719 * Returns an array of values in order of occurance in a provided string.
3720 * The key in the result is the character postion in the string.
3722 * @param array $values Values to be found in the string format
3723 * @param string $stringformat The string which may contain values being searched for.
3724 * @return array An array of values in order according to placement in the string format.
3726 function order_in_string($values, $stringformat) {
3727 $valuearray = array();
3728 foreach ($values as $value) {
3729 $pattern = "/$value\b/";
3730 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3731 if (preg_match($pattern, $stringformat)) {
3732 $replacement = "thing";
3733 // Replace the value with something more unique to ensure we get the right position when using strpos().
3734 $newformat = preg_replace($pattern, $replacement, $stringformat);
3735 $position = strpos($newformat, $replacement);
3736 $valuearray[$position] = $value;
3739 ksort($valuearray);
3740 return $valuearray;
3744 * Returns whether a given authentication plugin exists.
3746 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3747 * @return boolean Whether the plugin is available.
3749 function exists_auth_plugin($auth) {
3750 global $CFG;
3752 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3753 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3755 return false;
3759 * Checks if a given plugin is in the list of enabled authentication plugins.
3761 * @param string $auth Authentication plugin.
3762 * @return boolean Whether the plugin is enabled.
3764 function is_enabled_auth($auth) {
3765 if (empty($auth)) {
3766 return false;
3769 $enabled = get_enabled_auth_plugins();
3771 return in_array($auth, $enabled);
3775 * Returns an authentication plugin instance.
3777 * @param string $auth name of authentication plugin
3778 * @return auth_plugin_base An instance of the required authentication plugin.
3780 function get_auth_plugin($auth) {
3781 global $CFG;
3783 // Check the plugin exists first.
3784 if (! exists_auth_plugin($auth)) {
3785 throw new \moodle_exception('authpluginnotfound', 'debug', '', $auth);
3788 // Return auth plugin instance.
3789 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3790 $class = "auth_plugin_$auth";
3791 return new $class;
3795 * Returns array of active auth plugins.
3797 * @param bool $fix fix $CFG->auth if needed. Only set if logged in as admin.
3798 * @return array
3800 function get_enabled_auth_plugins($fix=false) {
3801 global $CFG;
3803 $default = array('manual', 'nologin');
3805 if (empty($CFG->auth)) {
3806 $auths = array();
3807 } else {
3808 $auths = explode(',', $CFG->auth);
3811 $auths = array_unique($auths);
3812 $oldauthconfig = implode(',', $auths);
3813 foreach ($auths as $k => $authname) {
3814 if (in_array($authname, $default)) {
3815 // The manual and nologin plugin never need to be stored.
3816 unset($auths[$k]);
3817 } else if (!exists_auth_plugin($authname)) {
3818 debugging(get_string('authpluginnotfound', 'debug', $authname));
3819 unset($auths[$k]);
3823 // Ideally only explicit interaction from a human admin should trigger a
3824 // change in auth config, see MDL-70424 for details.
3825 if ($fix) {
3826 $newconfig = implode(',', $auths);
3827 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3828 add_to_config_log('auth', $oldauthconfig, $newconfig, 'core');
3829 set_config('auth', $newconfig);
3833 return (array_merge($default, $auths));
3837 * Returns true if an internal authentication method is being used.
3838 * if method not specified then, global default is assumed
3840 * @param string $auth Form of authentication required
3841 * @return bool
3843 function is_internal_auth($auth) {
3844 // Throws error if bad $auth.
3845 $authplugin = get_auth_plugin($auth);
3846 return $authplugin->is_internal();
3850 * Returns true if the user is a 'restored' one.
3852 * Used in the login process to inform the user and allow him/her to reset the password
3854 * @param string $username username to be checked
3855 * @return bool
3857 function is_restored_user($username) {
3858 global $CFG, $DB;
3860 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3864 * Returns an array of user fields
3866 * @return array User field/column names
3868 function get_user_fieldnames() {
3869 global $DB;
3871 $fieldarray = $DB->get_columns('user');
3872 unset($fieldarray['id']);
3873 $fieldarray = array_keys($fieldarray);
3875 return $fieldarray;
3879 * Returns the string of the language for the new user.
3881 * @return string language for the new user
3883 function get_newuser_language() {
3884 global $CFG, $SESSION;
3885 return (!empty($CFG->autolangusercreation) && !empty($SESSION->lang)) ? $SESSION->lang : $CFG->lang;
3889 * Creates a bare-bones user record
3891 * @todo Outline auth types and provide code example
3893 * @param string $username New user's username to add to record
3894 * @param string $password New user's password to add to record
3895 * @param string $auth Form of authentication required
3896 * @return stdClass A complete user object
3898 function create_user_record($username, $password, $auth = 'manual') {
3899 global $CFG, $DB, $SESSION;
3900 require_once($CFG->dirroot.'/user/profile/lib.php');
3901 require_once($CFG->dirroot.'/user/lib.php');
3903 // Just in case check text case.
3904 $username = trim(core_text::strtolower($username));
3906 $authplugin = get_auth_plugin($auth);
3907 $customfields = $authplugin->get_custom_user_profile_fields();
3908 $newuser = new stdClass();
3909 if ($newinfo = $authplugin->get_userinfo($username)) {
3910 $newinfo = truncate_userinfo($newinfo);
3911 foreach ($newinfo as $key => $value) {
3912 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3913 $newuser->$key = $value;
3918 if (!empty($newuser->email)) {
3919 if (email_is_not_allowed($newuser->email)) {
3920 unset($newuser->email);
3924 $newuser->auth = $auth;
3925 $newuser->username = $username;
3927 // Fix for MDL-8480
3928 // user CFG lang for user if $newuser->lang is empty
3929 // or $user->lang is not an installed language.
3930 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3931 $newuser->lang = get_newuser_language();
3933 $newuser->confirmed = 1;
3934 $newuser->lastip = getremoteaddr();
3935 $newuser->timecreated = time();
3936 $newuser->timemodified = $newuser->timecreated;
3937 $newuser->mnethostid = $CFG->mnet_localhost_id;
3939 $newuser->id = user_create_user($newuser, false, false);
3941 // Save user profile data.
3942 profile_save_data($newuser);
3944 $user = get_complete_user_data('id', $newuser->id);
3945 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3946 set_user_preference('auth_forcepasswordchange', 1, $user);
3948 // Set the password.
3949 update_internal_user_password($user, $password);
3951 // Trigger event.
3952 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3954 return $user;
3958 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3960 * @param string $username user's username to update the record
3961 * @return stdClass A complete user object
3963 function update_user_record($username) {
3964 global $DB, $CFG;
3965 // Just in case check text case.
3966 $username = trim(core_text::strtolower($username));
3968 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3969 return update_user_record_by_id($oldinfo->id);
3973 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3975 * @param int $id user id
3976 * @return stdClass A complete user object
3978 function update_user_record_by_id($id) {
3979 global $DB, $CFG;
3980 require_once($CFG->dirroot."/user/profile/lib.php");
3981 require_once($CFG->dirroot.'/user/lib.php');
3983 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3984 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3986 $newuser = array();
3987 $userauth = get_auth_plugin($oldinfo->auth);
3989 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3990 $newinfo = truncate_userinfo($newinfo);
3991 $customfields = $userauth->get_custom_user_profile_fields();
3993 foreach ($newinfo as $key => $value) {
3994 $iscustom = in_array($key, $customfields);
3995 if (!$iscustom) {
3996 $key = strtolower($key);
3998 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3999 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4000 // Unknown or must not be changed.
4001 continue;
4003 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
4004 continue;
4006 $confval = $userauth->config->{'field_updatelocal_' . $key};
4007 $lockval = $userauth->config->{'field_lock_' . $key};
4008 if ($confval === 'onlogin') {
4009 // MDL-4207 Don't overwrite modified user profile values with
4010 // empty LDAP values when 'unlocked if empty' is set. The purpose
4011 // of the setting 'unlocked if empty' is to allow the user to fill
4012 // in a value for the selected field _if LDAP is giving
4013 // nothing_ for this field. Thus it makes sense to let this value
4014 // stand in until LDAP is giving a value for this field.
4015 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4016 if ($iscustom || (in_array($key, $userauth->userfields) &&
4017 ((string)$oldinfo->$key !== (string)$value))) {
4018 $newuser[$key] = (string)$value;
4023 if ($newuser) {
4024 $newuser['id'] = $oldinfo->id;
4025 $newuser['timemodified'] = time();
4026 user_update_user((object) $newuser, false, false);
4028 // Save user profile data.
4029 profile_save_data((object) $newuser);
4031 // Trigger event.
4032 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4036 return get_complete_user_data('id', $oldinfo->id);
4040 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4042 * @param array $info Array of user properties to truncate if needed
4043 * @return array The now truncated information that was passed in
4045 function truncate_userinfo(array $info) {
4046 // Define the limits.
4047 $limit = array(
4048 'username' => 100,
4049 'idnumber' => 255,
4050 'firstname' => 100,
4051 'lastname' => 100,
4052 'email' => 100,
4053 'phone1' => 20,
4054 'phone2' => 20,
4055 'institution' => 255,
4056 'department' => 255,
4057 'address' => 255,
4058 'city' => 120,
4059 'country' => 2,
4062 // Apply where needed.
4063 foreach (array_keys($info) as $key) {
4064 if (!empty($limit[$key])) {
4065 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4069 return $info;
4073 * Marks user deleted in internal user database and notifies the auth plugin.
4074 * Also unenrols user from all roles and does other cleanup.
4076 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4078 * @param stdClass $user full user object before delete
4079 * @return boolean success
4080 * @throws coding_exception if invalid $user parameter detected
4082 function delete_user(stdClass $user) {
4083 global $CFG, $DB, $SESSION;
4084 require_once($CFG->libdir.'/grouplib.php');
4085 require_once($CFG->libdir.'/gradelib.php');
4086 require_once($CFG->dirroot.'/message/lib.php');
4087 require_once($CFG->dirroot.'/user/lib.php');
4089 // Make sure nobody sends bogus record type as parameter.
4090 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4091 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4094 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4095 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4096 debugging('Attempt to delete unknown user account.');
4097 return false;
4100 // There must be always exactly one guest record, originally the guest account was identified by username only,
4101 // now we use $CFG->siteguest for performance reasons.
4102 if ($user->username === 'guest' or isguestuser($user)) {
4103 debugging('Guest user account can not be deleted.');
4104 return false;
4107 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4108 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4109 if ($user->auth === 'manual' and is_siteadmin($user)) {
4110 debugging('Local administrator accounts can not be deleted.');
4111 return false;
4114 // Allow plugins to use this user object before we completely delete it.
4115 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4116 foreach ($pluginsfunction as $plugintype => $plugins) {
4117 foreach ($plugins as $pluginfunction) {
4118 $pluginfunction($user);
4123 // Keep user record before updating it, as we have to pass this to user_deleted event.
4124 $olduser = clone $user;
4126 // Keep a copy of user context, we need it for event.
4127 $usercontext = context_user::instance($user->id);
4129 // Delete all grades - backup is kept in grade_grades_history table.
4130 grade_user_delete($user->id);
4132 // TODO: remove from cohorts using standard API here.
4134 // Remove user tags.
4135 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4137 // Unconditionally unenrol from all courses.
4138 enrol_user_delete($user);
4140 // Unenrol from all roles in all contexts.
4141 // This might be slow but it is really needed - modules might do some extra cleanup!
4142 role_unassign_all(array('userid' => $user->id));
4144 // Notify the competency subsystem.
4145 \core_competency\api::hook_user_deleted($user->id);
4147 // Now do a brute force cleanup.
4149 // Delete all user events and subscription events.
4150 $DB->delete_records_select('event', 'userid = :userid AND subscriptionid IS NOT NULL', ['userid' => $user->id]);
4152 // Now, delete all calendar subscription from the user.
4153 $DB->delete_records('event_subscriptions', ['userid' => $user->id]);
4155 // Remove from all cohorts.
4156 $DB->delete_records('cohort_members', array('userid' => $user->id));
4158 // Remove from all groups.
4159 $DB->delete_records('groups_members', array('userid' => $user->id));
4161 // Brute force unenrol from all courses.
4162 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4164 // Purge user preferences.
4165 $DB->delete_records('user_preferences', array('userid' => $user->id));
4167 // Purge user extra profile info.
4168 $DB->delete_records('user_info_data', array('userid' => $user->id));
4170 // Purge log of previous password hashes.
4171 $DB->delete_records('user_password_history', array('userid' => $user->id));
4173 // Last course access not necessary either.
4174 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4175 // Remove all user tokens.
4176 $DB->delete_records('external_tokens', array('userid' => $user->id));
4178 // Unauthorise the user for all services.
4179 $DB->delete_records('external_services_users', array('userid' => $user->id));
4181 // Remove users private keys.
4182 $DB->delete_records('user_private_key', array('userid' => $user->id));
4184 // Remove users customised pages.
4185 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4187 // Remove user's oauth2 refresh tokens, if present.
4188 $DB->delete_records('oauth2_refresh_token', array('userid' => $user->id));
4190 // Delete user from $SESSION->bulk_users.
4191 if (isset($SESSION->bulk_users[$user->id])) {
4192 unset($SESSION->bulk_users[$user->id]);
4195 // Force logout - may fail if file based sessions used, sorry.
4196 \core\session\manager::kill_user_sessions($user->id);
4198 // Generate username from email address, or a fake email.
4199 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4201 $deltime = time();
4202 $deltimelength = core_text::strlen((string) $deltime);
4204 // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
4205 $delname = clean_param($delemail, PARAM_USERNAME);
4206 $delname = core_text::substr($delname, 0, 100 - ($deltimelength + 1)) . ".{$deltime}";
4208 // Workaround for bulk deletes of users with the same email address.
4209 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4210 $delname++;
4213 // Mark internal user record as "deleted".
4214 $updateuser = new stdClass();
4215 $updateuser->id = $user->id;
4216 $updateuser->deleted = 1;
4217 $updateuser->username = $delname; // Remember it just in case.
4218 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4219 $updateuser->idnumber = ''; // Clear this field to free it up.
4220 $updateuser->picture = 0;
4221 $updateuser->timemodified = $deltime;
4223 // Don't trigger update event, as user is being deleted.
4224 user_update_user($updateuser, false, false);
4226 // Delete all content associated with the user context, but not the context itself.
4227 $usercontext->delete_content();
4229 // Delete any search data.
4230 \core_search\manager::context_deleted($usercontext);
4232 // Any plugin that needs to cleanup should register this event.
4233 // Trigger event.
4234 $event = \core\event\user_deleted::create(
4235 array(
4236 'objectid' => $user->id,
4237 'relateduserid' => $user->id,
4238 'context' => $usercontext,
4239 'other' => array(
4240 'username' => $user->username,
4241 'email' => $user->email,
4242 'idnumber' => $user->idnumber,
4243 'picture' => $user->picture,
4244 'mnethostid' => $user->mnethostid
4248 $event->add_record_snapshot('user', $olduser);
4249 $event->trigger();
4251 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4252 // should know about this updated property persisted to the user's table.
4253 $user->timemodified = $updateuser->timemodified;
4255 // Notify auth plugin - do not block the delete even when plugin fails.
4256 $authplugin = get_auth_plugin($user->auth);
4257 $authplugin->user_delete($user);
4259 return true;
4263 * Retrieve the guest user object.
4265 * @return stdClass A {@link $USER} object
4267 function guest_user() {
4268 global $CFG, $DB;
4270 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4271 $newuser->confirmed = 1;
4272 $newuser->lang = get_newuser_language();
4273 $newuser->lastip = getremoteaddr();
4276 return $newuser;
4280 * Authenticates a user against the chosen authentication mechanism
4282 * Given a username and password, this function looks them
4283 * up using the currently selected authentication mechanism,
4284 * and if the authentication is successful, it returns a
4285 * valid $user object from the 'user' table.
4287 * Uses auth_ functions from the currently active auth module
4289 * After authenticate_user_login() returns success, you will need to
4290 * log that the user has logged in, and call complete_user_login() to set
4291 * the session up.
4293 * Note: this function works only with non-mnet accounts!
4295 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4296 * @param string $password User's password
4297 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4298 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4299 * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4300 * @return stdClass|false A {@link $USER} object or false if error
4302 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4303 global $CFG, $DB, $PAGE;
4304 require_once("$CFG->libdir/authlib.php");
4306 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4307 // we have found the user
4309 } else if (!empty($CFG->authloginviaemail)) {
4310 if ($email = clean_param($username, PARAM_EMAIL)) {
4311 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4312 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4313 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4314 if (count($users) === 1) {
4315 // Use email for login only if unique.
4316 $user = reset($users);
4317 $user = get_complete_user_data('id', $user->id);
4318 $username = $user->username;
4320 unset($users);
4324 // Make sure this request came from the login form.
4325 if (!\core\session\manager::validate_login_token($logintoken)) {
4326 $failurereason = AUTH_LOGIN_FAILED;
4328 // Trigger login failed event (specifying the ID of the found user, if available).
4329 \core\event\user_login_failed::create([
4330 'userid' => ($user->id ?? 0),
4331 'other' => [
4332 'username' => $username,
4333 'reason' => $failurereason,
4335 ])->trigger();
4337 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4338 return false;
4341 $authsenabled = get_enabled_auth_plugins();
4343 if ($user) {
4344 // Use manual if auth not set.
4345 $auth = empty($user->auth) ? 'manual' : $user->auth;
4347 if (in_array($user->auth, $authsenabled)) {
4348 $authplugin = get_auth_plugin($user->auth);
4349 $authplugin->pre_user_login_hook($user);
4352 if (!empty($user->suspended)) {
4353 $failurereason = AUTH_LOGIN_SUSPENDED;
4355 // Trigger login failed event.
4356 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4357 'other' => array('username' => $username, 'reason' => $failurereason)));
4358 $event->trigger();
4359 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4360 return false;
4362 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4363 // Legacy way to suspend user.
4364 $failurereason = AUTH_LOGIN_SUSPENDED;
4366 // Trigger login failed event.
4367 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4368 'other' => array('username' => $username, 'reason' => $failurereason)));
4369 $event->trigger();
4370 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4371 return false;
4373 $auths = array($auth);
4375 } else {
4376 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4377 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4378 $failurereason = AUTH_LOGIN_NOUSER;
4380 // Trigger login failed event.
4381 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4382 'reason' => $failurereason)));
4383 $event->trigger();
4384 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4385 return false;
4388 // User does not exist.
4389 $auths = $authsenabled;
4390 $user = new stdClass();
4391 $user->id = 0;
4394 if ($ignorelockout) {
4395 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4396 // or this function is called from a SSO script.
4397 } else if ($user->id) {
4398 // Verify login lockout after other ways that may prevent user login.
4399 if (login_is_lockedout($user)) {
4400 $failurereason = AUTH_LOGIN_LOCKOUT;
4402 // Trigger login failed event.
4403 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4404 'other' => array('username' => $username, 'reason' => $failurereason)));
4405 $event->trigger();
4407 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4408 return false;
4410 } else {
4411 // We can not lockout non-existing accounts.
4414 foreach ($auths as $auth) {
4415 $authplugin = get_auth_plugin($auth);
4417 // On auth fail fall through to the next plugin.
4418 if (!$authplugin->user_login($username, $password)) {
4419 continue;
4422 // Before performing login actions, check if user still passes password policy, if admin setting is enabled.
4423 if (!empty($CFG->passwordpolicycheckonlogin)) {
4424 $errmsg = '';
4425 $passed = check_password_policy($password, $errmsg, $user);
4426 if (!$passed) {
4427 // First trigger event for failure.
4428 $failedevent = \core\event\user_password_policy_failed::create_from_user($user);
4429 $failedevent->trigger();
4431 // If able to change password, set flag and move on.
4432 if ($authplugin->can_change_password()) {
4433 // Check if we are on internal change password page, or service is external, don't show notification.
4434 $internalchangeurl = new moodle_url('/login/change_password.php');
4435 if (!($PAGE->has_set_url() && $internalchangeurl->compare($PAGE->url)) && $authplugin->is_internal()) {
4436 \core\notification::error(get_string('passwordpolicynomatch', '', $errmsg));
4438 set_user_preference('auth_forcepasswordchange', 1, $user);
4439 } else if ($authplugin->can_reset_password()) {
4440 // Else force a reset if possible.
4441 \core\notification::error(get_string('forcepasswordresetnotice', '', $errmsg));
4442 redirect(new moodle_url('/login/forgot_password.php'));
4443 } else {
4444 $notifymsg = get_string('forcepasswordresetfailurenotice', '', $errmsg);
4445 // If support page is set, add link for help.
4446 if (!empty($CFG->supportpage)) {
4447 $link = \html_writer::link($CFG->supportpage, $CFG->supportpage);
4448 $link = \html_writer::tag('p', $link);
4449 $notifymsg .= $link;
4452 // If no change or reset is possible, add a notification for user.
4453 \core\notification::error($notifymsg);
4458 // Successful authentication.
4459 if ($user->id) {
4460 // User already exists in database.
4461 if (empty($user->auth)) {
4462 // For some reason auth isn't set yet.
4463 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4464 $user->auth = $auth;
4467 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4468 // the current hash algorithm while we have access to the user's password.
4469 update_internal_user_password($user, $password);
4471 if ($authplugin->is_synchronised_with_external()) {
4472 // Update user record from external DB.
4473 $user = update_user_record_by_id($user->id);
4475 } else {
4476 // The user is authenticated but user creation may be disabled.
4477 if (!empty($CFG->authpreventaccountcreation)) {
4478 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4480 // Trigger login failed event.
4481 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4482 'reason' => $failurereason)));
4483 $event->trigger();
4485 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4486 $_SERVER['HTTP_USER_AGENT']);
4487 return false;
4488 } else {
4489 $user = create_user_record($username, $password, $auth);
4493 $authplugin->sync_roles($user);
4495 foreach ($authsenabled as $hau) {
4496 $hauth = get_auth_plugin($hau);
4497 $hauth->user_authenticated_hook($user, $username, $password);
4500 if (empty($user->id)) {
4501 $failurereason = AUTH_LOGIN_NOUSER;
4502 // Trigger login failed event.
4503 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4504 'reason' => $failurereason)));
4505 $event->trigger();
4506 return false;
4509 if (!empty($user->suspended)) {
4510 // Just in case some auth plugin suspended account.
4511 $failurereason = AUTH_LOGIN_SUSPENDED;
4512 // Trigger login failed event.
4513 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4514 'other' => array('username' => $username, 'reason' => $failurereason)));
4515 $event->trigger();
4516 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4517 return false;
4520 login_attempt_valid($user);
4521 $failurereason = AUTH_LOGIN_OK;
4522 return $user;
4525 // Failed if all the plugins have failed.
4526 if (debugging('', DEBUG_ALL)) {
4527 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4530 if ($user->id) {
4531 login_attempt_failed($user);
4532 $failurereason = AUTH_LOGIN_FAILED;
4533 // Trigger login failed event.
4534 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4535 'other' => array('username' => $username, 'reason' => $failurereason)));
4536 $event->trigger();
4537 } else {
4538 $failurereason = AUTH_LOGIN_NOUSER;
4539 // Trigger login failed event.
4540 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4541 'reason' => $failurereason)));
4542 $event->trigger();
4545 return false;
4549 * Call to complete the user login process after authenticate_user_login()
4550 * has succeeded. It will setup the $USER variable and other required bits
4551 * and pieces.
4553 * NOTE:
4554 * - It will NOT log anything -- up to the caller to decide what to log.
4555 * - this function does not set any cookies any more!
4557 * @param stdClass $user
4558 * @return stdClass A {@link $USER} object - BC only, do not use
4560 function complete_user_login($user) {
4561 global $CFG, $DB, $USER, $SESSION;
4563 \core\session\manager::login_user($user);
4565 // Reload preferences from DB.
4566 unset($USER->preference);
4567 check_user_preferences_loaded($USER);
4569 // Update login times.
4570 update_user_login_times();
4572 // Extra session prefs init.
4573 set_login_session_preferences();
4575 // Trigger login event.
4576 $event = \core\event\user_loggedin::create(
4577 array(
4578 'userid' => $USER->id,
4579 'objectid' => $USER->id,
4580 'other' => array('username' => $USER->username),
4583 $event->trigger();
4585 // Check if the user is using a new browser or session (a new MoodleSession cookie is set in that case).
4586 // If the user is accessing from the same IP, ignore everything (most of the time will be a new session in the same browser).
4587 // Skip Web Service requests, CLI scripts, AJAX scripts, and request from the mobile app itself.
4588 $loginip = getremoteaddr();
4589 $isnewip = isset($SESSION->userpreviousip) && $SESSION->userpreviousip != $loginip;
4590 $isvalidenv = (!WS_SERVER && !CLI_SCRIPT && !NO_MOODLE_COOKIES) || PHPUNIT_TEST;
4592 if (!empty($SESSION->isnewsessioncookie) && $isnewip && $isvalidenv && !\core_useragent::is_moodle_app()) {
4594 $logintime = time();
4595 $ismoodleapp = false;
4596 $useragent = \core_useragent::get_user_agent_string();
4598 // Schedule adhoc task to sent a login notification to the user.
4599 $task = new \core\task\send_login_notifications();
4600 $task->set_userid($USER->id);
4601 $task->set_custom_data(compact('ismoodleapp', 'useragent', 'loginip', 'logintime'));
4602 $task->set_component('core');
4603 \core\task\manager::queue_adhoc_task($task);
4606 // Queue migrating the messaging data, if we need to.
4607 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4608 // Check if there are any legacy messages to migrate.
4609 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4610 \core_message\task\migrate_message_data::queue_task($USER->id);
4611 } else {
4612 set_user_preference('core_message_migrate_data', true, $USER->id);
4616 if (isguestuser()) {
4617 // No need to continue when user is THE guest.
4618 return $USER;
4621 if (CLI_SCRIPT) {
4622 // We can redirect to password change URL only in browser.
4623 return $USER;
4626 // Select password change url.
4627 $userauth = get_auth_plugin($USER->auth);
4629 // Check whether the user should be changing password.
4630 if (get_user_preferences('auth_forcepasswordchange', false)) {
4631 if ($userauth->can_change_password()) {
4632 if ($changeurl = $userauth->change_password_url()) {
4633 redirect($changeurl);
4634 } else {
4635 require_once($CFG->dirroot . '/login/lib.php');
4636 $SESSION->wantsurl = core_login_get_return_url();
4637 redirect($CFG->wwwroot.'/login/change_password.php');
4639 } else {
4640 throw new \moodle_exception('nopasswordchangeforced', 'auth');
4643 return $USER;
4647 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4649 * @param string $password String to check.
4650 * @return boolean True if the $password matches the format of an md5 sum.
4652 function password_is_legacy_hash($password) {
4653 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4657 * Compare password against hash stored in user object to determine if it is valid.
4659 * If necessary it also updates the stored hash to the current format.
4661 * @param stdClass $user (Password property may be updated).
4662 * @param string $password Plain text password.
4663 * @return bool True if password is valid.
4665 function validate_internal_user_password($user, $password) {
4666 global $CFG;
4668 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4669 // Internal password is not used at all, it can not validate.
4670 return false;
4673 // If hash isn't a legacy (md5) hash, validate using the library function.
4674 if (!password_is_legacy_hash($user->password)) {
4675 return password_verify($password, $user->password);
4678 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4679 // is valid we can then update it to the new algorithm.
4681 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4682 $validated = false;
4684 if ($user->password === md5($password.$sitesalt)
4685 or $user->password === md5($password)
4686 or $user->password === md5(addslashes($password).$sitesalt)
4687 or $user->password === md5(addslashes($password))) {
4688 // Note: we are intentionally using the addslashes() here because we
4689 // need to accept old password hashes of passwords with magic quotes.
4690 $validated = true;
4692 } else {
4693 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4694 $alt = 'passwordsaltalt'.$i;
4695 if (!empty($CFG->$alt)) {
4696 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4697 $validated = true;
4698 break;
4704 if ($validated) {
4705 // If the password matches the existing md5 hash, update to the
4706 // current hash algorithm while we have access to the user's password.
4707 update_internal_user_password($user, $password);
4710 return $validated;
4714 * Calculate hash for a plain text password.
4716 * @param string $password Plain text password to be hashed.
4717 * @param bool $fasthash If true, use a low cost factor when generating the hash
4718 * This is much faster to generate but makes the hash
4719 * less secure. It is used when lots of hashes need to
4720 * be generated quickly.
4721 * @return string The hashed password.
4723 * @throws moodle_exception If a problem occurs while generating the hash.
4725 function hash_internal_user_password($password, $fasthash = false) {
4726 global $CFG;
4728 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4729 $options = ($fasthash) ? array('cost' => 4) : array();
4731 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4733 if ($generatedhash === false || $generatedhash === null) {
4734 throw new moodle_exception('Failed to generate password hash.');
4737 return $generatedhash;
4741 * Update password hash in user object (if necessary).
4743 * The password is updated if:
4744 * 1. The password has changed (the hash of $user->password is different
4745 * to the hash of $password).
4746 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4747 * md5 algorithm).
4749 * Updating the password will modify the $user object and the database
4750 * record to use the current hashing algorithm.
4751 * It will remove Web Services user tokens too.
4753 * @param stdClass $user User object (password property may be updated).
4754 * @param string $password Plain text password.
4755 * @param bool $fasthash If true, use a low cost factor when generating the hash
4756 * This is much faster to generate but makes the hash
4757 * less secure. It is used when lots of hashes need to
4758 * be generated quickly.
4759 * @return bool Always returns true.
4761 function update_internal_user_password($user, $password, $fasthash = false) {
4762 global $CFG, $DB;
4764 // Figure out what the hashed password should be.
4765 if (!isset($user->auth)) {
4766 debugging('User record in update_internal_user_password() must include field auth',
4767 DEBUG_DEVELOPER);
4768 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4770 $authplugin = get_auth_plugin($user->auth);
4771 if ($authplugin->prevent_local_passwords()) {
4772 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4773 } else {
4774 $hashedpassword = hash_internal_user_password($password, $fasthash);
4777 $algorithmchanged = false;
4779 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4780 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4781 $passwordchanged = ($user->password !== $hashedpassword);
4783 } else if (isset($user->password)) {
4784 // If verification fails then it means the password has changed.
4785 $passwordchanged = !password_verify($password, $user->password);
4786 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4787 } else {
4788 // While creating new user, password in unset in $user object, to avoid
4789 // saving it with user_create()
4790 $passwordchanged = true;
4793 if ($passwordchanged || $algorithmchanged) {
4794 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4795 $user->password = $hashedpassword;
4797 // Trigger event.
4798 $user = $DB->get_record('user', array('id' => $user->id));
4799 \core\event\user_password_updated::create_from_user($user)->trigger();
4801 // Remove WS user tokens.
4802 if (!empty($CFG->passwordchangetokendeletion)) {
4803 require_once($CFG->dirroot.'/webservice/lib.php');
4804 webservice::delete_user_ws_tokens($user->id);
4808 return true;
4812 * Get a complete user record, which includes all the info in the user record.
4814 * Intended for setting as $USER session variable
4816 * @param string $field The user field to be checked for a given value.
4817 * @param string $value The value to match for $field.
4818 * @param int $mnethostid
4819 * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4820 * found. Otherwise, it will just return false.
4821 * @return mixed False, or A {@link $USER} object.
4823 function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4824 global $CFG, $DB;
4826 if (!$field || !$value) {
4827 return false;
4830 // Change the field to lowercase.
4831 $field = core_text::strtolower($field);
4833 // List of case insensitive fields.
4834 $caseinsensitivefields = ['email'];
4836 // Username input is forced to lowercase and should be case sensitive.
4837 if ($field == 'username') {
4838 $value = core_text::strtolower($value);
4841 // Build the WHERE clause for an SQL query.
4842 $params = array('fieldval' => $value);
4844 // Do a case-insensitive query, if necessary. These are generally very expensive. The performance can be improved on some DBs
4845 // such as MySQL by pre-filtering users with accent-insensitive subselect.
4846 if (in_array($field, $caseinsensitivefields)) {
4847 $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4848 $idsubselect = $DB->sql_equal($field, ':fieldval2', false, false);
4849 $params['fieldval2'] = $value;
4850 } else {
4851 $fieldselect = "$field = :fieldval";
4852 $idsubselect = '';
4854 $constraints = "$fieldselect AND deleted <> 1";
4856 // If we are loading user data based on anything other than id,
4857 // we must also restrict our search based on mnet host.
4858 if ($field != 'id') {
4859 if (empty($mnethostid)) {
4860 // If empty, we restrict to local users.
4861 $mnethostid = $CFG->mnet_localhost_id;
4864 if (!empty($mnethostid)) {
4865 $params['mnethostid'] = $mnethostid;
4866 $constraints .= " AND mnethostid = :mnethostid";
4869 if ($idsubselect) {
4870 $constraints .= " AND id IN (SELECT id FROM {user} WHERE {$idsubselect})";
4873 // Get all the basic user data.
4874 try {
4875 // Make sure that there's only a single record that matches our query.
4876 // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4877 // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4878 $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST);
4879 } catch (dml_exception $exception) {
4880 if ($throwexception) {
4881 throw $exception;
4882 } else {
4883 // Return false when no records or multiple records were found.
4884 return false;
4888 // Get various settings and preferences.
4890 // Preload preference cache.
4891 check_user_preferences_loaded($user);
4893 // Load course enrolment related stuff.
4894 $user->lastcourseaccess = array(); // During last session.
4895 $user->currentcourseaccess = array(); // During current session.
4896 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4897 foreach ($lastaccesses as $lastaccess) {
4898 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4902 // Add cohort theme.
4903 if (!empty($CFG->allowcohortthemes)) {
4904 require_once($CFG->dirroot . '/cohort/lib.php');
4905 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4906 $user->cohorttheme = $cohorttheme;
4910 // Add the custom profile fields to the user record.
4911 $user->profile = array();
4912 if (!isguestuser($user)) {
4913 require_once($CFG->dirroot.'/user/profile/lib.php');
4914 profile_load_custom_fields($user);
4917 // Rewrite some variables if necessary.
4918 if (!empty($user->description)) {
4919 // No need to cart all of it around.
4920 $user->description = true;
4922 if (isguestuser($user)) {
4923 // Guest language always same as site.
4924 $user->lang = get_newuser_language();
4925 // Name always in current language.
4926 $user->firstname = get_string('guestuser');
4927 $user->lastname = ' ';
4930 return $user;
4934 * Validate a password against the configured password policy
4936 * @param string $password the password to be checked against the password policy
4937 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4938 * @param stdClass $user the user object to perform password validation against. Defaults to null if not provided.
4940 * @return bool true if the password is valid according to the policy. false otherwise.
4942 function check_password_policy($password, &$errmsg, $user = null) {
4943 global $CFG;
4945 if (!empty($CFG->passwordpolicy)) {
4946 $errmsg = '';
4947 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4948 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4950 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4951 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4953 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4954 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4956 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4957 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4959 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4960 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4962 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4963 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4966 // Fire any additional password policy functions from plugins.
4967 // Plugin functions should output an error message string or empty string for success.
4968 $pluginsfunction = get_plugins_with_function('check_password_policy');
4969 foreach ($pluginsfunction as $plugintype => $plugins) {
4970 foreach ($plugins as $pluginfunction) {
4971 $pluginerr = $pluginfunction($password, $user);
4972 if ($pluginerr) {
4973 $errmsg .= '<div>'. $pluginerr .'</div>';
4979 if ($errmsg == '') {
4980 return true;
4981 } else {
4982 return false;
4988 * When logging in, this function is run to set certain preferences for the current SESSION.
4990 function set_login_session_preferences() {
4991 global $SESSION;
4993 $SESSION->justloggedin = true;
4995 unset($SESSION->lang);
4996 unset($SESSION->forcelang);
4997 unset($SESSION->load_navigation_admin);
5002 * Delete a course, including all related data from the database, and any associated files.
5004 * @param mixed $courseorid The id of the course or course object to delete.
5005 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5006 * @return bool true if all the removals succeeded. false if there were any failures. If this
5007 * method returns false, some of the removals will probably have succeeded, and others
5008 * failed, but you have no way of knowing which.
5010 function delete_course($courseorid, $showfeedback = true) {
5011 global $DB;
5013 if (is_object($courseorid)) {
5014 $courseid = $courseorid->id;
5015 $course = $courseorid;
5016 } else {
5017 $courseid = $courseorid;
5018 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
5019 return false;
5022 $context = context_course::instance($courseid);
5024 // Frontpage course can not be deleted!!
5025 if ($courseid == SITEID) {
5026 return false;
5029 // Allow plugins to use this course before we completely delete it.
5030 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
5031 foreach ($pluginsfunction as $plugintype => $plugins) {
5032 foreach ($plugins as $pluginfunction) {
5033 $pluginfunction($course);
5038 // Tell the search manager we are about to delete a course. This prevents us sending updates
5039 // for each individual context being deleted.
5040 \core_search\manager::course_deleting_start($courseid);
5042 $handler = core_course\customfield\course_handler::create();
5043 $handler->delete_instance($courseid);
5045 // Make the course completely empty.
5046 remove_course_contents($courseid, $showfeedback);
5048 // Delete the course and related context instance.
5049 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
5051 $DB->delete_records("course", array("id" => $courseid));
5052 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5054 // Reset all course related caches here.
5055 core_courseformat\base::reset_course_cache($courseid);
5057 // Tell search that we have deleted the course so it can delete course data from the index.
5058 \core_search\manager::course_deleting_finish($courseid);
5060 // Trigger a course deleted event.
5061 $event = \core\event\course_deleted::create(array(
5062 'objectid' => $course->id,
5063 'context' => $context,
5064 'other' => array(
5065 'shortname' => $course->shortname,
5066 'fullname' => $course->fullname,
5067 'idnumber' => $course->idnumber
5070 $event->add_record_snapshot('course', $course);
5071 $event->trigger();
5073 return true;
5077 * Clear a course out completely, deleting all content but don't delete the course itself.
5079 * This function does not verify any permissions.
5081 * Please note this function also deletes all user enrolments,
5082 * enrolment instances and role assignments by default.
5084 * $options:
5085 * - 'keep_roles_and_enrolments' - false by default
5086 * - 'keep_groups_and_groupings' - false by default
5088 * @param int $courseid The id of the course that is being deleted
5089 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5090 * @param array $options extra options
5091 * @return bool true if all the removals succeeded. false if there were any failures. If this
5092 * method returns false, some of the removals will probably have succeeded, and others
5093 * failed, but you have no way of knowing which.
5095 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5096 global $CFG, $DB, $OUTPUT;
5098 require_once($CFG->libdir.'/badgeslib.php');
5099 require_once($CFG->libdir.'/completionlib.php');
5100 require_once($CFG->libdir.'/questionlib.php');
5101 require_once($CFG->libdir.'/gradelib.php');
5102 require_once($CFG->dirroot.'/group/lib.php');
5103 require_once($CFG->dirroot.'/comment/lib.php');
5104 require_once($CFG->dirroot.'/rating/lib.php');
5105 require_once($CFG->dirroot.'/notes/lib.php');
5107 // Handle course badges.
5108 badges_handle_course_deletion($courseid);
5110 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5111 $strdeleted = get_string('deleted').' - ';
5113 // Some crazy wishlist of stuff we should skip during purging of course content.
5114 $options = (array)$options;
5116 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5117 $coursecontext = context_course::instance($courseid);
5118 $fs = get_file_storage();
5120 // Delete course completion information, this has to be done before grades and enrols.
5121 $cc = new completion_info($course);
5122 $cc->clear_criteria();
5123 if ($showfeedback) {
5124 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5127 // Remove all data from gradebook - this needs to be done before course modules
5128 // because while deleting this information, the system may need to reference
5129 // the course modules that own the grades.
5130 remove_course_grades($courseid, $showfeedback);
5131 remove_grade_letters($coursecontext, $showfeedback);
5133 // Delete course blocks in any all child contexts,
5134 // they may depend on modules so delete them first.
5135 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5136 foreach ($childcontexts as $childcontext) {
5137 blocks_delete_all_for_context($childcontext->id);
5139 unset($childcontexts);
5140 blocks_delete_all_for_context($coursecontext->id);
5141 if ($showfeedback) {
5142 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5145 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $courseid]);
5146 rebuild_course_cache($courseid, true);
5148 // Get the list of all modules that are properly installed.
5149 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5151 // Delete every instance of every module,
5152 // this has to be done before deleting of course level stuff.
5153 $locations = core_component::get_plugin_list('mod');
5154 foreach ($locations as $modname => $moddir) {
5155 if ($modname === 'NEWMODULE') {
5156 continue;
5158 if (array_key_exists($modname, $allmodules)) {
5159 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5160 FROM {".$modname."} m
5161 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5162 WHERE m.course = :courseid";
5163 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5164 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5166 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5167 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5169 if ($instances) {
5170 foreach ($instances as $cm) {
5171 if ($cm->id) {
5172 // Delete activity context questions and question categories.
5173 question_delete_activity($cm);
5174 // Notify the competency subsystem.
5175 \core_competency\api::hook_course_module_deleted($cm);
5177 if (function_exists($moddelete)) {
5178 // This purges all module data in related tables, extra user prefs, settings, etc.
5179 $moddelete($cm->modinstance);
5180 } else {
5181 // NOTE: we should not allow installation of modules with missing delete support!
5182 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5183 $DB->delete_records($modname, array('id' => $cm->modinstance));
5186 if ($cm->id) {
5187 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5188 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5189 $DB->delete_records('course_modules_completion', ['coursemoduleid' => $cm->id]);
5190 $DB->delete_records('course_modules', array('id' => $cm->id));
5191 rebuild_course_cache($cm->course, true);
5195 if ($instances and $showfeedback) {
5196 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5198 } else {
5199 // Ooops, this module is not properly installed, force-delete it in the next block.
5203 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5205 // Delete completion defaults.
5206 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5208 // Remove all data from availability and completion tables that is associated
5209 // with course-modules belonging to this course. Note this is done even if the
5210 // features are not enabled now, in case they were enabled previously.
5211 $DB->delete_records_subquery('course_modules_completion', 'coursemoduleid', 'id',
5212 'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
5214 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5215 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5216 $allmodulesbyid = array_flip($allmodules);
5217 foreach ($cms as $cm) {
5218 if (array_key_exists($cm->module, $allmodulesbyid)) {
5219 try {
5220 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5221 } catch (Exception $e) {
5222 // Ignore weird or missing table problems.
5225 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5226 $DB->delete_records('course_modules', array('id' => $cm->id));
5227 rebuild_course_cache($cm->course, true);
5230 if ($showfeedback) {
5231 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5234 // Delete questions and question categories.
5235 question_delete_course($course);
5236 if ($showfeedback) {
5237 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5240 // Delete content bank contents.
5241 $cb = new \core_contentbank\contentbank();
5242 $cbdeleted = $cb->delete_contents($coursecontext);
5243 if ($showfeedback && $cbdeleted) {
5244 echo $OUTPUT->notification($strdeleted.get_string('contentbank', 'contentbank'), 'notifysuccess');
5247 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5248 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5249 foreach ($childcontexts as $childcontext) {
5250 $childcontext->delete();
5252 unset($childcontexts);
5254 // Remove roles and enrolments by default.
5255 if (empty($options['keep_roles_and_enrolments'])) {
5256 // This hack is used in restore when deleting contents of existing course.
5257 // During restore, we should remove only enrolment related data that the user performing the restore has a
5258 // permission to remove.
5259 $userid = $options['userid'] ?? null;
5260 enrol_course_delete($course, $userid);
5261 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5262 if ($showfeedback) {
5263 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5267 // Delete any groups, removing members and grouping/course links first.
5268 if (empty($options['keep_groups_and_groupings'])) {
5269 groups_delete_groupings($course->id, $showfeedback);
5270 groups_delete_groups($course->id, $showfeedback);
5273 // Filters be gone!
5274 filter_delete_all_for_context($coursecontext->id);
5276 // Notes, you shall not pass!
5277 note_delete_all($course->id);
5279 // Die comments!
5280 comment::delete_comments($coursecontext->id);
5282 // Ratings are history too.
5283 $delopt = new stdclass();
5284 $delopt->contextid = $coursecontext->id;
5285 $rm = new rating_manager();
5286 $rm->delete_ratings($delopt);
5288 // Delete course tags.
5289 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5291 // Give the course format the opportunity to remove its obscure data.
5292 $format = course_get_format($course);
5293 $format->delete_format_data();
5295 // Notify the competency subsystem.
5296 \core_competency\api::hook_course_deleted($course);
5298 // Delete calendar events.
5299 $DB->delete_records('event', array('courseid' => $course->id));
5300 $fs->delete_area_files($coursecontext->id, 'calendar');
5302 // Delete all related records in other core tables that may have a courseid
5303 // This array stores the tables that need to be cleared, as
5304 // table_name => column_name that contains the course id.
5305 $tablestoclear = array(
5306 'backup_courses' => 'courseid', // Scheduled backup stuff.
5307 'user_lastaccess' => 'courseid', // User access info.
5309 foreach ($tablestoclear as $table => $col) {
5310 $DB->delete_records($table, array($col => $course->id));
5313 // Delete all course backup files.
5314 $fs->delete_area_files($coursecontext->id, 'backup');
5316 // Cleanup course record - remove links to deleted stuff.
5317 $oldcourse = new stdClass();
5318 $oldcourse->id = $course->id;
5319 $oldcourse->summary = '';
5320 $oldcourse->cacherev = 0;
5321 $oldcourse->legacyfiles = 0;
5322 if (!empty($options['keep_groups_and_groupings'])) {
5323 $oldcourse->defaultgroupingid = 0;
5325 $DB->update_record('course', $oldcourse);
5327 // Delete course sections.
5328 $DB->delete_records('course_sections', array('course' => $course->id));
5330 // Delete legacy, section and any other course files.
5331 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5333 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5334 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5335 // Easy, do not delete the context itself...
5336 $coursecontext->delete_content();
5337 } else {
5338 // Hack alert!!!!
5339 // We can not drop all context stuff because it would bork enrolments and roles,
5340 // there might be also files used by enrol plugins...
5343 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5344 // also some non-standard unsupported plugins may try to store something there.
5345 fulldelete($CFG->dataroot.'/'.$course->id);
5347 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5348 course_modinfo::purge_course_cache($courseid);
5350 // Trigger a course content deleted event.
5351 $event = \core\event\course_content_deleted::create(array(
5352 'objectid' => $course->id,
5353 'context' => $coursecontext,
5354 'other' => array('shortname' => $course->shortname,
5355 'fullname' => $course->fullname,
5356 'options' => $options) // Passing this for legacy reasons.
5358 $event->add_record_snapshot('course', $course);
5359 $event->trigger();
5361 return true;
5365 * Change dates in module - used from course reset.
5367 * @param string $modname forum, assignment, etc
5368 * @param array $fields array of date fields from mod table
5369 * @param int $timeshift time difference
5370 * @param int $courseid
5371 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5372 * @return bool success
5374 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5375 global $CFG, $DB;
5376 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5378 $return = true;
5379 $params = array($timeshift, $courseid);
5380 foreach ($fields as $field) {
5381 $updatesql = "UPDATE {".$modname."}
5382 SET $field = $field + ?
5383 WHERE course=? AND $field<>0";
5384 if ($modid) {
5385 $updatesql .= ' AND id=?';
5386 $params[] = $modid;
5388 $return = $DB->execute($updatesql, $params) && $return;
5391 return $return;
5395 * This function will empty a course of user data.
5396 * It will retain the activities and the structure of the course.
5398 * @param object $data an object containing all the settings including courseid (without magic quotes)
5399 * @return array status array of array component, item, error
5401 function reset_course_userdata($data) {
5402 global $CFG, $DB;
5403 require_once($CFG->libdir.'/gradelib.php');
5404 require_once($CFG->libdir.'/completionlib.php');
5405 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5406 require_once($CFG->dirroot.'/group/lib.php');
5408 $data->courseid = $data->id;
5409 $context = context_course::instance($data->courseid);
5411 $eventparams = array(
5412 'context' => $context,
5413 'courseid' => $data->id,
5414 'other' => array(
5415 'reset_options' => (array) $data
5418 $event = \core\event\course_reset_started::create($eventparams);
5419 $event->trigger();
5421 // Calculate the time shift of dates.
5422 if (!empty($data->reset_start_date)) {
5423 // Time part of course startdate should be zero.
5424 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5425 } else {
5426 $data->timeshift = 0;
5429 // Result array: component, item, error.
5430 $status = array();
5432 // Start the resetting.
5433 $componentstr = get_string('general');
5435 // Move the course start time.
5436 if (!empty($data->reset_start_date) and $data->timeshift) {
5437 // Change course start data.
5438 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5439 // Update all course and group events - do not move activity events.
5440 $updatesql = "UPDATE {event}
5441 SET timestart = timestart + ?
5442 WHERE courseid=? AND instance=0";
5443 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5445 // Update any date activity restrictions.
5446 if ($CFG->enableavailability) {
5447 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5450 // Update completion expected dates.
5451 if ($CFG->enablecompletion) {
5452 $modinfo = get_fast_modinfo($data->courseid);
5453 $changed = false;
5454 foreach ($modinfo->get_cms() as $cm) {
5455 if ($cm->completion && !empty($cm->completionexpected)) {
5456 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5457 array('id' => $cm->id));
5458 $changed = true;
5462 // Clear course cache if changes made.
5463 if ($changed) {
5464 rebuild_course_cache($data->courseid, true);
5467 // Update course date completion criteria.
5468 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5471 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5474 if (!empty($data->reset_end_date)) {
5475 // If the user set a end date value respect it.
5476 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5477 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5478 // If there is a time shift apply it to the end date as well.
5479 $enddate = $data->reset_end_date_old + $data->timeshift;
5480 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5483 if (!empty($data->reset_events)) {
5484 $DB->delete_records('event', array('courseid' => $data->courseid));
5485 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5488 if (!empty($data->reset_notes)) {
5489 require_once($CFG->dirroot.'/notes/lib.php');
5490 note_delete_all($data->courseid);
5491 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5494 if (!empty($data->delete_blog_associations)) {
5495 require_once($CFG->dirroot.'/blog/lib.php');
5496 blog_remove_associations_for_course($data->courseid);
5497 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5500 if (!empty($data->reset_completion)) {
5501 // Delete course and activity completion information.
5502 $course = $DB->get_record('course', array('id' => $data->courseid));
5503 $cc = new completion_info($course);
5504 $cc->delete_all_completion_data();
5505 $status[] = array('component' => $componentstr,
5506 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5509 if (!empty($data->reset_competency_ratings)) {
5510 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5511 $status[] = array('component' => $componentstr,
5512 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5515 $componentstr = get_string('roles');
5517 if (!empty($data->reset_roles_overrides)) {
5518 $children = $context->get_child_contexts();
5519 foreach ($children as $child) {
5520 $child->delete_capabilities();
5522 $context->delete_capabilities();
5523 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5526 if (!empty($data->reset_roles_local)) {
5527 $children = $context->get_child_contexts();
5528 foreach ($children as $child) {
5529 role_unassign_all(array('contextid' => $child->id));
5531 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5534 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5535 $data->unenrolled = array();
5536 if (!empty($data->unenrol_users)) {
5537 $plugins = enrol_get_plugins(true);
5538 $instances = enrol_get_instances($data->courseid, true);
5539 foreach ($instances as $key => $instance) {
5540 if (!isset($plugins[$instance->enrol])) {
5541 unset($instances[$key]);
5542 continue;
5546 $usersroles = enrol_get_course_users_roles($data->courseid);
5547 foreach ($data->unenrol_users as $withroleid) {
5548 if ($withroleid) {
5549 $sql = "SELECT ue.*
5550 FROM {user_enrolments} ue
5551 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5552 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5553 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5554 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5556 } else {
5557 // Without any role assigned at course context.
5558 $sql = "SELECT ue.*
5559 FROM {user_enrolments} ue
5560 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5561 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5562 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5563 WHERE ra.id IS null";
5564 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5567 $rs = $DB->get_recordset_sql($sql, $params);
5568 foreach ($rs as $ue) {
5569 if (!isset($instances[$ue->enrolid])) {
5570 continue;
5572 $instance = $instances[$ue->enrolid];
5573 $plugin = $plugins[$instance->enrol];
5574 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5575 continue;
5578 if ($withroleid && count($usersroles[$ue->userid]) > 1) {
5579 // If we don't remove all roles and user has more than one role, just remove this role.
5580 role_unassign($withroleid, $ue->userid, $context->id);
5582 unset($usersroles[$ue->userid][$withroleid]);
5583 } else {
5584 // If we remove all roles or user has only one role, unenrol user from course.
5585 $plugin->unenrol_user($instance, $ue->userid);
5587 $data->unenrolled[$ue->userid] = $ue->userid;
5589 $rs->close();
5592 if (!empty($data->unenrolled)) {
5593 $status[] = array(
5594 'component' => $componentstr,
5595 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5596 'error' => false
5600 $componentstr = get_string('groups');
5602 // Remove all group members.
5603 if (!empty($data->reset_groups_members)) {
5604 groups_delete_group_members($data->courseid);
5605 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5608 // Remove all groups.
5609 if (!empty($data->reset_groups_remove)) {
5610 groups_delete_groups($data->courseid, false);
5611 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5614 // Remove all grouping members.
5615 if (!empty($data->reset_groupings_members)) {
5616 groups_delete_groupings_groups($data->courseid, false);
5617 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5620 // Remove all groupings.
5621 if (!empty($data->reset_groupings_remove)) {
5622 groups_delete_groupings($data->courseid, false);
5623 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5626 // Look in every instance of every module for data to delete.
5627 $unsupportedmods = array();
5628 if ($allmods = $DB->get_records('modules') ) {
5629 foreach ($allmods as $mod) {
5630 $modname = $mod->name;
5631 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5632 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5633 if (file_exists($modfile)) {
5634 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5635 continue; // Skip mods with no instances.
5637 include_once($modfile);
5638 if (function_exists($moddeleteuserdata)) {
5639 $modstatus = $moddeleteuserdata($data);
5640 if (is_array($modstatus)) {
5641 $status = array_merge($status, $modstatus);
5642 } else {
5643 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5645 } else {
5646 $unsupportedmods[] = $mod;
5648 } else {
5649 debugging('Missing lib.php in '.$modname.' module!');
5651 // Update calendar events for all modules.
5652 course_module_bulk_update_calendar_events($modname, $data->courseid);
5656 // Mention unsupported mods.
5657 if (!empty($unsupportedmods)) {
5658 foreach ($unsupportedmods as $mod) {
5659 $status[] = array(
5660 'component' => get_string('modulenameplural', $mod->name),
5661 'item' => '',
5662 'error' => get_string('resetnotimplemented')
5667 $componentstr = get_string('gradebook', 'grades');
5668 // Reset gradebook,.
5669 if (!empty($data->reset_gradebook_items)) {
5670 remove_course_grades($data->courseid, false);
5671 grade_grab_course_grades($data->courseid);
5672 grade_regrade_final_grades($data->courseid);
5673 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5675 } else if (!empty($data->reset_gradebook_grades)) {
5676 grade_course_reset($data->courseid);
5677 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5679 // Reset comments.
5680 if (!empty($data->reset_comments)) {
5681 require_once($CFG->dirroot.'/comment/lib.php');
5682 comment::reset_course_page_comments($context);
5685 $event = \core\event\course_reset_ended::create($eventparams);
5686 $event->trigger();
5688 return $status;
5692 * Generate an email processing address.
5694 * @param int $modid
5695 * @param string $modargs
5696 * @return string Returns email processing address
5698 function generate_email_processing_address($modid, $modargs) {
5699 global $CFG;
5701 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5702 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5708 * @todo Finish documenting this function
5710 * @param string $modargs
5711 * @param string $body Currently unused
5713 function moodle_process_email($modargs, $body) {
5714 global $DB;
5716 // The first char should be an unencoded letter. We'll take this as an action.
5717 switch ($modargs[0]) {
5718 case 'B': { // Bounce.
5719 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5720 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5721 // Check the half md5 of their email.
5722 $md5check = substr(md5($user->email), 0, 16);
5723 if ($md5check == substr($modargs, -16)) {
5724 set_bounce_count($user);
5726 // Else maybe they've already changed it?
5729 break;
5730 // Maybe more later?
5734 // CORRESPONDENCE.
5737 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5739 * @param string $action 'get', 'buffer', 'close' or 'flush'
5740 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5742 function get_mailer($action='get') {
5743 global $CFG;
5745 /** @var moodle_phpmailer $mailer */
5746 static $mailer = null;
5747 static $counter = 0;
5749 if (!isset($CFG->smtpmaxbulk)) {
5750 $CFG->smtpmaxbulk = 1;
5753 if ($action == 'get') {
5754 $prevkeepalive = false;
5756 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5757 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5758 $counter++;
5759 // Reset the mailer.
5760 $mailer->Priority = 3;
5761 $mailer->CharSet = 'UTF-8'; // Our default.
5762 $mailer->ContentType = "text/plain";
5763 $mailer->Encoding = "8bit";
5764 $mailer->From = "root@localhost";
5765 $mailer->FromName = "Root User";
5766 $mailer->Sender = "";
5767 $mailer->Subject = "";
5768 $mailer->Body = "";
5769 $mailer->AltBody = "";
5770 $mailer->ConfirmReadingTo = "";
5772 $mailer->clearAllRecipients();
5773 $mailer->clearReplyTos();
5774 $mailer->clearAttachments();
5775 $mailer->clearCustomHeaders();
5776 return $mailer;
5779 $prevkeepalive = $mailer->SMTPKeepAlive;
5780 get_mailer('flush');
5783 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5784 $mailer = new moodle_phpmailer();
5786 $counter = 1;
5788 if ($CFG->smtphosts == 'qmail') {
5789 // Use Qmail system.
5790 $mailer->isQmail();
5792 } else if (empty($CFG->smtphosts)) {
5793 // Use PHP mail() = sendmail.
5794 $mailer->isMail();
5796 } else {
5797 // Use SMTP directly.
5798 $mailer->isSMTP();
5799 if (!empty($CFG->debugsmtp) && (!empty($CFG->debugdeveloper))) {
5800 $mailer->SMTPDebug = 3;
5802 // Specify main and backup servers.
5803 $mailer->Host = $CFG->smtphosts;
5804 // Specify secure connection protocol.
5805 $mailer->SMTPSecure = $CFG->smtpsecure;
5806 // Use previous keepalive.
5807 $mailer->SMTPKeepAlive = $prevkeepalive;
5809 if ($CFG->smtpuser) {
5810 // Use SMTP authentication.
5811 $mailer->SMTPAuth = true;
5812 $mailer->Username = $CFG->smtpuser;
5813 $mailer->Password = $CFG->smtppass;
5817 return $mailer;
5820 $nothing = null;
5822 // Keep smtp session open after sending.
5823 if ($action == 'buffer') {
5824 if (!empty($CFG->smtpmaxbulk)) {
5825 get_mailer('flush');
5826 $m = get_mailer();
5827 if ($m->Mailer == 'smtp') {
5828 $m->SMTPKeepAlive = true;
5831 return $nothing;
5834 // Close smtp session, but continue buffering.
5835 if ($action == 'flush') {
5836 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5837 if (!empty($mailer->SMTPDebug)) {
5838 echo '<pre>'."\n";
5840 $mailer->SmtpClose();
5841 if (!empty($mailer->SMTPDebug)) {
5842 echo '</pre>';
5845 return $nothing;
5848 // Close smtp session, do not buffer anymore.
5849 if ($action == 'close') {
5850 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5851 get_mailer('flush');
5852 $mailer->SMTPKeepAlive = false;
5854 $mailer = null; // Better force new instance.
5855 return $nothing;
5860 * A helper function to test for email diversion
5862 * @param string $email
5863 * @return bool Returns true if the email should be diverted
5865 function email_should_be_diverted($email) {
5866 global $CFG;
5868 if (empty($CFG->divertallemailsto)) {
5869 return false;
5872 if (empty($CFG->divertallemailsexcept)) {
5873 return true;
5876 $patterns = array_map('trim', preg_split("/[\s,]+/", $CFG->divertallemailsexcept, -1, PREG_SPLIT_NO_EMPTY));
5877 foreach ($patterns as $pattern) {
5878 if (preg_match("/$pattern/", $email)) {
5879 return false;
5883 return true;
5887 * Generate a unique email Message-ID using the moodle domain and install path
5889 * @param string $localpart An optional unique message id prefix.
5890 * @return string The formatted ID ready for appending to the email headers.
5892 function generate_email_messageid($localpart = null) {
5893 global $CFG;
5895 $urlinfo = parse_url($CFG->wwwroot);
5896 $base = '@' . $urlinfo['host'];
5898 // If multiple moodles are on the same domain we want to tell them
5899 // apart so we add the install path to the local part. This means
5900 // that the id local part should never contain a / character so
5901 // we can correctly parse the id to reassemble the wwwroot.
5902 if (isset($urlinfo['path'])) {
5903 $base = $urlinfo['path'] . $base;
5906 if (empty($localpart)) {
5907 $localpart = uniqid('', true);
5910 // Because we may have an option /installpath suffix to the local part
5911 // of the id we need to escape any / chars which are in the $localpart.
5912 $localpart = str_replace('/', '%2F', $localpart);
5914 return '<' . $localpart . $base . '>';
5918 * Send an email to a specified user
5920 * @param stdClass $user A {@link $USER} object
5921 * @param stdClass $from A {@link $USER} object
5922 * @param string $subject plain text subject line of the email
5923 * @param string $messagetext plain text version of the message
5924 * @param string $messagehtml complete html version of the message (optional)
5925 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in one of
5926 * the following directories: $CFG->cachedir, $CFG->dataroot, $CFG->dirroot, $CFG->localcachedir, $CFG->tempdir
5927 * @param string $attachname the name of the file (extension indicates MIME)
5928 * @param bool $usetrueaddress determines whether $from email address should
5929 * be sent out. Will be overruled by user profile setting for maildisplay
5930 * @param string $replyto Email address to reply to
5931 * @param string $replytoname Name of reply to recipient
5932 * @param int $wordwrapwidth custom word wrap width, default 79
5933 * @return bool Returns true if mail was sent OK and false if there was an error.
5935 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5936 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5938 global $CFG, $PAGE, $SITE;
5940 if (empty($user) or empty($user->id)) {
5941 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5942 return false;
5945 if (empty($user->email)) {
5946 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5947 return false;
5950 if (!empty($user->deleted)) {
5951 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5952 return false;
5955 if (defined('BEHAT_SITE_RUNNING')) {
5956 // Fake email sending in behat.
5957 return true;
5960 if (!empty($CFG->noemailever)) {
5961 // Hidden setting for development sites, set in config.php if needed.
5962 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5963 return true;
5966 if (email_should_be_diverted($user->email)) {
5967 $subject = "[DIVERTED {$user->email}] $subject";
5968 $user = clone($user);
5969 $user->email = $CFG->divertallemailsto;
5972 // Skip mail to suspended users.
5973 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5974 return true;
5977 if (!validate_email($user->email)) {
5978 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5979 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5980 return false;
5983 if (over_bounce_threshold($user)) {
5984 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5985 return false;
5988 // TLD .invalid is specifically reserved for invalid domain names.
5989 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5990 if (substr($user->email, -8) == '.invalid') {
5991 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5992 return true; // This is not an error.
5995 // If the user is a remote mnet user, parse the email text for URL to the
5996 // wwwroot and modify the url to direct the user's browser to login at their
5997 // home site (identity provider - idp) before hitting the link itself.
5998 if (is_mnet_remote_user($user)) {
5999 require_once($CFG->dirroot.'/mnet/lib.php');
6001 $jumpurl = mnet_get_idp_jump_url($user);
6002 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
6004 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
6005 $callback,
6006 $messagetext);
6007 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
6008 $callback,
6009 $messagehtml);
6011 $mail = get_mailer();
6013 if (!empty($mail->SMTPDebug)) {
6014 echo '<pre>' . "\n";
6017 $temprecipients = array();
6018 $tempreplyto = array();
6020 // Make sure that we fall back onto some reasonable no-reply address.
6021 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
6022 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
6024 if (!validate_email($noreplyaddress)) {
6025 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
6026 $noreplyaddress = $noreplyaddressdefault;
6029 // Make up an email address for handling bounces.
6030 if (!empty($CFG->handlebounces)) {
6031 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
6032 $mail->Sender = generate_email_processing_address(0, $modargs);
6033 } else {
6034 $mail->Sender = $noreplyaddress;
6037 // Make sure that the explicit replyto is valid, fall back to the implicit one.
6038 if (!empty($replyto) && !validate_email($replyto)) {
6039 debugging('email_to_user: Invalid replyto-email '.s($replyto));
6040 $replyto = $noreplyaddress;
6043 if (is_string($from)) { // So we can pass whatever we want if there is need.
6044 $mail->From = $noreplyaddress;
6045 $mail->FromName = $from;
6046 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
6047 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6048 // in a course with the sender.
6049 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
6050 if (!validate_email($from->email)) {
6051 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
6052 // Better not to use $noreplyaddress in this case.
6053 return false;
6055 $mail->From = $from->email;
6056 $fromdetails = new stdClass();
6057 $fromdetails->name = fullname($from);
6058 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6059 $fromdetails->siteshortname = format_string($SITE->shortname);
6060 $fromstring = $fromdetails->name;
6061 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
6062 $fromstring = get_string('emailvia', 'core', $fromdetails);
6064 $mail->FromName = $fromstring;
6065 if (empty($replyto)) {
6066 $tempreplyto[] = array($from->email, fullname($from));
6068 } else {
6069 $mail->From = $noreplyaddress;
6070 $fromdetails = new stdClass();
6071 $fromdetails->name = fullname($from);
6072 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6073 $fromdetails->siteshortname = format_string($SITE->shortname);
6074 $fromstring = $fromdetails->name;
6075 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
6076 $fromstring = get_string('emailvia', 'core', $fromdetails);
6078 $mail->FromName = $fromstring;
6079 if (empty($replyto)) {
6080 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
6084 if (!empty($replyto)) {
6085 $tempreplyto[] = array($replyto, $replytoname);
6088 $temprecipients[] = array($user->email, fullname($user));
6090 // Set word wrap.
6091 $mail->WordWrap = $wordwrapwidth;
6093 if (!empty($from->customheaders)) {
6094 // Add custom headers.
6095 if (is_array($from->customheaders)) {
6096 foreach ($from->customheaders as $customheader) {
6097 $mail->addCustomHeader($customheader);
6099 } else {
6100 $mail->addCustomHeader($from->customheaders);
6104 // If the X-PHP-Originating-Script email header is on then also add an additional
6105 // header with details of where exactly in moodle the email was triggered from,
6106 // either a call to message_send() or to email_to_user().
6107 if (ini_get('mail.add_x_header')) {
6109 $stack = debug_backtrace(false);
6110 $origin = $stack[0];
6112 foreach ($stack as $depth => $call) {
6113 if ($call['function'] == 'message_send') {
6114 $origin = $call;
6118 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
6119 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
6120 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
6123 if (!empty($CFG->emailheaders)) {
6124 $headers = array_map('trim', explode("\n", $CFG->emailheaders));
6125 foreach ($headers as $header) {
6126 if (!empty($header)) {
6127 $mail->addCustomHeader($header);
6132 if (!empty($from->priority)) {
6133 $mail->Priority = $from->priority;
6136 $renderer = $PAGE->get_renderer('core');
6137 $context = array(
6138 'sitefullname' => $SITE->fullname,
6139 'siteshortname' => $SITE->shortname,
6140 'sitewwwroot' => $CFG->wwwroot,
6141 'subject' => $subject,
6142 'prefix' => $CFG->emailsubjectprefix,
6143 'to' => $user->email,
6144 'toname' => fullname($user),
6145 'from' => $mail->From,
6146 'fromname' => $mail->FromName,
6148 if (!empty($tempreplyto[0])) {
6149 $context['replyto'] = $tempreplyto[0][0];
6150 $context['replytoname'] = $tempreplyto[0][1];
6152 if ($user->id > 0) {
6153 $context['touserid'] = $user->id;
6154 $context['tousername'] = $user->username;
6157 if (!empty($user->mailformat) && $user->mailformat == 1) {
6158 // Only process html templates if the user preferences allow html email.
6160 if (!$messagehtml) {
6161 // If no html has been given, BUT there is an html wrapping template then
6162 // auto convert the text to html and then wrap it.
6163 $messagehtml = trim(text_to_html($messagetext));
6165 $context['body'] = $messagehtml;
6166 $messagehtml = $renderer->render_from_template('core/email_html', $context);
6169 $context['body'] = html_to_text(nl2br($messagetext));
6170 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
6171 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
6172 $messagetext = $renderer->render_from_template('core/email_text', $context);
6174 // Autogenerate a MessageID if it's missing.
6175 if (empty($mail->MessageID)) {
6176 $mail->MessageID = generate_email_messageid();
6179 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6180 // Don't ever send HTML to users who don't want it.
6181 $mail->isHTML(true);
6182 $mail->Encoding = 'quoted-printable';
6183 $mail->Body = $messagehtml;
6184 $mail->AltBody = "\n$messagetext\n";
6185 } else {
6186 $mail->IsHTML(false);
6187 $mail->Body = "\n$messagetext\n";
6190 if ($attachment && $attachname) {
6191 if (preg_match( "~\\.\\.~" , $attachment )) {
6192 // Security check for ".." in dir path.
6193 $supportuser = core_user::get_support_user();
6194 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6195 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6196 } else {
6197 require_once($CFG->libdir.'/filelib.php');
6198 $mimetype = mimeinfo('type', $attachname);
6200 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6201 // The absolute (real) path is also fetched to ensure that comparisons to allowed paths are compared equally.
6202 $attachpath = str_replace('\\', '/', realpath($attachment));
6204 // Build an array of all filepaths from which attachments can be added (normalised slashes, absolute/real path).
6205 $allowedpaths = array_map(function(string $path): string {
6206 return str_replace('\\', '/', realpath($path));
6207 }, [
6208 $CFG->cachedir,
6209 $CFG->dataroot,
6210 $CFG->dirroot,
6211 $CFG->localcachedir,
6212 $CFG->tempdir,
6213 $CFG->localrequestdir,
6216 // Set addpath to true.
6217 $addpath = true;
6219 // Check if attachment includes one of the allowed paths.
6220 foreach (array_filter($allowedpaths) as $allowedpath) {
6221 // Set addpath to false if the attachment includes one of the allowed paths.
6222 if (strpos($attachpath, $allowedpath) === 0) {
6223 $addpath = false;
6224 break;
6228 // If the attachment is a full path to a file in the multiple allowed paths, use it as is,
6229 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6230 if ($addpath == true) {
6231 $attachment = $CFG->dataroot . '/' . $attachment;
6234 $mail->addAttachment($attachment, $attachname, 'base64', $mimetype);
6238 // Check if the email should be sent in an other charset then the default UTF-8.
6239 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6241 // Use the defined site mail charset or eventually the one preferred by the recipient.
6242 $charset = $CFG->sitemailcharset;
6243 if (!empty($CFG->allowusermailcharset)) {
6244 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6245 $charset = $useremailcharset;
6249 // Convert all the necessary strings if the charset is supported.
6250 $charsets = get_list_of_charsets();
6251 unset($charsets['UTF-8']);
6252 if (in_array($charset, $charsets)) {
6253 $mail->CharSet = $charset;
6254 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6255 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6256 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6257 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6259 foreach ($temprecipients as $key => $values) {
6260 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6262 foreach ($tempreplyto as $key => $values) {
6263 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6268 foreach ($temprecipients as $values) {
6269 $mail->addAddress($values[0], $values[1]);
6271 foreach ($tempreplyto as $values) {
6272 $mail->addReplyTo($values[0], $values[1]);
6275 if (!empty($CFG->emaildkimselector)) {
6276 $domain = substr(strrchr($mail->From, "@"), 1);
6277 $pempath = "{$CFG->dataroot}/dkim/{$domain}/{$CFG->emaildkimselector}.private";
6278 if (file_exists($pempath)) {
6279 $mail->DKIM_domain = $domain;
6280 $mail->DKIM_private = $pempath;
6281 $mail->DKIM_selector = $CFG->emaildkimselector;
6282 $mail->DKIM_identity = $mail->From;
6283 } else {
6284 debugging("Email DKIM selector chosen due to {$mail->From} but no certificate found at $pempath", DEBUG_DEVELOPER);
6288 if ($mail->send()) {
6289 set_send_count($user);
6290 if (!empty($mail->SMTPDebug)) {
6291 echo '</pre>';
6293 return true;
6294 } else {
6295 // Trigger event for failing to send email.
6296 $event = \core\event\email_failed::create(array(
6297 'context' => context_system::instance(),
6298 'userid' => $from->id,
6299 'relateduserid' => $user->id,
6300 'other' => array(
6301 'subject' => $subject,
6302 'message' => $messagetext,
6303 'errorinfo' => $mail->ErrorInfo
6306 $event->trigger();
6307 if (CLI_SCRIPT) {
6308 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6310 if (!empty($mail->SMTPDebug)) {
6311 echo '</pre>';
6313 return false;
6318 * Check to see if a user's real email address should be used for the "From" field.
6320 * @param object $from The user object for the user we are sending the email from.
6321 * @param object $user The user object that we are sending the email to.
6322 * @param array $unused No longer used.
6323 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6325 function can_send_from_real_email_address($from, $user, $unused = null) {
6326 global $CFG;
6327 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6328 return false;
6330 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6331 // Email is in the list of allowed domains for sending email,
6332 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6333 // in a course with the sender.
6334 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6335 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6336 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6337 && enrol_get_shared_courses($user, $from, false, true)))) {
6338 return true;
6340 return false;
6344 * Generate a signoff for emails based on support settings
6346 * @return string
6348 function generate_email_signoff() {
6349 global $CFG;
6351 $signoff = "\n";
6352 if (!empty($CFG->supportname)) {
6353 $signoff .= $CFG->supportname."\n";
6355 if (!empty($CFG->supportemail)) {
6356 $signoff .= $CFG->supportemail."\n";
6358 if (!empty($CFG->supportpage)) {
6359 $signoff .= $CFG->supportpage."\n";
6361 return $signoff;
6365 * Sets specified user's password and send the new password to the user via email.
6367 * @param stdClass $user A {@link $USER} object
6368 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6369 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6371 function setnew_password_and_mail($user, $fasthash = false) {
6372 global $CFG, $DB;
6374 // We try to send the mail in language the user understands,
6375 // unfortunately the filter_string() does not support alternative langs yet
6376 // so multilang will not work properly for site->fullname.
6377 $lang = empty($user->lang) ? get_newuser_language() : $user->lang;
6379 $site = get_site();
6381 $supportuser = core_user::get_support_user();
6383 $newpassword = generate_password();
6385 update_internal_user_password($user, $newpassword, $fasthash);
6387 $a = new stdClass();
6388 $a->firstname = fullname($user, true);
6389 $a->sitename = format_string($site->fullname);
6390 $a->username = $user->username;
6391 $a->newpassword = $newpassword;
6392 $a->link = $CFG->wwwroot .'/login/?lang='.$lang;
6393 $a->signoff = generate_email_signoff();
6395 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6397 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6399 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6400 return email_to_user($user, $supportuser, $subject, $message);
6405 * Resets specified user's password and send the new password to the user via email.
6407 * @param stdClass $user A {@link $USER} object
6408 * @return bool Returns true if mail was sent OK and false if there was an error.
6410 function reset_password_and_mail($user) {
6411 global $CFG;
6413 $site = get_site();
6414 $supportuser = core_user::get_support_user();
6416 $userauth = get_auth_plugin($user->auth);
6417 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6418 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6419 return false;
6422 $newpassword = generate_password();
6424 if (!$userauth->user_update_password($user, $newpassword)) {
6425 throw new \moodle_exception("cannotsetpassword");
6428 $a = new stdClass();
6429 $a->firstname = $user->firstname;
6430 $a->lastname = $user->lastname;
6431 $a->sitename = format_string($site->fullname);
6432 $a->username = $user->username;
6433 $a->newpassword = $newpassword;
6434 $a->link = $CFG->wwwroot .'/login/change_password.php';
6435 $a->signoff = generate_email_signoff();
6437 $message = get_string('newpasswordtext', '', $a);
6439 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6441 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6443 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6444 return email_to_user($user, $supportuser, $subject, $message);
6448 * Send email to specified user with confirmation text and activation link.
6450 * @param stdClass $user A {@link $USER} object
6451 * @param string $confirmationurl user confirmation URL
6452 * @return bool Returns true if mail was sent OK and false if there was an error.
6454 function send_confirmation_email($user, $confirmationurl = null) {
6455 global $CFG;
6457 $site = get_site();
6458 $supportuser = core_user::get_support_user();
6460 $data = new stdClass();
6461 $data->sitename = format_string($site->fullname);
6462 $data->admin = generate_email_signoff();
6464 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6466 if (empty($confirmationurl)) {
6467 $confirmationurl = '/login/confirm.php';
6470 $confirmationurl = new moodle_url($confirmationurl);
6471 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6472 $confirmationurl->remove_params('data');
6473 $confirmationpath = $confirmationurl->out(false);
6475 // We need to custom encode the username to include trailing dots in the link.
6476 // Because of this custom encoding we can't use moodle_url directly.
6477 // Determine if a query string is present in the confirmation url.
6478 $hasquerystring = strpos($confirmationpath, '?') !== false;
6479 // Perform normal url encoding of the username first.
6480 $username = urlencode($user->username);
6481 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6482 $username = str_replace('.', '%2E', $username);
6484 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6486 $message = get_string('emailconfirmation', '', $data);
6487 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6489 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6490 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6494 * Sends a password change confirmation email.
6496 * @param stdClass $user A {@link $USER} object
6497 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6498 * @return bool Returns true if mail was sent OK and false if there was an error.
6500 function send_password_change_confirmation_email($user, $resetrecord) {
6501 global $CFG;
6503 $site = get_site();
6504 $supportuser = core_user::get_support_user();
6505 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6507 $data = new stdClass();
6508 $data->firstname = $user->firstname;
6509 $data->lastname = $user->lastname;
6510 $data->username = $user->username;
6511 $data->sitename = format_string($site->fullname);
6512 $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6513 $data->admin = generate_email_signoff();
6514 $data->resetminutes = $pwresetmins;
6516 $message = get_string('emailresetconfirmation', '', $data);
6517 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6519 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6520 return email_to_user($user, $supportuser, $subject, $message);
6525 * Sends an email containing information on how to change your password.
6527 * @param stdClass $user A {@link $USER} object
6528 * @return bool Returns true if mail was sent OK and false if there was an error.
6530 function send_password_change_info($user) {
6531 $site = get_site();
6532 $supportuser = core_user::get_support_user();
6534 $data = new stdClass();
6535 $data->firstname = $user->firstname;
6536 $data->lastname = $user->lastname;
6537 $data->username = $user->username;
6538 $data->sitename = format_string($site->fullname);
6539 $data->admin = generate_email_signoff();
6541 if (!is_enabled_auth($user->auth)) {
6542 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6543 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6544 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6545 return email_to_user($user, $supportuser, $subject, $message);
6548 $userauth = get_auth_plugin($user->auth);
6549 ['subject' => $subject, 'message' => $message] = $userauth->get_password_change_info($user);
6551 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6552 return email_to_user($user, $supportuser, $subject, $message);
6556 * Check that an email is allowed. It returns an error message if there was a problem.
6558 * @param string $email Content of email
6559 * @return string|false
6561 function email_is_not_allowed($email) {
6562 global $CFG;
6564 // Comparing lowercase domains.
6565 $email = strtolower($email);
6566 if (!empty($CFG->allowemailaddresses)) {
6567 $allowed = explode(' ', strtolower($CFG->allowemailaddresses));
6568 foreach ($allowed as $allowedpattern) {
6569 $allowedpattern = trim($allowedpattern);
6570 if (!$allowedpattern) {
6571 continue;
6573 if (strpos($allowedpattern, '.') === 0) {
6574 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6575 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6576 return false;
6579 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6580 return false;
6583 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6585 } else if (!empty($CFG->denyemailaddresses)) {
6586 $denied = explode(' ', strtolower($CFG->denyemailaddresses));
6587 foreach ($denied as $deniedpattern) {
6588 $deniedpattern = trim($deniedpattern);
6589 if (!$deniedpattern) {
6590 continue;
6592 if (strpos($deniedpattern, '.') === 0) {
6593 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6594 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6595 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6598 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6599 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6604 return false;
6607 // FILE HANDLING.
6610 * Returns local file storage instance
6612 * @return file_storage
6614 function get_file_storage($reset = false) {
6615 global $CFG;
6617 static $fs = null;
6619 if ($reset) {
6620 $fs = null;
6621 return;
6624 if ($fs) {
6625 return $fs;
6628 require_once("$CFG->libdir/filelib.php");
6630 $fs = new file_storage();
6632 return $fs;
6636 * Returns local file storage instance
6638 * @return file_browser
6640 function get_file_browser() {
6641 global $CFG;
6643 static $fb = null;
6645 if ($fb) {
6646 return $fb;
6649 require_once("$CFG->libdir/filelib.php");
6651 $fb = new file_browser();
6653 return $fb;
6657 * Returns file packer
6659 * @param string $mimetype default application/zip
6660 * @return file_packer
6662 function get_file_packer($mimetype='application/zip') {
6663 global $CFG;
6665 static $fp = array();
6667 if (isset($fp[$mimetype])) {
6668 return $fp[$mimetype];
6671 switch ($mimetype) {
6672 case 'application/zip':
6673 case 'application/vnd.moodle.profiling':
6674 $classname = 'zip_packer';
6675 break;
6677 case 'application/x-gzip' :
6678 $classname = 'tgz_packer';
6679 break;
6681 case 'application/vnd.moodle.backup':
6682 $classname = 'mbz_packer';
6683 break;
6685 default:
6686 return false;
6689 require_once("$CFG->libdir/filestorage/$classname.php");
6690 $fp[$mimetype] = new $classname();
6692 return $fp[$mimetype];
6696 * Returns current name of file on disk if it exists.
6698 * @param string $newfile File to be verified
6699 * @return string Current name of file on disk if true
6701 function valid_uploaded_file($newfile) {
6702 if (empty($newfile)) {
6703 return '';
6705 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6706 return $newfile['tmp_name'];
6707 } else {
6708 return '';
6713 * Returns the maximum size for uploading files.
6715 * There are seven possible upload limits:
6716 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6717 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6718 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6719 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6720 * 5. by the Moodle admin in $CFG->maxbytes
6721 * 6. by the teacher in the current course $course->maxbytes
6722 * 7. by the teacher for the current module, eg $assignment->maxbytes
6724 * These last two are passed to this function as arguments (in bytes).
6725 * Anything defined as 0 is ignored.
6726 * The smallest of all the non-zero numbers is returned.
6728 * @todo Finish documenting this function
6730 * @param int $sitebytes Set maximum size
6731 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6732 * @param int $modulebytes Current module ->maxbytes (in bytes)
6733 * @param bool $unused This parameter has been deprecated and is not used any more.
6734 * @return int The maximum size for uploading files.
6736 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6738 if (! $filesize = ini_get('upload_max_filesize')) {
6739 $filesize = '5M';
6741 $minimumsize = get_real_size($filesize);
6743 if ($postsize = ini_get('post_max_size')) {
6744 $postsize = get_real_size($postsize);
6745 if ($postsize < $minimumsize) {
6746 $minimumsize = $postsize;
6750 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6751 $minimumsize = $sitebytes;
6754 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6755 $minimumsize = $coursebytes;
6758 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6759 $minimumsize = $modulebytes;
6762 return $minimumsize;
6766 * Returns the maximum size for uploading files for the current user
6768 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6770 * @param context $context The context in which to check user capabilities
6771 * @param int $sitebytes Set maximum size
6772 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6773 * @param int $modulebytes Current module ->maxbytes (in bytes)
6774 * @param stdClass $user The user
6775 * @param bool $unused This parameter has been deprecated and is not used any more.
6776 * @return int The maximum size for uploading files.
6778 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6779 $unused = false) {
6780 global $USER;
6782 if (empty($user)) {
6783 $user = $USER;
6786 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6787 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6790 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6794 * Returns an array of possible sizes in local language
6796 * Related to {@link get_max_upload_file_size()} - this function returns an
6797 * array of possible sizes in an array, translated to the
6798 * local language.
6800 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6802 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6803 * with the value set to 0. This option will be the first in the list.
6805 * @uses SORT_NUMERIC
6806 * @param int $sitebytes Set maximum size
6807 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6808 * @param int $modulebytes Current module ->maxbytes (in bytes)
6809 * @param int|array $custombytes custom upload size/s which will be added to list,
6810 * Only value/s smaller then maxsize will be added to list.
6811 * @return array
6813 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6814 global $CFG;
6816 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6817 return array();
6820 if ($sitebytes == 0) {
6821 // Will get the minimum of upload_max_filesize or post_max_size.
6822 $sitebytes = get_max_upload_file_size();
6825 $filesize = array();
6826 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6827 5242880, 10485760, 20971520, 52428800, 104857600,
6828 262144000, 524288000, 786432000, 1073741824,
6829 2147483648, 4294967296, 8589934592);
6831 // If custombytes is given and is valid then add it to the list.
6832 if (is_number($custombytes) and $custombytes > 0) {
6833 $custombytes = (int)$custombytes;
6834 if (!in_array($custombytes, $sizelist)) {
6835 $sizelist[] = $custombytes;
6837 } else if (is_array($custombytes)) {
6838 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6841 // Allow maxbytes to be selected if it falls outside the above boundaries.
6842 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6843 // Note: get_real_size() is used in order to prevent problems with invalid values.
6844 $sizelist[] = get_real_size($CFG->maxbytes);
6847 foreach ($sizelist as $sizebytes) {
6848 if ($sizebytes < $maxsize && $sizebytes > 0) {
6849 $filesize[(string)intval($sizebytes)] = display_size($sizebytes, 0);
6853 $limitlevel = '';
6854 $displaysize = '';
6855 if ($modulebytes &&
6856 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6857 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6858 $limitlevel = get_string('activity', 'core');
6859 $displaysize = display_size($modulebytes, 0);
6860 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6862 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6863 $limitlevel = get_string('course', 'core');
6864 $displaysize = display_size($coursebytes, 0);
6865 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6867 } else if ($sitebytes) {
6868 $limitlevel = get_string('site', 'core');
6869 $displaysize = display_size($sitebytes, 0);
6870 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6873 krsort($filesize, SORT_NUMERIC);
6874 if ($limitlevel) {
6875 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6876 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6879 return $filesize;
6883 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6885 * If excludefiles is defined, then that file/directory is ignored
6886 * If getdirs is true, then (sub)directories are included in the output
6887 * If getfiles is true, then files are included in the output
6888 * (at least one of these must be true!)
6890 * @todo Finish documenting this function. Add examples of $excludefile usage.
6892 * @param string $rootdir A given root directory to start from
6893 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6894 * @param bool $descend If true then subdirectories are recursed as well
6895 * @param bool $getdirs If true then (sub)directories are included in the output
6896 * @param bool $getfiles If true then files are included in the output
6897 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6899 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6901 $dirs = array();
6903 if (!$getdirs and !$getfiles) { // Nothing to show.
6904 return $dirs;
6907 if (!is_dir($rootdir)) { // Must be a directory.
6908 return $dirs;
6911 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6912 return $dirs;
6915 if (!is_array($excludefiles)) {
6916 $excludefiles = array($excludefiles);
6919 while (false !== ($file = readdir($dir))) {
6920 $firstchar = substr($file, 0, 1);
6921 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6922 continue;
6924 $fullfile = $rootdir .'/'. $file;
6925 if (filetype($fullfile) == 'dir') {
6926 if ($getdirs) {
6927 $dirs[] = $file;
6929 if ($descend) {
6930 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6931 foreach ($subdirs as $subdir) {
6932 $dirs[] = $file .'/'. $subdir;
6935 } else if ($getfiles) {
6936 $dirs[] = $file;
6939 closedir($dir);
6941 asort($dirs);
6943 return $dirs;
6948 * Adds up all the files in a directory and works out the size.
6950 * @param string $rootdir The directory to start from
6951 * @param string $excludefile A file to exclude when summing directory size
6952 * @return int The summed size of all files and subfiles within the root directory
6954 function get_directory_size($rootdir, $excludefile='') {
6955 global $CFG;
6957 // Do it this way if we can, it's much faster.
6958 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6959 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6960 $output = null;
6961 $return = null;
6962 exec($command, $output, $return);
6963 if (is_array($output)) {
6964 // We told it to return k.
6965 return get_real_size(intval($output[0]).'k');
6969 if (!is_dir($rootdir)) {
6970 // Must be a directory.
6971 return 0;
6974 if (!$dir = @opendir($rootdir)) {
6975 // Can't open it for some reason.
6976 return 0;
6979 $size = 0;
6981 while (false !== ($file = readdir($dir))) {
6982 $firstchar = substr($file, 0, 1);
6983 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6984 continue;
6986 $fullfile = $rootdir .'/'. $file;
6987 if (filetype($fullfile) == 'dir') {
6988 $size += get_directory_size($fullfile, $excludefile);
6989 } else {
6990 $size += filesize($fullfile);
6993 closedir($dir);
6995 return $size;
6999 * Converts bytes into display form
7001 * @param int $size The size to convert to human readable form
7002 * @param int $decimalplaces If specified, uses fixed number of decimal places
7003 * @param string $fixedunits If specified, uses fixed units (e.g. 'KB')
7004 * @return string Display version of size
7006 function display_size($size, int $decimalplaces = 1, string $fixedunits = ''): string {
7008 static $units;
7010 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
7011 return get_string('unlimited');
7014 if (empty($units)) {
7015 $units[] = get_string('sizeb');
7016 $units[] = get_string('sizekb');
7017 $units[] = get_string('sizemb');
7018 $units[] = get_string('sizegb');
7019 $units[] = get_string('sizetb');
7020 $units[] = get_string('sizepb');
7023 switch ($fixedunits) {
7024 case 'PB' :
7025 $magnitude = 5;
7026 break;
7027 case 'TB' :
7028 $magnitude = 4;
7029 break;
7030 case 'GB' :
7031 $magnitude = 3;
7032 break;
7033 case 'MB' :
7034 $magnitude = 2;
7035 break;
7036 case 'KB' :
7037 $magnitude = 1;
7038 break;
7039 case 'B' :
7040 $magnitude = 0;
7041 break;
7042 case '':
7043 $magnitude = floor(log($size, 1024));
7044 $magnitude = max(0, min(5, $magnitude));
7045 break;
7046 default:
7047 throw new coding_exception('Unknown fixed units value: ' . $fixedunits);
7050 // Special case for magnitude 0 (bytes) - never use decimal places.
7051 $nbsp = "\xc2\xa0";
7052 if ($magnitude === 0) {
7053 return round($size) . $nbsp . $units[$magnitude];
7056 // Convert to specified units.
7057 $sizeinunit = $size / 1024 ** $magnitude;
7059 // Fixed decimal places.
7060 return sprintf('%.' . $decimalplaces . 'f', $sizeinunit) . $nbsp . $units[$magnitude];
7064 * Cleans a given filename by removing suspicious or troublesome characters
7066 * @see clean_param()
7067 * @param string $string file name
7068 * @return string cleaned file name
7070 function clean_filename($string) {
7071 return clean_param($string, PARAM_FILE);
7074 // STRING TRANSLATION.
7077 * Returns the code for the current language
7079 * @category string
7080 * @return string
7082 function current_language() {
7083 global $CFG, $PAGE, $SESSION, $USER;
7085 if (!empty($SESSION->forcelang)) {
7086 // Allows overriding course-forced language (useful for admins to check
7087 // issues in courses whose language they don't understand).
7088 // Also used by some code to temporarily get language-related information in a
7089 // specific language (see force_current_language()).
7090 $return = $SESSION->forcelang;
7092 } else if (!empty($PAGE->cm->lang)) {
7093 // Activity language, if set.
7094 $return = $PAGE->cm->lang;
7096 } else if (!empty($PAGE->course->id) && $PAGE->course->id != SITEID && !empty($PAGE->course->lang)) {
7097 // Course language can override all other settings for this page.
7098 $return = $PAGE->course->lang;
7100 } else if (!empty($SESSION->lang)) {
7101 // Session language can override other settings.
7102 $return = $SESSION->lang;
7104 } else if (!empty($USER->lang)) {
7105 $return = $USER->lang;
7107 } else if (isset($CFG->lang)) {
7108 $return = $CFG->lang;
7110 } else {
7111 $return = 'en';
7114 // Just in case this slipped in from somewhere by accident.
7115 $return = str_replace('_utf8', '', $return);
7117 return $return;
7121 * Returns parent language of current active language if defined
7123 * @category string
7124 * @param string $lang null means current language
7125 * @return string
7127 function get_parent_language($lang=null) {
7129 $parentlang = get_string_manager()->get_string('parentlanguage', 'langconfig', null, $lang);
7131 if ($parentlang === 'en') {
7132 $parentlang = '';
7135 return $parentlang;
7139 * Force the current language to get strings and dates localised in the given language.
7141 * After calling this function, all strings will be provided in the given language
7142 * until this function is called again, or equivalent code is run.
7144 * @param string $language
7145 * @return string previous $SESSION->forcelang value
7147 function force_current_language($language) {
7148 global $SESSION;
7149 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
7150 if ($language !== $sessionforcelang) {
7151 // Setting forcelang to null or an empty string disables its effect.
7152 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
7153 $SESSION->forcelang = $language;
7154 moodle_setlocale();
7157 return $sessionforcelang;
7161 * Returns current string_manager instance.
7163 * The param $forcereload is needed for CLI installer only where the string_manager instance
7164 * must be replaced during the install.php script life time.
7166 * @category string
7167 * @param bool $forcereload shall the singleton be released and new instance created instead?
7168 * @return core_string_manager
7170 function get_string_manager($forcereload=false) {
7171 global $CFG;
7173 static $singleton = null;
7175 if ($forcereload) {
7176 $singleton = null;
7178 if ($singleton === null) {
7179 if (empty($CFG->early_install_lang)) {
7181 $transaliases = array();
7182 if (empty($CFG->langlist)) {
7183 $translist = array();
7184 } else {
7185 $translist = explode(',', $CFG->langlist);
7186 $translist = array_map('trim', $translist);
7187 // Each language in the $CFG->langlist can has an "alias" that would substitute the default language name.
7188 foreach ($translist as $i => $value) {
7189 $parts = preg_split('/\s*\|\s*/', $value, 2);
7190 if (count($parts) == 2) {
7191 $transaliases[$parts[0]] = $parts[1];
7192 $translist[$i] = $parts[0];
7197 if (!empty($CFG->config_php_settings['customstringmanager'])) {
7198 $classname = $CFG->config_php_settings['customstringmanager'];
7200 if (class_exists($classname)) {
7201 $implements = class_implements($classname);
7203 if (isset($implements['core_string_manager'])) {
7204 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7205 return $singleton;
7207 } else {
7208 debugging('Unable to instantiate custom string manager: class '.$classname.
7209 ' does not implement the core_string_manager interface.');
7212 } else {
7213 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7217 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7219 } else {
7220 $singleton = new core_string_manager_install();
7224 return $singleton;
7228 * Returns a localized string.
7230 * Returns the translated string specified by $identifier as
7231 * for $module. Uses the same format files as STphp.
7232 * $a is an object, string or number that can be used
7233 * within translation strings
7235 * eg 'hello {$a->firstname} {$a->lastname}'
7236 * or 'hello {$a}'
7238 * If you would like to directly echo the localized string use
7239 * the function {@link print_string()}
7241 * Example usage of this function involves finding the string you would
7242 * like a local equivalent of and using its identifier and module information
7243 * to retrieve it.<br/>
7244 * If you open moodle/lang/en/moodle.php and look near line 278
7245 * you will find a string to prompt a user for their word for 'course'
7246 * <code>
7247 * $string['course'] = 'Course';
7248 * </code>
7249 * So if you want to display the string 'Course'
7250 * in any language that supports it on your site
7251 * you just need to use the identifier 'course'
7252 * <code>
7253 * $mystring = '<strong>'. get_string('course') .'</strong>';
7254 * or
7255 * </code>
7256 * If the string you want is in another file you'd take a slightly
7257 * different approach. Looking in moodle/lang/en/calendar.php you find
7258 * around line 75:
7259 * <code>
7260 * $string['typecourse'] = 'Course event';
7261 * </code>
7262 * If you want to display the string "Course event" in any language
7263 * supported you would use the identifier 'typecourse' and the module 'calendar'
7264 * (because it is in the file calendar.php):
7265 * <code>
7266 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7267 * </code>
7269 * As a last resort, should the identifier fail to map to a string
7270 * the returned string will be [[ $identifier ]]
7272 * In Moodle 2.3 there is a new argument to this function $lazyload.
7273 * Setting $lazyload to true causes get_string to return a lang_string object
7274 * rather than the string itself. The fetching of the string is then put off until
7275 * the string object is first used. The object can be used by calling it's out
7276 * method or by casting the object to a string, either directly e.g.
7277 * (string)$stringobject
7278 * or indirectly by using the string within another string or echoing it out e.g.
7279 * echo $stringobject
7280 * return "<p>{$stringobject}</p>";
7281 * It is worth noting that using $lazyload and attempting to use the string as an
7282 * array key will cause a fatal error as objects cannot be used as array keys.
7283 * But you should never do that anyway!
7284 * For more information {@link lang_string}
7286 * @category string
7287 * @param string $identifier The key identifier for the localized string
7288 * @param string $component The module where the key identifier is stored,
7289 * usually expressed as the filename in the language pack without the
7290 * .php on the end but can also be written as mod/forum or grade/export/xls.
7291 * If none is specified then moodle.php is used.
7292 * @param string|object|array $a An object, string or number that can be used
7293 * within translation strings
7294 * @param bool $lazyload If set to true a string object is returned instead of
7295 * the string itself. The string then isn't calculated until it is first used.
7296 * @return string The localized string.
7297 * @throws coding_exception
7299 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7300 global $CFG;
7302 // If the lazy load argument has been supplied return a lang_string object
7303 // instead.
7304 // We need to make sure it is true (and a bool) as you will see below there
7305 // used to be a forth argument at one point.
7306 if ($lazyload === true) {
7307 return new lang_string($identifier, $component, $a);
7310 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7311 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7314 // There is now a forth argument again, this time it is a boolean however so
7315 // we can still check for the old extralocations parameter.
7316 if (!is_bool($lazyload) && !empty($lazyload)) {
7317 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7320 if (strpos($component, '/') !== false) {
7321 debugging('The module name you passed to get_string is the deprecated format ' .
7322 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7323 $componentpath = explode('/', $component);
7325 switch ($componentpath[0]) {
7326 case 'mod':
7327 $component = $componentpath[1];
7328 break;
7329 case 'blocks':
7330 case 'block':
7331 $component = 'block_'.$componentpath[1];
7332 break;
7333 case 'enrol':
7334 $component = 'enrol_'.$componentpath[1];
7335 break;
7336 case 'format':
7337 $component = 'format_'.$componentpath[1];
7338 break;
7339 case 'grade':
7340 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7341 break;
7345 $result = get_string_manager()->get_string($identifier, $component, $a);
7347 // Debugging feature lets you display string identifier and component.
7348 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7349 $result .= ' {' . $identifier . '/' . $component . '}';
7351 return $result;
7355 * Converts an array of strings to their localized value.
7357 * @param array $array An array of strings
7358 * @param string $component The language module that these strings can be found in.
7359 * @return stdClass translated strings.
7361 function get_strings($array, $component = '') {
7362 $string = new stdClass;
7363 foreach ($array as $item) {
7364 $string->$item = get_string($item, $component);
7366 return $string;
7370 * Prints out a translated string.
7372 * Prints out a translated string using the return value from the {@link get_string()} function.
7374 * Example usage of this function when the string is in the moodle.php file:<br/>
7375 * <code>
7376 * echo '<strong>';
7377 * print_string('course');
7378 * echo '</strong>';
7379 * </code>
7381 * Example usage of this function when the string is not in the moodle.php file:<br/>
7382 * <code>
7383 * echo '<h1>';
7384 * print_string('typecourse', 'calendar');
7385 * echo '</h1>';
7386 * </code>
7388 * @category string
7389 * @param string $identifier The key identifier for the localized string
7390 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7391 * @param string|object|array $a An object, string or number that can be used within translation strings
7393 function print_string($identifier, $component = '', $a = null) {
7394 echo get_string($identifier, $component, $a);
7398 * Returns a list of charset codes
7400 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7401 * (checking that such charset is supported by the texlib library!)
7403 * @return array And associative array with contents in the form of charset => charset
7405 function get_list_of_charsets() {
7407 $charsets = array(
7408 'EUC-JP' => 'EUC-JP',
7409 'ISO-2022-JP'=> 'ISO-2022-JP',
7410 'ISO-8859-1' => 'ISO-8859-1',
7411 'SHIFT-JIS' => 'SHIFT-JIS',
7412 'GB2312' => 'GB2312',
7413 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7414 'UTF-8' => 'UTF-8');
7416 asort($charsets);
7418 return $charsets;
7422 * Returns a list of valid and compatible themes
7424 * @return array
7426 function get_list_of_themes() {
7427 global $CFG;
7429 $themes = array();
7431 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7432 $themelist = explode(',', $CFG->themelist);
7433 } else {
7434 $themelist = array_keys(core_component::get_plugin_list("theme"));
7437 foreach ($themelist as $key => $themename) {
7438 $theme = theme_config::load($themename);
7439 $themes[$themename] = $theme;
7442 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7444 return $themes;
7448 * Factory function for emoticon_manager
7450 * @return emoticon_manager singleton
7452 function get_emoticon_manager() {
7453 static $singleton = null;
7455 if (is_null($singleton)) {
7456 $singleton = new emoticon_manager();
7459 return $singleton;
7463 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7465 * Whenever this manager mentiones 'emoticon object', the following data
7466 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7467 * altidentifier and altcomponent
7469 * @see admin_setting_emoticons
7471 * @copyright 2010 David Mudrak
7472 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7474 class emoticon_manager {
7477 * Returns the currently enabled emoticons
7479 * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
7480 * @return array of emoticon objects
7482 public function get_emoticons($selectable = false) {
7483 global $CFG;
7484 $notselectable = ['martin', 'egg'];
7486 if (empty($CFG->emoticons)) {
7487 return array();
7490 $emoticons = $this->decode_stored_config($CFG->emoticons);
7492 if (!is_array($emoticons)) {
7493 // Something is wrong with the format of stored setting.
7494 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7495 return array();
7497 if ($selectable) {
7498 foreach ($emoticons as $index => $emote) {
7499 if (in_array($emote->altidentifier, $notselectable)) {
7500 // Skip this one.
7501 unset($emoticons[$index]);
7506 return $emoticons;
7510 * Converts emoticon object into renderable pix_emoticon object
7512 * @param stdClass $emoticon emoticon object
7513 * @param array $attributes explicit HTML attributes to set
7514 * @return pix_emoticon
7516 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7517 $stringmanager = get_string_manager();
7518 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7519 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7520 } else {
7521 $alt = s($emoticon->text);
7523 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7527 * Encodes the array of emoticon objects into a string storable in config table
7529 * @see self::decode_stored_config()
7530 * @param array $emoticons array of emtocion objects
7531 * @return string
7533 public function encode_stored_config(array $emoticons) {
7534 return json_encode($emoticons);
7538 * Decodes the string into an array of emoticon objects
7540 * @see self::encode_stored_config()
7541 * @param string $encoded
7542 * @return string|null
7544 public function decode_stored_config($encoded) {
7545 $decoded = json_decode($encoded);
7546 if (!is_array($decoded)) {
7547 return null;
7549 return $decoded;
7553 * Returns default set of emoticons supported by Moodle
7555 * @return array of sdtClasses
7557 public function default_emoticons() {
7558 return array(
7559 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7560 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7561 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7562 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7563 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7564 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7565 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7566 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7567 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7568 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7569 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7570 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7571 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7572 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7573 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7574 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7575 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7576 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7577 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7578 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7579 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7580 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7581 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7582 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7583 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7584 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7585 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7586 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7587 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7588 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7593 * Helper method preparing the stdClass with the emoticon properties
7595 * @param string|array $text or array of strings
7596 * @param string $imagename to be used by {@link pix_emoticon}
7597 * @param string $altidentifier alternative string identifier, null for no alt
7598 * @param string $altcomponent where the alternative string is defined
7599 * @param string $imagecomponent to be used by {@link pix_emoticon}
7600 * @return stdClass
7602 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7603 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7604 return (object)array(
7605 'text' => $text,
7606 'imagename' => $imagename,
7607 'imagecomponent' => $imagecomponent,
7608 'altidentifier' => $altidentifier,
7609 'altcomponent' => $altcomponent,
7614 // ENCRYPTION.
7617 * rc4encrypt
7619 * @param string $data Data to encrypt.
7620 * @return string The now encrypted data.
7622 function rc4encrypt($data) {
7623 return endecrypt(get_site_identifier(), $data, '');
7627 * rc4decrypt
7629 * @param string $data Data to decrypt.
7630 * @return string The now decrypted data.
7632 function rc4decrypt($data) {
7633 return endecrypt(get_site_identifier(), $data, 'de');
7637 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7639 * @todo Finish documenting this function
7641 * @param string $pwd The password to use when encrypting or decrypting
7642 * @param string $data The data to be decrypted/encrypted
7643 * @param string $case Either 'de' for decrypt or '' for encrypt
7644 * @return string
7646 function endecrypt ($pwd, $data, $case) {
7648 if ($case == 'de') {
7649 $data = urldecode($data);
7652 $key[] = '';
7653 $box[] = '';
7654 $pwdlength = strlen($pwd);
7656 for ($i = 0; $i <= 255; $i++) {
7657 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7658 $box[$i] = $i;
7661 $x = 0;
7663 for ($i = 0; $i <= 255; $i++) {
7664 $x = ($x + $box[$i] + $key[$i]) % 256;
7665 $tempswap = $box[$i];
7666 $box[$i] = $box[$x];
7667 $box[$x] = $tempswap;
7670 $cipher = '';
7672 $a = 0;
7673 $j = 0;
7675 for ($i = 0; $i < strlen($data); $i++) {
7676 $a = ($a + 1) % 256;
7677 $j = ($j + $box[$a]) % 256;
7678 $temp = $box[$a];
7679 $box[$a] = $box[$j];
7680 $box[$j] = $temp;
7681 $k = $box[(($box[$a] + $box[$j]) % 256)];
7682 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7683 $cipher .= chr($cipherby);
7686 if ($case == 'de') {
7687 $cipher = urldecode(urlencode($cipher));
7688 } else {
7689 $cipher = urlencode($cipher);
7692 return $cipher;
7695 // ENVIRONMENT CHECKING.
7698 * This method validates a plug name. It is much faster than calling clean_param.
7700 * @param string $name a string that might be a plugin name.
7701 * @return bool if this string is a valid plugin name.
7703 function is_valid_plugin_name($name) {
7704 // This does not work for 'mod', bad luck, use any other type.
7705 return core_component::is_valid_plugin_name('tool', $name);
7709 * Get a list of all the plugins of a given type that define a certain API function
7710 * in a certain file. The plugin component names and function names are returned.
7712 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7713 * @param string $function the part of the name of the function after the
7714 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7715 * names like report_courselist_hook.
7716 * @param string $file the name of file within the plugin that defines the
7717 * function. Defaults to lib.php.
7718 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7719 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7721 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7722 global $CFG;
7724 // We don't include here as all plugin types files would be included.
7725 $plugins = get_plugins_with_function($function, $file, false);
7727 if (empty($plugins[$plugintype])) {
7728 return array();
7731 $allplugins = core_component::get_plugin_list($plugintype);
7733 // Reformat the array and include the files.
7734 $pluginfunctions = array();
7735 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7737 // Check that it has not been removed and the file is still available.
7738 if (!empty($allplugins[$pluginname])) {
7740 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7741 if (file_exists($filepath)) {
7742 include_once($filepath);
7744 // Now that the file is loaded, we must verify the function still exists.
7745 if (function_exists($functionname)) {
7746 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7747 } else {
7748 // Invalidate the cache for next run.
7749 \cache_helper::invalidate_by_definition('core', 'plugin_functions');
7755 return $pluginfunctions;
7759 * Get a list of all the plugins that define a certain API function in a certain file.
7761 * @param string $function the part of the name of the function after the
7762 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7763 * names like report_courselist_hook.
7764 * @param string $file the name of file within the plugin that defines the
7765 * function. Defaults to lib.php.
7766 * @param bool $include Whether to include the files that contain the functions or not.
7767 * @return array with [plugintype][plugin] = functionname
7769 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7770 global $CFG;
7772 if (during_initial_install() || isset($CFG->upgraderunning)) {
7773 // API functions _must not_ be called during an installation or upgrade.
7774 return [];
7777 $cache = \cache::make('core', 'plugin_functions');
7779 // Including both although I doubt that we will find two functions definitions with the same name.
7780 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7781 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7782 $pluginfunctions = $cache->get($key);
7783 $dirty = false;
7785 // Use the plugin manager to check that plugins are currently installed.
7786 $pluginmanager = \core_plugin_manager::instance();
7788 if ($pluginfunctions !== false) {
7790 // Checking that the files are still available.
7791 foreach ($pluginfunctions as $plugintype => $plugins) {
7793 $allplugins = \core_component::get_plugin_list($plugintype);
7794 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7795 foreach ($plugins as $plugin => $function) {
7796 if (!isset($installedplugins[$plugin])) {
7797 // Plugin code is still present on disk but it is not installed.
7798 $dirty = true;
7799 break 2;
7802 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7803 if (empty($allplugins[$plugin])) {
7804 $dirty = true;
7805 break 2;
7808 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7809 if ($include && $fileexists) {
7810 // Include the files if it was requested.
7811 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7812 } else if (!$fileexists) {
7813 // If the file is not available any more it should not be returned.
7814 $dirty = true;
7815 break 2;
7818 // Check if the function still exists in the file.
7819 if ($include && !function_exists($function)) {
7820 $dirty = true;
7821 break 2;
7826 // If the cache is dirty, we should fall through and let it rebuild.
7827 if (!$dirty) {
7828 return $pluginfunctions;
7832 $pluginfunctions = array();
7834 // To fill the cached. Also, everything should continue working with cache disabled.
7835 $plugintypes = \core_component::get_plugin_types();
7836 foreach ($plugintypes as $plugintype => $unused) {
7838 // We need to include files here.
7839 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7840 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7841 foreach ($pluginswithfile as $plugin => $notused) {
7843 if (!isset($installedplugins[$plugin])) {
7844 continue;
7847 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7849 $pluginfunction = false;
7850 if (function_exists($fullfunction)) {
7851 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7852 $pluginfunction = $fullfunction;
7854 } else if ($plugintype === 'mod') {
7855 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7856 $shortfunction = $plugin . '_' . $function;
7857 if (function_exists($shortfunction)) {
7858 $pluginfunction = $shortfunction;
7862 if ($pluginfunction) {
7863 if (empty($pluginfunctions[$plugintype])) {
7864 $pluginfunctions[$plugintype] = array();
7866 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7871 $cache->set($key, $pluginfunctions);
7873 return $pluginfunctions;
7878 * Lists plugin-like directories within specified directory
7880 * This function was originally used for standard Moodle plugins, please use
7881 * new core_component::get_plugin_list() now.
7883 * This function is used for general directory listing and backwards compatility.
7885 * @param string $directory relative directory from root
7886 * @param string $exclude dir name to exclude from the list (defaults to none)
7887 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7888 * @return array Sorted array of directory names found under the requested parameters
7890 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7891 global $CFG;
7893 $plugins = array();
7895 if (empty($basedir)) {
7896 $basedir = $CFG->dirroot .'/'. $directory;
7898 } else {
7899 $basedir = $basedir .'/'. $directory;
7902 if ($CFG->debugdeveloper and empty($exclude)) {
7903 // Make sure devs do not use this to list normal plugins,
7904 // this is intended for general directories that are not plugins!
7906 $subtypes = core_component::get_plugin_types();
7907 if (in_array($basedir, $subtypes)) {
7908 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7910 unset($subtypes);
7913 $ignorelist = array_flip(array_filter([
7914 'CVS',
7915 '_vti_cnf',
7916 'amd',
7917 'classes',
7918 'simpletest',
7919 'tests',
7920 'templates',
7921 'yui',
7922 $exclude,
7923 ]));
7925 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7926 if (!$dirhandle = opendir($basedir)) {
7927 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7928 return array();
7930 while (false !== ($dir = readdir($dirhandle))) {
7931 if (strpos($dir, '.') === 0) {
7932 // Ignore directories starting with .
7933 // These are treated as hidden directories.
7934 continue;
7936 if (array_key_exists($dir, $ignorelist)) {
7937 // This directory features on the ignore list.
7938 continue;
7940 if (filetype($basedir .'/'. $dir) != 'dir') {
7941 continue;
7943 $plugins[] = $dir;
7945 closedir($dirhandle);
7947 if ($plugins) {
7948 asort($plugins);
7950 return $plugins;
7954 * Invoke plugin's callback functions
7956 * @param string $type plugin type e.g. 'mod'
7957 * @param string $name plugin name
7958 * @param string $feature feature name
7959 * @param string $action feature's action
7960 * @param array $params parameters of callback function, should be an array
7961 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7962 * @return mixed
7964 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7966 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7967 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7971 * Invoke component's callback functions
7973 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7974 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7975 * @param array $params parameters of callback function
7976 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7977 * @return mixed
7979 function component_callback($component, $function, array $params = array(), $default = null) {
7981 $functionname = component_callback_exists($component, $function);
7983 if ($params && (array_keys($params) !== range(0, count($params) - 1))) {
7984 // PHP 8 allows to have associative arrays in the call_user_func_array() parameters but
7985 // PHP 7 does not. Using associative arrays can result in different behavior in different PHP versions.
7986 // See https://php.watch/versions/8.0/named-parameters#named-params-call_user_func_array
7987 // This check can be removed when minimum PHP version for Moodle is raised to 8.
7988 debugging('Parameters array can not be an associative array while Moodle supports both PHP 7 and PHP 8.',
7989 DEBUG_DEVELOPER);
7990 $params = array_values($params);
7993 if ($functionname) {
7994 // Function exists, so just return function result.
7995 $ret = call_user_func_array($functionname, $params);
7996 if (is_null($ret)) {
7997 return $default;
7998 } else {
7999 return $ret;
8002 return $default;
8006 * Determine if a component callback exists and return the function name to call. Note that this
8007 * function will include the required library files so that the functioname returned can be
8008 * called directly.
8010 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
8011 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
8012 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
8013 * @throws coding_exception if invalid component specfied
8015 function component_callback_exists($component, $function) {
8016 global $CFG; // This is needed for the inclusions.
8018 $cleancomponent = clean_param($component, PARAM_COMPONENT);
8019 if (empty($cleancomponent)) {
8020 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8022 $component = $cleancomponent;
8024 list($type, $name) = core_component::normalize_component($component);
8025 $component = $type . '_' . $name;
8027 $oldfunction = $name.'_'.$function;
8028 $function = $component.'_'.$function;
8030 $dir = core_component::get_component_directory($component);
8031 if (empty($dir)) {
8032 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8035 // Load library and look for function.
8036 if (file_exists($dir.'/lib.php')) {
8037 require_once($dir.'/lib.php');
8040 if (!function_exists($function) and function_exists($oldfunction)) {
8041 if ($type !== 'mod' and $type !== 'core') {
8042 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
8044 $function = $oldfunction;
8047 if (function_exists($function)) {
8048 return $function;
8050 return false;
8054 * Call the specified callback method on the provided class.
8056 * If the callback returns null, then the default value is returned instead.
8057 * If the class does not exist, then the default value is returned.
8059 * @param string $classname The name of the class to call upon.
8060 * @param string $methodname The name of the staticically defined method on the class.
8061 * @param array $params The arguments to pass into the method.
8062 * @param mixed $default The default value.
8063 * @return mixed The return value.
8065 function component_class_callback($classname, $methodname, array $params, $default = null) {
8066 if (!class_exists($classname)) {
8067 return $default;
8070 if (!method_exists($classname, $methodname)) {
8071 return $default;
8074 $fullfunction = $classname . '::' . $methodname;
8075 $result = call_user_func_array($fullfunction, $params);
8077 if (null === $result) {
8078 return $default;
8079 } else {
8080 return $result;
8085 * Checks whether a plugin supports a specified feature.
8087 * @param string $type Plugin type e.g. 'mod'
8088 * @param string $name Plugin name e.g. 'forum'
8089 * @param string $feature Feature code (FEATURE_xx constant)
8090 * @param mixed $default default value if feature support unknown
8091 * @return mixed Feature result (false if not supported, null if feature is unknown,
8092 * otherwise usually true but may have other feature-specific value such as array)
8093 * @throws coding_exception
8095 function plugin_supports($type, $name, $feature, $default = null) {
8096 global $CFG;
8098 if ($type === 'mod' and $name === 'NEWMODULE') {
8099 // Somebody forgot to rename the module template.
8100 return false;
8103 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
8104 if (empty($component)) {
8105 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8108 $function = null;
8110 if ($type === 'mod') {
8111 // We need this special case because we support subplugins in modules,
8112 // otherwise it would end up in infinite loop.
8113 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8114 include_once("$CFG->dirroot/mod/$name/lib.php");
8115 $function = $component.'_supports';
8116 if (!function_exists($function)) {
8117 // Legacy non-frankenstyle function name.
8118 $function = $name.'_supports';
8122 } else {
8123 if (!$path = core_component::get_plugin_directory($type, $name)) {
8124 // Non existent plugin type.
8125 return false;
8127 if (file_exists("$path/lib.php")) {
8128 include_once("$path/lib.php");
8129 $function = $component.'_supports';
8133 if ($function and function_exists($function)) {
8134 $supports = $function($feature);
8135 if (is_null($supports)) {
8136 // Plugin does not know - use default.
8137 return $default;
8138 } else {
8139 return $supports;
8143 // Plugin does not care, so use default.
8144 return $default;
8148 * Returns true if the current version of PHP is greater that the specified one.
8150 * @todo Check PHP version being required here is it too low?
8152 * @param string $version The version of php being tested.
8153 * @return bool
8155 function check_php_version($version='5.2.4') {
8156 return (version_compare(phpversion(), $version) >= 0);
8160 * Determine if moodle installation requires update.
8162 * Checks version numbers of main code and all plugins to see
8163 * if there are any mismatches.
8165 * @return bool
8167 function moodle_needs_upgrading() {
8168 global $CFG;
8170 if (empty($CFG->version)) {
8171 return true;
8174 // There is no need to purge plugininfo caches here because
8175 // these caches are not used during upgrade and they are purged after
8176 // every upgrade.
8178 if (empty($CFG->allversionshash)) {
8179 return true;
8182 $hash = core_component::get_all_versions_hash();
8184 return ($hash !== $CFG->allversionshash);
8188 * Returns the major version of this site
8190 * Moodle version numbers consist of three numbers separated by a dot, for
8191 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
8192 * called major version. This function extracts the major version from either
8193 * $CFG->release (default) or eventually from the $release variable defined in
8194 * the main version.php.
8196 * @param bool $fromdisk should the version if source code files be used
8197 * @return string|false the major version like '2.3', false if could not be determined
8199 function moodle_major_version($fromdisk = false) {
8200 global $CFG;
8202 if ($fromdisk) {
8203 $release = null;
8204 require($CFG->dirroot.'/version.php');
8205 if (empty($release)) {
8206 return false;
8209 } else {
8210 if (empty($CFG->release)) {
8211 return false;
8213 $release = $CFG->release;
8216 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8217 return $matches[0];
8218 } else {
8219 return false;
8223 // MISCELLANEOUS.
8226 * Gets the system locale
8228 * @return string Retuns the current locale.
8230 function moodle_getlocale() {
8231 global $CFG;
8233 // Fetch the correct locale based on ostype.
8234 if ($CFG->ostype == 'WINDOWS') {
8235 $stringtofetch = 'localewin';
8236 } else {
8237 $stringtofetch = 'locale';
8240 if (!empty($CFG->locale)) { // Override locale for all language packs.
8241 return $CFG->locale;
8244 return get_string($stringtofetch, 'langconfig');
8248 * Sets the system locale
8250 * @category string
8251 * @param string $locale Can be used to force a locale
8253 function moodle_setlocale($locale='') {
8254 global $CFG;
8256 static $currentlocale = ''; // Last locale caching.
8258 $oldlocale = $currentlocale;
8260 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8261 if (!empty($locale)) {
8262 $currentlocale = $locale;
8263 } else {
8264 $currentlocale = moodle_getlocale();
8267 // Do nothing if locale already set up.
8268 if ($oldlocale == $currentlocale) {
8269 return;
8272 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8273 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8274 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8276 // Get current values.
8277 $monetary= setlocale (LC_MONETARY, 0);
8278 $numeric = setlocale (LC_NUMERIC, 0);
8279 $ctype = setlocale (LC_CTYPE, 0);
8280 if ($CFG->ostype != 'WINDOWS') {
8281 $messages= setlocale (LC_MESSAGES, 0);
8283 // Set locale to all.
8284 $result = setlocale (LC_ALL, $currentlocale);
8285 // If setting of locale fails try the other utf8 or utf-8 variant,
8286 // some operating systems support both (Debian), others just one (OSX).
8287 if ($result === false) {
8288 if (stripos($currentlocale, '.UTF-8') !== false) {
8289 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8290 setlocale (LC_ALL, $newlocale);
8291 } else if (stripos($currentlocale, '.UTF8') !== false) {
8292 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8293 setlocale (LC_ALL, $newlocale);
8296 // Set old values.
8297 setlocale (LC_MONETARY, $monetary);
8298 setlocale (LC_NUMERIC, $numeric);
8299 if ($CFG->ostype != 'WINDOWS') {
8300 setlocale (LC_MESSAGES, $messages);
8302 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8303 // To workaround a well-known PHP problem with Turkish letter Ii.
8304 setlocale (LC_CTYPE, $ctype);
8309 * Count words in a string.
8311 * Words are defined as things between whitespace.
8313 * @category string
8314 * @param string $string The text to be searched for words. May be HTML.
8315 * @return int The count of words in the specified string
8317 function count_words($string) {
8318 // Before stripping tags, add a space after the close tag of anything that is not obviously inline.
8319 // Also, br is a special case because it definitely delimits a word, but has no close tag.
8320 $string = preg_replace('~
8321 ( # Capture the tag we match.
8322 </ # Start of close tag.
8323 (?! # Do not match any of these specific close tag names.
8324 a> | b> | del> | em> | i> |
8325 ins> | s> | small> |
8326 strong> | sub> | sup> | u>
8328 \w+ # But, apart from those execptions, match any tag name.
8329 > # End of close tag.
8331 <br> | <br\s*/> # Special cases that are not close tags.
8333 ~x', '$1 ', $string); // Add a space after the close tag.
8334 // Now remove HTML tags.
8335 $string = strip_tags($string);
8336 // Decode HTML entities.
8337 $string = html_entity_decode($string);
8339 // Now, the word count is the number of blocks of characters separated
8340 // by any sort of space. That seems to be the definition used by all other systems.
8341 // To be precise about what is considered to separate words:
8342 // * Anything that Unicode considers a 'Separator'
8343 // * Anything that Unicode considers a 'Control character'
8344 // * An em- or en- dash.
8345 return count(preg_split('~[\p{Z}\p{Cc}—–]+~u', $string, -1, PREG_SPLIT_NO_EMPTY));
8349 * Count letters in a string.
8351 * Letters are defined as chars not in tags and different from whitespace.
8353 * @category string
8354 * @param string $string The text to be searched for letters. May be HTML.
8355 * @return int The count of letters in the specified text.
8357 function count_letters($string) {
8358 $string = strip_tags($string); // Tags are out now.
8359 $string = html_entity_decode($string);
8360 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8362 return core_text::strlen($string);
8366 * Generate and return a random string of the specified length.
8368 * @param int $length The length of the string to be created.
8369 * @return string
8371 function random_string($length=15) {
8372 $randombytes = random_bytes_emulate($length);
8373 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8374 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8375 $pool .= '0123456789';
8376 $poollen = strlen($pool);
8377 $string = '';
8378 for ($i = 0; $i < $length; $i++) {
8379 $rand = ord($randombytes[$i]);
8380 $string .= substr($pool, ($rand%($poollen)), 1);
8382 return $string;
8386 * Generate a complex random string (useful for md5 salts)
8388 * This function is based on the above {@link random_string()} however it uses a
8389 * larger pool of characters and generates a string between 24 and 32 characters
8391 * @param int $length Optional if set generates a string to exactly this length
8392 * @return string
8394 function complex_random_string($length=null) {
8395 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8396 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8397 $poollen = strlen($pool);
8398 if ($length===null) {
8399 $length = floor(rand(24, 32));
8401 $randombytes = random_bytes_emulate($length);
8402 $string = '';
8403 for ($i = 0; $i < $length; $i++) {
8404 $rand = ord($randombytes[$i]);
8405 $string .= $pool[($rand%$poollen)];
8407 return $string;
8411 * Try to generates cryptographically secure pseudo-random bytes.
8413 * Note this is achieved by fallbacking between:
8414 * - PHP 7 random_bytes().
8415 * - OpenSSL openssl_random_pseudo_bytes().
8416 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8418 * @param int $length requested length in bytes
8419 * @return string binary data
8421 function random_bytes_emulate($length) {
8422 global $CFG;
8423 if ($length <= 0) {
8424 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8425 return '';
8427 if (function_exists('random_bytes')) {
8428 // Use PHP 7 goodness.
8429 $hash = @random_bytes($length);
8430 if ($hash !== false) {
8431 return $hash;
8434 if (function_exists('openssl_random_pseudo_bytes')) {
8435 // If you have the openssl extension enabled.
8436 $hash = openssl_random_pseudo_bytes($length);
8437 if ($hash !== false) {
8438 return $hash;
8442 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8443 $staticdata = serialize($CFG) . serialize($_SERVER);
8444 $hash = '';
8445 do {
8446 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8447 } while (strlen($hash) < $length);
8449 return substr($hash, 0, $length);
8453 * Given some text (which may contain HTML) and an ideal length,
8454 * this function truncates the text neatly on a word boundary if possible
8456 * @category string
8457 * @param string $text text to be shortened
8458 * @param int $ideal ideal string length
8459 * @param boolean $exact if false, $text will not be cut mid-word
8460 * @param string $ending The string to append if the passed string is truncated
8461 * @return string $truncate shortened string
8463 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8464 // If the plain text is shorter than the maximum length, return the whole text.
8465 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8466 return $text;
8469 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8470 // and only tag in its 'line'.
8471 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8473 $totallength = core_text::strlen($ending);
8474 $truncate = '';
8476 // This array stores information about open and close tags and their position
8477 // in the truncated string. Each item in the array is an object with fields
8478 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8479 // (byte position in truncated text).
8480 $tagdetails = array();
8482 foreach ($lines as $linematchings) {
8483 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8484 if (!empty($linematchings[1])) {
8485 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8486 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8487 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8488 // Record closing tag.
8489 $tagdetails[] = (object) array(
8490 'open' => false,
8491 'tag' => core_text::strtolower($tagmatchings[1]),
8492 'pos' => core_text::strlen($truncate),
8495 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8496 // Record opening tag.
8497 $tagdetails[] = (object) array(
8498 'open' => true,
8499 'tag' => core_text::strtolower($tagmatchings[1]),
8500 'pos' => core_text::strlen($truncate),
8502 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8503 $tagdetails[] = (object) array(
8504 'open' => true,
8505 'tag' => core_text::strtolower('if'),
8506 'pos' => core_text::strlen($truncate),
8508 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8509 $tagdetails[] = (object) array(
8510 'open' => false,
8511 'tag' => core_text::strtolower('if'),
8512 'pos' => core_text::strlen($truncate),
8516 // Add html-tag to $truncate'd text.
8517 $truncate .= $linematchings[1];
8520 // Calculate the length of the plain text part of the line; handle entities as one character.
8521 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8522 if ($totallength + $contentlength > $ideal) {
8523 // The number of characters which are left.
8524 $left = $ideal - $totallength;
8525 $entitieslength = 0;
8526 // Search for html entities.
8527 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)) {
8528 // Calculate the real length of all entities in the legal range.
8529 foreach ($entities[0] as $entity) {
8530 if ($entity[1]+1-$entitieslength <= $left) {
8531 $left--;
8532 $entitieslength += core_text::strlen($entity[0]);
8533 } else {
8534 // No more characters left.
8535 break;
8539 $breakpos = $left + $entitieslength;
8541 // If the words shouldn't be cut in the middle...
8542 if (!$exact) {
8543 // Search the last occurence of a space.
8544 for (; $breakpos > 0; $breakpos--) {
8545 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8546 if ($char === '.' or $char === ' ') {
8547 $breakpos += 1;
8548 break;
8549 } else if (strlen($char) > 2) {
8550 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8551 $breakpos += 1;
8552 break;
8557 if ($breakpos == 0) {
8558 // This deals with the test_shorten_text_no_spaces case.
8559 $breakpos = $left + $entitieslength;
8560 } else if ($breakpos > $left + $entitieslength) {
8561 // This deals with the previous for loop breaking on the first char.
8562 $breakpos = $left + $entitieslength;
8565 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8566 // Maximum length is reached, so get off the loop.
8567 break;
8568 } else {
8569 $truncate .= $linematchings[2];
8570 $totallength += $contentlength;
8573 // If the maximum length is reached, get off the loop.
8574 if ($totallength >= $ideal) {
8575 break;
8579 // Add the defined ending to the text.
8580 $truncate .= $ending;
8582 // Now calculate the list of open html tags based on the truncate position.
8583 $opentags = array();
8584 foreach ($tagdetails as $taginfo) {
8585 if ($taginfo->open) {
8586 // Add tag to the beginning of $opentags list.
8587 array_unshift($opentags, $taginfo->tag);
8588 } else {
8589 // Can have multiple exact same open tags, close the last one.
8590 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8591 if ($pos !== false) {
8592 unset($opentags[$pos]);
8597 // Close all unclosed html-tags.
8598 foreach ($opentags as $tag) {
8599 if ($tag === 'if') {
8600 $truncate .= '<!--<![endif]-->';
8601 } else {
8602 $truncate .= '</' . $tag . '>';
8606 return $truncate;
8610 * Shortens a given filename by removing characters positioned after the ideal string length.
8611 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8612 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8614 * @param string $filename file name
8615 * @param int $length ideal string length
8616 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8617 * @return string $shortened shortened file name
8619 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8620 $shortened = $filename;
8621 // Extract a part of the filename if it's char size exceeds the ideal string length.
8622 if (core_text::strlen($filename) > $length) {
8623 // Exclude extension if present in filename.
8624 $mimetypes = get_mimetypes_array();
8625 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8626 if ($extension && !empty($mimetypes[$extension])) {
8627 $basename = pathinfo($filename, PATHINFO_FILENAME);
8628 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8629 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8630 $shortened .= '.' . $extension;
8631 } else {
8632 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8633 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8636 return $shortened;
8640 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8642 * @param array $path The paths to reduce the length.
8643 * @param int $length Ideal string length
8644 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8645 * @return array $result Shortened paths in array.
8647 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8648 $result = null;
8650 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8651 $carry[] = shorten_filename($singlepath, $length, $includehash);
8652 return $carry;
8653 }, []);
8655 return $result;
8659 * Given dates in seconds, how many weeks is the date from startdate
8660 * The first week is 1, the second 2 etc ...
8662 * @param int $startdate Timestamp for the start date
8663 * @param int $thedate Timestamp for the end date
8664 * @return string
8666 function getweek ($startdate, $thedate) {
8667 if ($thedate < $startdate) {
8668 return 0;
8671 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8675 * Returns a randomly generated password of length $maxlen. inspired by
8677 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8678 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8680 * @param int $maxlen The maximum size of the password being generated.
8681 * @return string
8683 function generate_password($maxlen=10) {
8684 global $CFG;
8686 if (empty($CFG->passwordpolicy)) {
8687 $fillers = PASSWORD_DIGITS;
8688 $wordlist = file($CFG->wordlist);
8689 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8690 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8691 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8692 $password = $word1 . $filler1 . $word2;
8693 } else {
8694 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8695 $digits = $CFG->minpassworddigits;
8696 $lower = $CFG->minpasswordlower;
8697 $upper = $CFG->minpasswordupper;
8698 $nonalphanum = $CFG->minpasswordnonalphanum;
8699 $total = $lower + $upper + $digits + $nonalphanum;
8700 // Var minlength should be the greater one of the two ( $minlen and $total ).
8701 $minlen = $minlen < $total ? $total : $minlen;
8702 // Var maxlen can never be smaller than minlen.
8703 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8704 $additional = $maxlen - $total;
8706 // Make sure we have enough characters to fulfill
8707 // complexity requirements.
8708 $passworddigits = PASSWORD_DIGITS;
8709 while ($digits > strlen($passworddigits)) {
8710 $passworddigits .= PASSWORD_DIGITS;
8712 $passwordlower = PASSWORD_LOWER;
8713 while ($lower > strlen($passwordlower)) {
8714 $passwordlower .= PASSWORD_LOWER;
8716 $passwordupper = PASSWORD_UPPER;
8717 while ($upper > strlen($passwordupper)) {
8718 $passwordupper .= PASSWORD_UPPER;
8720 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8721 while ($nonalphanum > strlen($passwordnonalphanum)) {
8722 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8725 // Now mix and shuffle it all.
8726 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8727 substr(str_shuffle ($passwordupper), 0, $upper) .
8728 substr(str_shuffle ($passworddigits), 0, $digits) .
8729 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8730 substr(str_shuffle ($passwordlower .
8731 $passwordupper .
8732 $passworddigits .
8733 $passwordnonalphanum), 0 , $additional));
8736 return substr ($password, 0, $maxlen);
8740 * Given a float, prints it nicely.
8741 * Localized floats must not be used in calculations!
8743 * The stripzeros feature is intended for making numbers look nicer in small
8744 * areas where it is not necessary to indicate the degree of accuracy by showing
8745 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8746 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8748 * @param float $float The float to print
8749 * @param int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision).
8750 * @param bool $localized use localized decimal separator
8751 * @param bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after
8752 * the decimal point are always striped if $decimalpoints is -1.
8753 * @return string locale float
8755 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8756 if (is_null($float)) {
8757 return '';
8759 if ($localized) {
8760 $separator = get_string('decsep', 'langconfig');
8761 } else {
8762 $separator = '.';
8764 if ($decimalpoints == -1) {
8765 // The following counts the number of decimals.
8766 // It is safe as both floatval() and round() functions have same behaviour when non-numeric values are provided.
8767 $floatval = floatval($float);
8768 for ($decimalpoints = 0; $floatval != round($float, $decimalpoints); $decimalpoints++);
8771 $result = number_format($float, $decimalpoints, $separator, '');
8772 if ($stripzeros && $decimalpoints > 0) {
8773 // Remove zeros and final dot if not needed.
8774 // However, only do this if there is a decimal point!
8775 $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
8777 return $result;
8781 * Converts locale specific floating point/comma number back to standard PHP float value
8782 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8784 * @param string $localefloat locale aware float representation
8785 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8786 * @return mixed float|bool - false or the parsed float.
8788 function unformat_float($localefloat, $strict = false) {
8789 $localefloat = trim($localefloat);
8791 if ($localefloat == '') {
8792 return null;
8795 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8796 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8798 if ($strict && !is_numeric($localefloat)) {
8799 return false;
8802 return (float)$localefloat;
8806 * Given a simple array, this shuffles it up just like shuffle()
8807 * Unlike PHP's shuffle() this function works on any machine.
8809 * @param array $array The array to be rearranged
8810 * @return array
8812 function swapshuffle($array) {
8814 $last = count($array) - 1;
8815 for ($i = 0; $i <= $last; $i++) {
8816 $from = rand(0, $last);
8817 $curr = $array[$i];
8818 $array[$i] = $array[$from];
8819 $array[$from] = $curr;
8821 return $array;
8825 * Like {@link swapshuffle()}, but works on associative arrays
8827 * @param array $array The associative array to be rearranged
8828 * @return array
8830 function swapshuffle_assoc($array) {
8832 $newarray = array();
8833 $newkeys = swapshuffle(array_keys($array));
8835 foreach ($newkeys as $newkey) {
8836 $newarray[$newkey] = $array[$newkey];
8838 return $newarray;
8842 * Given an arbitrary array, and a number of draws,
8843 * this function returns an array with that amount
8844 * of items. The indexes are retained.
8846 * @todo Finish documenting this function
8848 * @param array $array
8849 * @param int $draws
8850 * @return array
8852 function draw_rand_array($array, $draws) {
8854 $return = array();
8856 $last = count($array);
8858 if ($draws > $last) {
8859 $draws = $last;
8862 while ($draws > 0) {
8863 $last--;
8865 $keys = array_keys($array);
8866 $rand = rand(0, $last);
8868 $return[$keys[$rand]] = $array[$keys[$rand]];
8869 unset($array[$keys[$rand]]);
8871 $draws--;
8874 return $return;
8878 * Calculate the difference between two microtimes
8880 * @param string $a The first Microtime
8881 * @param string $b The second Microtime
8882 * @return string
8884 function microtime_diff($a, $b) {
8885 list($adec, $asec) = explode(' ', $a);
8886 list($bdec, $bsec) = explode(' ', $b);
8887 return $bsec - $asec + $bdec - $adec;
8891 * Given a list (eg a,b,c,d,e) this function returns
8892 * an array of 1->a, 2->b, 3->c etc
8894 * @param string $list The string to explode into array bits
8895 * @param string $separator The separator used within the list string
8896 * @return array The now assembled array
8898 function make_menu_from_list($list, $separator=',') {
8900 $array = array_reverse(explode($separator, $list), true);
8901 foreach ($array as $key => $item) {
8902 $outarray[$key+1] = trim($item);
8904 return $outarray;
8908 * Creates an array that represents all the current grades that
8909 * can be chosen using the given grading type.
8911 * Negative numbers
8912 * are scales, zero is no grade, and positive numbers are maximum
8913 * grades.
8915 * @todo Finish documenting this function or better deprecated this completely!
8917 * @param int $gradingtype
8918 * @return array
8920 function make_grades_menu($gradingtype) {
8921 global $DB;
8923 $grades = array();
8924 if ($gradingtype < 0) {
8925 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8926 return make_menu_from_list($scale->scale);
8928 } else if ($gradingtype > 0) {
8929 for ($i=$gradingtype; $i>=0; $i--) {
8930 $grades[$i] = $i .' / '. $gradingtype;
8932 return $grades;
8934 return $grades;
8938 * make_unique_id_code
8940 * @todo Finish documenting this function
8942 * @uses $_SERVER
8943 * @param string $extra Extra string to append to the end of the code
8944 * @return string
8946 function make_unique_id_code($extra = '') {
8948 $hostname = 'unknownhost';
8949 if (!empty($_SERVER['HTTP_HOST'])) {
8950 $hostname = $_SERVER['HTTP_HOST'];
8951 } else if (!empty($_ENV['HTTP_HOST'])) {
8952 $hostname = $_ENV['HTTP_HOST'];
8953 } else if (!empty($_SERVER['SERVER_NAME'])) {
8954 $hostname = $_SERVER['SERVER_NAME'];
8955 } else if (!empty($_ENV['SERVER_NAME'])) {
8956 $hostname = $_ENV['SERVER_NAME'];
8959 $date = gmdate("ymdHis");
8961 $random = random_string(6);
8963 if ($extra) {
8964 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8965 } else {
8966 return $hostname .'+'. $date .'+'. $random;
8972 * Function to check the passed address is within the passed subnet
8974 * The parameter is a comma separated string of subnet definitions.
8975 * Subnet strings can be in one of three formats:
8976 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8977 * 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)
8978 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8979 * Code for type 1 modified from user posted comments by mediator at
8980 * {@link http://au.php.net/manual/en/function.ip2long.php}
8982 * @param string $addr The address you are checking
8983 * @param string $subnetstr The string of subnet addresses
8984 * @return bool
8986 function address_in_subnet($addr, $subnetstr) {
8988 if ($addr == '0.0.0.0') {
8989 return false;
8991 $subnets = explode(',', $subnetstr);
8992 $found = false;
8993 $addr = trim($addr);
8994 $addr = cleanremoteaddr($addr, false); // Normalise.
8995 if ($addr === null) {
8996 return false;
8998 $addrparts = explode(':', $addr);
9000 $ipv6 = strpos($addr, ':');
9002 foreach ($subnets as $subnet) {
9003 $subnet = trim($subnet);
9004 if ($subnet === '') {
9005 continue;
9008 if (strpos($subnet, '/') !== false) {
9009 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
9010 list($ip, $mask) = explode('/', $subnet);
9011 $mask = trim($mask);
9012 if (!is_number($mask)) {
9013 continue; // Incorect mask number, eh?
9015 $ip = cleanremoteaddr($ip, false); // Normalise.
9016 if ($ip === null) {
9017 continue;
9019 if (strpos($ip, ':') !== false) {
9020 // IPv6.
9021 if (!$ipv6) {
9022 continue;
9024 if ($mask > 128 or $mask < 0) {
9025 continue; // Nonsense.
9027 if ($mask == 0) {
9028 return true; // Any address.
9030 if ($mask == 128) {
9031 if ($ip === $addr) {
9032 return true;
9034 continue;
9036 $ipparts = explode(':', $ip);
9037 $modulo = $mask % 16;
9038 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
9039 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
9040 if (implode(':', $ipnet) === implode(':', $addrnet)) {
9041 if ($modulo == 0) {
9042 return true;
9044 $pos = ($mask-$modulo)/16;
9045 $ipnet = hexdec($ipparts[$pos]);
9046 $addrnet = hexdec($addrparts[$pos]);
9047 $mask = 0xffff << (16 - $modulo);
9048 if (($addrnet & $mask) == ($ipnet & $mask)) {
9049 return true;
9053 } else {
9054 // IPv4.
9055 if ($ipv6) {
9056 continue;
9058 if ($mask > 32 or $mask < 0) {
9059 continue; // Nonsense.
9061 if ($mask == 0) {
9062 return true;
9064 if ($mask == 32) {
9065 if ($ip === $addr) {
9066 return true;
9068 continue;
9070 $mask = 0xffffffff << (32 - $mask);
9071 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
9072 return true;
9076 } else if (strpos($subnet, '-') !== false) {
9077 // 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.
9078 $parts = explode('-', $subnet);
9079 if (count($parts) != 2) {
9080 continue;
9083 if (strpos($subnet, ':') !== false) {
9084 // IPv6.
9085 if (!$ipv6) {
9086 continue;
9088 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9089 if ($ipstart === null) {
9090 continue;
9092 $ipparts = explode(':', $ipstart);
9093 $start = hexdec(array_pop($ipparts));
9094 $ipparts[] = trim($parts[1]);
9095 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
9096 if ($ipend === null) {
9097 continue;
9099 $ipparts[7] = '';
9100 $ipnet = implode(':', $ipparts);
9101 if (strpos($addr, $ipnet) !== 0) {
9102 continue;
9104 $ipparts = explode(':', $ipend);
9105 $end = hexdec($ipparts[7]);
9107 $addrend = hexdec($addrparts[7]);
9109 if (($addrend >= $start) and ($addrend <= $end)) {
9110 return true;
9113 } else {
9114 // IPv4.
9115 if ($ipv6) {
9116 continue;
9118 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9119 if ($ipstart === null) {
9120 continue;
9122 $ipparts = explode('.', $ipstart);
9123 $ipparts[3] = trim($parts[1]);
9124 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
9125 if ($ipend === null) {
9126 continue;
9129 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9130 return true;
9134 } else {
9135 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9136 if (strpos($subnet, ':') !== false) {
9137 // IPv6.
9138 if (!$ipv6) {
9139 continue;
9141 $parts = explode(':', $subnet);
9142 $count = count($parts);
9143 if ($parts[$count-1] === '') {
9144 unset($parts[$count-1]); // Trim trailing :'s.
9145 $count--;
9146 $subnet = implode('.', $parts);
9148 $isip = cleanremoteaddr($subnet, false); // Normalise.
9149 if ($isip !== null) {
9150 if ($isip === $addr) {
9151 return true;
9153 continue;
9154 } else if ($count > 8) {
9155 continue;
9157 $zeros = array_fill(0, 8-$count, '0');
9158 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9159 if (address_in_subnet($addr, $subnet)) {
9160 return true;
9163 } else {
9164 // IPv4.
9165 if ($ipv6) {
9166 continue;
9168 $parts = explode('.', $subnet);
9169 $count = count($parts);
9170 if ($parts[$count-1] === '') {
9171 unset($parts[$count-1]); // Trim trailing .
9172 $count--;
9173 $subnet = implode('.', $parts);
9175 if ($count == 4) {
9176 $subnet = cleanremoteaddr($subnet, false); // Normalise.
9177 if ($subnet === $addr) {
9178 return true;
9180 continue;
9181 } else if ($count > 4) {
9182 continue;
9184 $zeros = array_fill(0, 4-$count, '0');
9185 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9186 if (address_in_subnet($addr, $subnet)) {
9187 return true;
9193 return false;
9197 * For outputting debugging info
9199 * @param string $string The string to write
9200 * @param string $eol The end of line char(s) to use
9201 * @param string $sleep Period to make the application sleep
9202 * This ensures any messages have time to display before redirect
9204 function mtrace($string, $eol="\n", $sleep=0) {
9205 global $CFG;
9207 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
9208 $fn = $CFG->mtrace_wrapper;
9209 $fn($string, $eol);
9210 return;
9211 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
9212 // We must explicitly call the add_line function here.
9213 // Uses of fwrite to STDOUT are not picked up by ob_start.
9214 if ($output = \core\task\logmanager::add_line("{$string}{$eol}")) {
9215 fwrite(STDOUT, $output);
9217 } else {
9218 echo $string . $eol;
9221 // Flush again.
9222 flush();
9224 // Delay to keep message on user's screen in case of subsequent redirect.
9225 if ($sleep) {
9226 sleep($sleep);
9231 * Replace 1 or more slashes or backslashes to 1 slash
9233 * @param string $path The path to strip
9234 * @return string the path with double slashes removed
9236 function cleardoubleslashes ($path) {
9237 return preg_replace('/(\/|\\\){1,}/', '/', $path);
9241 * Is the current ip in a given list?
9243 * @param string $list
9244 * @return bool
9246 function remoteip_in_list($list) {
9247 $clientip = getremoteaddr(null);
9249 if (!$clientip) {
9250 // Ensure access on cli.
9251 return true;
9253 return \core\ip_utils::is_ip_in_subnet_list($clientip, $list);
9257 * Returns most reliable client address
9259 * @param string $default If an address can't be determined, then return this
9260 * @return string The remote IP address
9262 function getremoteaddr($default='0.0.0.0') {
9263 global $CFG;
9265 if (!isset($CFG->getremoteaddrconf)) {
9266 // This will happen, for example, before just after the upgrade, as the
9267 // user is redirected to the admin screen.
9268 $variablestoskip = GETREMOTEADDR_SKIP_DEFAULT;
9269 } else {
9270 $variablestoskip = $CFG->getremoteaddrconf;
9272 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
9273 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9274 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9275 return $address ? $address : $default;
9278 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
9279 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9280 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9282 $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
9283 global $CFG;
9284 return !\core\ip_utils::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore ?? '', ',');
9287 // Multiple proxies can append values to this header including an
9288 // untrusted original request header so we must only trust the last ip.
9289 $address = end($forwardedaddresses);
9291 if (substr_count($address, ":") > 1) {
9292 // Remove port and brackets from IPv6.
9293 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9294 $address = $matches[1];
9296 } else {
9297 // Remove port from IPv4.
9298 if (substr_count($address, ":") == 1) {
9299 $parts = explode(":", $address);
9300 $address = $parts[0];
9304 $address = cleanremoteaddr($address);
9305 return $address ? $address : $default;
9308 if (!empty($_SERVER['REMOTE_ADDR'])) {
9309 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9310 return $address ? $address : $default;
9311 } else {
9312 return $default;
9317 * Cleans an ip address. Internal addresses are now allowed.
9318 * (Originally local addresses were not allowed.)
9320 * @param string $addr IPv4 or IPv6 address
9321 * @param bool $compress use IPv6 address compression
9322 * @return string normalised ip address string, null if error
9324 function cleanremoteaddr($addr, $compress=false) {
9325 $addr = trim($addr);
9327 if (strpos($addr, ':') !== false) {
9328 // Can be only IPv6.
9329 $parts = explode(':', $addr);
9330 $count = count($parts);
9332 if (strpos($parts[$count-1], '.') !== false) {
9333 // Legacy ipv4 notation.
9334 $last = array_pop($parts);
9335 $ipv4 = cleanremoteaddr($last, true);
9336 if ($ipv4 === null) {
9337 return null;
9339 $bits = explode('.', $ipv4);
9340 $parts[] = dechex($bits[0]).dechex($bits[1]);
9341 $parts[] = dechex($bits[2]).dechex($bits[3]);
9342 $count = count($parts);
9343 $addr = implode(':', $parts);
9346 if ($count < 3 or $count > 8) {
9347 return null; // Severly malformed.
9350 if ($count != 8) {
9351 if (strpos($addr, '::') === false) {
9352 return null; // Malformed.
9354 // Uncompress.
9355 $insertat = array_search('', $parts, true);
9356 $missing = array_fill(0, 1 + 8 - $count, '0');
9357 array_splice($parts, $insertat, 1, $missing);
9358 foreach ($parts as $key => $part) {
9359 if ($part === '') {
9360 $parts[$key] = '0';
9365 $adr = implode(':', $parts);
9366 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9367 return null; // Incorrect format - sorry.
9370 // Normalise 0s and case.
9371 $parts = array_map('hexdec', $parts);
9372 $parts = array_map('dechex', $parts);
9374 $result = implode(':', $parts);
9376 if (!$compress) {
9377 return $result;
9380 if ($result === '0:0:0:0:0:0:0:0') {
9381 return '::'; // All addresses.
9384 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9385 if ($compressed !== $result) {
9386 return $compressed;
9389 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9390 if ($compressed !== $result) {
9391 return $compressed;
9394 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9395 if ($compressed !== $result) {
9396 return $compressed;
9399 return $result;
9402 // First get all things that look like IPv4 addresses.
9403 $parts = array();
9404 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9405 return null;
9407 unset($parts[0]);
9409 foreach ($parts as $key => $match) {
9410 if ($match > 255) {
9411 return null;
9413 $parts[$key] = (int)$match; // Normalise 0s.
9416 return implode('.', $parts);
9421 * Is IP address a public address?
9423 * @param string $ip The ip to check
9424 * @return bool true if the ip is public
9426 function ip_is_public($ip) {
9427 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9431 * This function will make a complete copy of anything it's given,
9432 * regardless of whether it's an object or not.
9434 * @param mixed $thing Something you want cloned
9435 * @return mixed What ever it is you passed it
9437 function fullclone($thing) {
9438 return unserialize(serialize($thing));
9442 * Used to make sure that $min <= $value <= $max
9444 * Make sure that value is between min, and max
9446 * @param int $min The minimum value
9447 * @param int $value The value to check
9448 * @param int $max The maximum value
9449 * @return int
9451 function bounded_number($min, $value, $max) {
9452 if ($value < $min) {
9453 return $min;
9455 if ($value > $max) {
9456 return $max;
9458 return $value;
9462 * Check if there is a nested array within the passed array
9464 * @param array $array
9465 * @return bool true if there is a nested array false otherwise
9467 function array_is_nested($array) {
9468 foreach ($array as $value) {
9469 if (is_array($value)) {
9470 return true;
9473 return false;
9477 * get_performance_info() pairs up with init_performance_info()
9478 * loaded in setup.php. Returns an array with 'html' and 'txt'
9479 * values ready for use, and each of the individual stats provided
9480 * separately as well.
9482 * @return array
9484 function get_performance_info() {
9485 global $CFG, $PERF, $DB, $PAGE;
9487 $info = array();
9488 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9490 $info['html'] = '';
9491 if (!empty($CFG->themedesignermode)) {
9492 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9493 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9495 $info['html'] .= '<ul class="list-unstyled row mx-md-0">'; // Holds userfriendly HTML representation.
9497 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9499 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9500 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9502 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9503 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9505 if (function_exists('memory_get_usage')) {
9506 $info['memory_total'] = memory_get_usage();
9507 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9508 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9509 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9510 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9513 if (function_exists('memory_get_peak_usage')) {
9514 $info['memory_peak'] = memory_get_peak_usage();
9515 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9516 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9519 $info['html'] .= '</ul><ul class="list-unstyled row mx-md-0">';
9520 $inc = get_included_files();
9521 $info['includecount'] = count($inc);
9522 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9523 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9525 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9526 // We can not track more performance before installation or before PAGE init, sorry.
9527 return $info;
9530 $filtermanager = filter_manager::instance();
9531 if (method_exists($filtermanager, 'get_performance_summary')) {
9532 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9533 $info = array_merge($filterinfo, $info);
9534 foreach ($filterinfo as $key => $value) {
9535 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9536 $info['txt'] .= "$key: $value ";
9540 $stringmanager = get_string_manager();
9541 if (method_exists($stringmanager, 'get_performance_summary')) {
9542 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9543 $info = array_merge($filterinfo, $info);
9544 foreach ($filterinfo as $key => $value) {
9545 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9546 $info['txt'] .= "$key: $value ";
9550 if (!empty($PERF->logwrites)) {
9551 $info['logwrites'] = $PERF->logwrites;
9552 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9553 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9556 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9557 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9558 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9560 if ($DB->want_read_slave()) {
9561 $info['dbreads_slave'] = $DB->perf_get_reads_slave();
9562 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads from slave: '.$info['dbreads_slave'].'</li> ';
9563 $info['txt'] .= 'db reads from slave: '.$info['dbreads_slave'].' ';
9566 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9567 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9568 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9570 if (function_exists('posix_times')) {
9571 $ptimes = posix_times();
9572 if (is_array($ptimes)) {
9573 foreach ($ptimes as $key => $val) {
9574 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9576 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9577 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9578 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9582 // Grab the load average for the last minute.
9583 // /proc will only work under some linux configurations
9584 // while uptime is there under MacOSX/Darwin and other unices.
9585 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9586 list($serverload) = explode(' ', $loadavg[0]);
9587 unset($loadavg);
9588 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9589 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9590 $serverload = $matches[1];
9591 } else {
9592 trigger_error('Could not parse uptime output!');
9595 if (!empty($serverload)) {
9596 $info['serverload'] = $serverload;
9597 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9598 $info['txt'] .= "serverload: {$info['serverload']} ";
9601 // Display size of session if session started.
9602 if ($si = \core\session\manager::get_performance_info()) {
9603 $info['sessionsize'] = $si['size'];
9604 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9605 $info['txt'] .= $si['txt'];
9608 $info['html'] .= '</ul>';
9609 $html = '';
9610 if ($stats = cache_helper::get_stats()) {
9612 $table = new html_table();
9613 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9614 $table->head = ['Mode', 'Cache item', 'Static', 'H', 'M', get_string('mappingprimary', 'cache'), 'H', 'M', 'S', 'I/O'];
9615 $table->data = [];
9616 $table->align = ['left', 'left', 'left', 'right', 'right', 'left', 'right', 'right', 'right', 'right'];
9618 $text = 'Caches used (hits/misses/sets): ';
9619 $hits = 0;
9620 $misses = 0;
9621 $sets = 0;
9622 $maxstores = 0;
9624 // We want to align static caches into their own column.
9625 $hasstatic = false;
9626 foreach ($stats as $definition => $details) {
9627 $numstores = count($details['stores']);
9628 $first = key($details['stores']);
9629 if ($first !== cache_store::STATIC_ACCEL) {
9630 $numstores++; // Add a blank space for the missing static store.
9632 $maxstores = max($maxstores, $numstores);
9635 $storec = 0;
9637 while ($storec++ < ($maxstores - 2)) {
9638 if ($storec == ($maxstores - 2)) {
9639 $table->head[] = get_string('mappingfinal', 'cache');
9640 } else {
9641 $table->head[] = "Store $storec";
9643 $table->align[] = 'left';
9644 $table->align[] = 'right';
9645 $table->align[] = 'right';
9646 $table->align[] = 'right';
9647 $table->align[] = 'right';
9648 $table->head[] = 'H';
9649 $table->head[] = 'M';
9650 $table->head[] = 'S';
9651 $table->head[] = 'I/O';
9654 ksort($stats);
9656 foreach ($stats as $definition => $details) {
9657 switch ($details['mode']) {
9658 case cache_store::MODE_APPLICATION:
9659 $modeclass = 'application';
9660 $mode = ' <span title="application cache">App</span>';
9661 break;
9662 case cache_store::MODE_SESSION:
9663 $modeclass = 'session';
9664 $mode = ' <span title="session cache">Ses</span>';
9665 break;
9666 case cache_store::MODE_REQUEST:
9667 $modeclass = 'request';
9668 $mode = ' <span title="request cache">Req</span>';
9669 break;
9671 $row = [$mode, $definition];
9673 $text .= "$definition {";
9675 $storec = 0;
9676 foreach ($details['stores'] as $store => $data) {
9678 if ($storec == 0 && $store !== cache_store::STATIC_ACCEL) {
9679 $row[] = '';
9680 $row[] = '';
9681 $row[] = '';
9682 $storec++;
9685 $hits += $data['hits'];
9686 $misses += $data['misses'];
9687 $sets += $data['sets'];
9688 if ($data['hits'] == 0 and $data['misses'] > 0) {
9689 $cachestoreclass = 'nohits bg-danger';
9690 } else if ($data['hits'] < $data['misses']) {
9691 $cachestoreclass = 'lowhits bg-warning text-dark';
9692 } else {
9693 $cachestoreclass = 'hihits';
9695 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9696 $cell = new html_table_cell($store);
9697 $cell->attributes = ['class' => $cachestoreclass];
9698 $row[] = $cell;
9699 $cell = new html_table_cell($data['hits']);
9700 $cell->attributes = ['class' => $cachestoreclass];
9701 $row[] = $cell;
9702 $cell = new html_table_cell($data['misses']);
9703 $cell->attributes = ['class' => $cachestoreclass];
9704 $row[] = $cell;
9706 if ($store !== cache_store::STATIC_ACCEL) {
9707 // The static cache is never set.
9708 $cell = new html_table_cell($data['sets']);
9709 $cell->attributes = ['class' => $cachestoreclass];
9710 $row[] = $cell;
9712 if ($data['hits'] || $data['sets']) {
9713 if ($data['iobytes'] === cache_store::IO_BYTES_NOT_SUPPORTED) {
9714 $size = '-';
9715 } else {
9716 $size = display_size($data['iobytes'], 1, 'KB');
9717 if ($data['iobytes'] >= 10 * 1024) {
9718 $cachestoreclass = ' bg-warning text-dark';
9721 } else {
9722 $size = '';
9724 $cell = new html_table_cell($size);
9725 $cell->attributes = ['class' => $cachestoreclass];
9726 $row[] = $cell;
9728 $storec++;
9730 while ($storec++ < $maxstores) {
9731 $row[] = '';
9732 $row[] = '';
9733 $row[] = '';
9734 $row[] = '';
9735 $row[] = '';
9737 $text .= '} ';
9739 $table->data[] = $row;
9742 $html .= html_writer::table($table);
9744 // Now lets also show sub totals for each cache store.
9745 $storetotals = [];
9746 $storetotal = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9747 foreach ($stats as $definition => $details) {
9748 foreach ($details['stores'] as $store => $data) {
9749 if (!array_key_exists($store, $storetotals)) {
9750 $storetotals[$store] = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9752 $storetotals[$store]['class'] = $data['class'];
9753 $storetotals[$store]['hits'] += $data['hits'];
9754 $storetotals[$store]['misses'] += $data['misses'];
9755 $storetotals[$store]['sets'] += $data['sets'];
9756 $storetotal['hits'] += $data['hits'];
9757 $storetotal['misses'] += $data['misses'];
9758 $storetotal['sets'] += $data['sets'];
9759 if ($data['iobytes'] !== cache_store::IO_BYTES_NOT_SUPPORTED) {
9760 $storetotals[$store]['iobytes'] += $data['iobytes'];
9761 $storetotal['iobytes'] += $data['iobytes'];
9766 $table = new html_table();
9767 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9768 $table->head = [get_string('storename', 'cache'), get_string('type_cachestore', 'plugin'), 'H', 'M', 'S', 'I/O'];
9769 $table->data = [];
9770 $table->align = ['left', 'left', 'right', 'right', 'right', 'right'];
9772 ksort($storetotals);
9774 foreach ($storetotals as $store => $data) {
9775 $row = [];
9776 if ($data['hits'] == 0 and $data['misses'] > 0) {
9777 $cachestoreclass = 'nohits bg-danger';
9778 } else if ($data['hits'] < $data['misses']) {
9779 $cachestoreclass = 'lowhits bg-warning text-dark';
9780 } else {
9781 $cachestoreclass = 'hihits';
9783 $cell = new html_table_cell($store);
9784 $cell->attributes = ['class' => $cachestoreclass];
9785 $row[] = $cell;
9786 $cell = new html_table_cell($data['class']);
9787 $cell->attributes = ['class' => $cachestoreclass];
9788 $row[] = $cell;
9789 $cell = new html_table_cell($data['hits']);
9790 $cell->attributes = ['class' => $cachestoreclass];
9791 $row[] = $cell;
9792 $cell = new html_table_cell($data['misses']);
9793 $cell->attributes = ['class' => $cachestoreclass];
9794 $row[] = $cell;
9795 $cell = new html_table_cell($data['sets']);
9796 $cell->attributes = ['class' => $cachestoreclass];
9797 $row[] = $cell;
9798 if ($data['hits'] || $data['sets']) {
9799 if ($data['iobytes']) {
9800 $size = display_size($data['iobytes'], 1, 'KB');
9801 } else {
9802 $size = '-';
9804 } else {
9805 $size = '';
9807 $cell = new html_table_cell($size);
9808 $cell->attributes = ['class' => $cachestoreclass];
9809 $row[] = $cell;
9810 $table->data[] = $row;
9812 if (!empty($storetotal['iobytes'])) {
9813 $size = display_size($storetotal['iobytes'], 1, 'KB');
9814 } else if (!empty($storetotal['hits']) || !empty($storetotal['sets'])) {
9815 $size = '-';
9816 } else {
9817 $size = '';
9819 $row = [
9820 get_string('total'),
9822 $storetotal['hits'],
9823 $storetotal['misses'],
9824 $storetotal['sets'],
9825 $size,
9827 $table->data[] = $row;
9829 $html .= html_writer::table($table);
9831 $info['cachesused'] = "$hits / $misses / $sets";
9832 $info['html'] .= $html;
9833 $info['txt'] .= $text.'. ';
9834 } else {
9835 $info['cachesused'] = '0 / 0 / 0';
9836 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9837 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9840 $info['html'] = '<div class="performanceinfo siteinfo container-fluid px-md-0 overflow-auto pt-3">'.$info['html'].'</div>';
9841 return $info;
9845 * Renames a file or directory to a unique name within the same directory.
9847 * This function is designed to avoid any potential race conditions, and select an unused name.
9849 * @param string $filepath Original filepath
9850 * @param string $prefix Prefix to use for the temporary name
9851 * @return string|bool New file path or false if failed
9852 * @since Moodle 3.10
9854 function rename_to_unused_name(string $filepath, string $prefix = '_temp_') {
9855 $dir = dirname($filepath);
9856 $basename = $dir . '/' . $prefix;
9857 $limit = 0;
9858 while ($limit < 100) {
9859 // Select a new name based on a random number.
9860 $newfilepath = $basename . md5(mt_rand());
9862 // Attempt a rename to that new name.
9863 if (@rename($filepath, $newfilepath)) {
9864 return $newfilepath;
9867 // The first time, do some sanity checks, maybe it is failing for a good reason and there
9868 // is no point trying 100 times if so.
9869 if ($limit === 0 && (!file_exists($filepath) || !is_writable($dir))) {
9870 return false;
9872 $limit++;
9874 return false;
9878 * Delete directory or only its content
9880 * @param string $dir directory path
9881 * @param bool $contentonly
9882 * @return bool success, true also if dir does not exist
9884 function remove_dir($dir, $contentonly=false) {
9885 if (!is_dir($dir)) {
9886 // Nothing to do.
9887 return true;
9890 if (!$contentonly) {
9891 // Start by renaming the directory; this will guarantee that other processes don't write to it
9892 // while it is in the process of being deleted.
9893 $tempdir = rename_to_unused_name($dir);
9894 if ($tempdir) {
9895 // If the rename was successful then delete the $tempdir instead.
9896 $dir = $tempdir;
9898 // If the rename fails, we will continue through and attempt to delete the directory
9899 // without renaming it since that is likely to at least delete most of the files.
9902 if (!$handle = opendir($dir)) {
9903 return false;
9905 $result = true;
9906 while (false!==($item = readdir($handle))) {
9907 if ($item != '.' && $item != '..') {
9908 if (is_dir($dir.'/'.$item)) {
9909 $result = remove_dir($dir.'/'.$item) && $result;
9910 } else {
9911 $result = unlink($dir.'/'.$item) && $result;
9915 closedir($handle);
9916 if ($contentonly) {
9917 clearstatcache(); // Make sure file stat cache is properly invalidated.
9918 return $result;
9920 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9921 clearstatcache(); // Make sure file stat cache is properly invalidated.
9922 return $result;
9926 * Detect if an object or a class contains a given property
9927 * will take an actual object or the name of a class
9929 * @param mix $obj Name of class or real object to test
9930 * @param string $property name of property to find
9931 * @return bool true if property exists
9933 function object_property_exists( $obj, $property ) {
9934 if (is_string( $obj )) {
9935 $properties = get_class_vars( $obj );
9936 } else {
9937 $properties = get_object_vars( $obj );
9939 return array_key_exists( $property, $properties );
9943 * Converts an object into an associative array
9945 * This function converts an object into an associative array by iterating
9946 * over its public properties. Because this function uses the foreach
9947 * construct, Iterators are respected. It works recursively on arrays of objects.
9948 * Arrays and simple values are returned as is.
9950 * If class has magic properties, it can implement IteratorAggregate
9951 * and return all available properties in getIterator()
9953 * @param mixed $var
9954 * @return array
9956 function convert_to_array($var) {
9957 $result = array();
9959 // Loop over elements/properties.
9960 foreach ($var as $key => $value) {
9961 // Recursively convert objects.
9962 if (is_object($value) || is_array($value)) {
9963 $result[$key] = convert_to_array($value);
9964 } else {
9965 // Simple values are untouched.
9966 $result[$key] = $value;
9969 return $result;
9973 * Detect a custom script replacement in the data directory that will
9974 * replace an existing moodle script
9976 * @return string|bool full path name if a custom script exists, false if no custom script exists
9978 function custom_script_path() {
9979 global $CFG, $SCRIPT;
9981 if ($SCRIPT === null) {
9982 // Probably some weird external script.
9983 return false;
9986 $scriptpath = $CFG->customscripts . $SCRIPT;
9988 // Check the custom script exists.
9989 if (file_exists($scriptpath) and is_file($scriptpath)) {
9990 return $scriptpath;
9991 } else {
9992 return false;
9997 * Returns whether or not the user object is a remote MNET user. This function
9998 * is in moodlelib because it does not rely on loading any of the MNET code.
10000 * @param object $user A valid user object
10001 * @return bool True if the user is from a remote Moodle.
10003 function is_mnet_remote_user($user) {
10004 global $CFG;
10006 if (!isset($CFG->mnet_localhost_id)) {
10007 include_once($CFG->dirroot . '/mnet/lib.php');
10008 $env = new mnet_environment();
10009 $env->init();
10010 unset($env);
10013 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
10017 * This function will search for browser prefereed languages, setting Moodle
10018 * to use the best one available if $SESSION->lang is undefined
10020 function setup_lang_from_browser() {
10021 global $CFG, $SESSION, $USER;
10023 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
10024 // Lang is defined in session or user profile, nothing to do.
10025 return;
10028 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
10029 return;
10032 // Extract and clean langs from headers.
10033 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
10034 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
10035 $rawlangs = explode(',', $rawlangs); // Convert to array.
10036 $langs = array();
10038 $order = 1.0;
10039 foreach ($rawlangs as $lang) {
10040 if (strpos($lang, ';') === false) {
10041 $langs[(string)$order] = $lang;
10042 $order = $order-0.01;
10043 } else {
10044 $parts = explode(';', $lang);
10045 $pos = strpos($parts[1], '=');
10046 $langs[substr($parts[1], $pos+1)] = $parts[0];
10049 krsort($langs, SORT_NUMERIC);
10051 // Look for such langs under standard locations.
10052 foreach ($langs as $lang) {
10053 // Clean it properly for include.
10054 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
10055 if (get_string_manager()->translation_exists($lang, false)) {
10056 // Lang exists, set it in session.
10057 $SESSION->lang = $lang;
10058 // We have finished. Go out.
10059 break;
10062 return;
10066 * Check if $url matches anything in proxybypass list
10068 * Any errors just result in the proxy being used (least bad)
10070 * @param string $url url to check
10071 * @return boolean true if we should bypass the proxy
10073 function is_proxybypass( $url ) {
10074 global $CFG;
10076 // Sanity check.
10077 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
10078 return false;
10081 // Get the host part out of the url.
10082 if (!$host = parse_url( $url, PHP_URL_HOST )) {
10083 return false;
10086 // Get the possible bypass hosts into an array.
10087 $matches = explode( ',', $CFG->proxybypass );
10089 // Check for a match.
10090 // (IPs need to match the left hand side and hosts the right of the url,
10091 // but we can recklessly check both as there can't be a false +ve).
10092 foreach ($matches as $match) {
10093 $match = trim($match);
10095 // Try for IP match (Left side).
10096 $lhs = substr($host, 0, strlen($match));
10097 if (strcasecmp($match, $lhs)==0) {
10098 return true;
10101 // Try for host match (Right side).
10102 $rhs = substr($host, -strlen($match));
10103 if (strcasecmp($match, $rhs)==0) {
10104 return true;
10108 // Nothing matched.
10109 return false;
10113 * Check if the passed navigation is of the new style
10115 * @param mixed $navigation
10116 * @return bool true for yes false for no
10118 function is_newnav($navigation) {
10119 if (is_array($navigation) && !empty($navigation['newnav'])) {
10120 return true;
10121 } else {
10122 return false;
10127 * Checks whether the given variable name is defined as a variable within the given object.
10129 * This will NOT work with stdClass objects, which have no class variables.
10131 * @param string $var The variable name
10132 * @param object $object The object to check
10133 * @return boolean
10135 function in_object_vars($var, $object) {
10136 $classvars = get_class_vars(get_class($object));
10137 $classvars = array_keys($classvars);
10138 return in_array($var, $classvars);
10142 * Returns an array without repeated objects.
10143 * This function is similar to array_unique, but for arrays that have objects as values
10145 * @param array $array
10146 * @param bool $keepkeyassoc
10147 * @return array
10149 function object_array_unique($array, $keepkeyassoc = true) {
10150 $duplicatekeys = array();
10151 $tmp = array();
10153 foreach ($array as $key => $val) {
10154 // Convert objects to arrays, in_array() does not support objects.
10155 if (is_object($val)) {
10156 $val = (array)$val;
10159 if (!in_array($val, $tmp)) {
10160 $tmp[] = $val;
10161 } else {
10162 $duplicatekeys[] = $key;
10166 foreach ($duplicatekeys as $key) {
10167 unset($array[$key]);
10170 return $keepkeyassoc ? $array : array_values($array);
10174 * Is a userid the primary administrator?
10176 * @param int $userid int id of user to check
10177 * @return boolean
10179 function is_primary_admin($userid) {
10180 $primaryadmin = get_admin();
10182 if ($userid == $primaryadmin->id) {
10183 return true;
10184 } else {
10185 return false;
10190 * Returns the site identifier
10192 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
10194 function get_site_identifier() {
10195 global $CFG;
10196 // Check to see if it is missing. If so, initialise it.
10197 if (empty($CFG->siteidentifier)) {
10198 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
10200 // Return it.
10201 return $CFG->siteidentifier;
10205 * Check whether the given password has no more than the specified
10206 * number of consecutive identical characters.
10208 * @param string $password password to be checked against the password policy
10209 * @param integer $maxchars maximum number of consecutive identical characters
10210 * @return bool
10212 function check_consecutive_identical_characters($password, $maxchars) {
10214 if ($maxchars < 1) {
10215 return true; // Zero 0 is to disable this check.
10217 if (strlen($password) <= $maxchars) {
10218 return true; // Too short to fail this test.
10221 $previouschar = '';
10222 $consecutivecount = 1;
10223 foreach (str_split($password) as $char) {
10224 if ($char != $previouschar) {
10225 $consecutivecount = 1;
10226 } else {
10227 $consecutivecount++;
10228 if ($consecutivecount > $maxchars) {
10229 return false; // Check failed already.
10233 $previouschar = $char;
10236 return true;
10240 * Helper function to do partial function binding.
10241 * so we can use it for preg_replace_callback, for example
10242 * this works with php functions, user functions, static methods and class methods
10243 * it returns you a callback that you can pass on like so:
10245 * $callback = partial('somefunction', $arg1, $arg2);
10246 * or
10247 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
10248 * or even
10249 * $obj = new someclass();
10250 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
10252 * and then the arguments that are passed through at calltime are appended to the argument list.
10254 * @param mixed $function a php callback
10255 * @param mixed $arg1,... $argv arguments to partially bind with
10256 * @return array Array callback
10258 function partial() {
10259 if (!class_exists('partial')) {
10261 * Used to manage function binding.
10262 * @copyright 2009 Penny Leach
10263 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10265 class partial{
10266 /** @var array */
10267 public $values = array();
10268 /** @var string The function to call as a callback. */
10269 public $func;
10271 * Constructor
10272 * @param string $func
10273 * @param array $args
10275 public function __construct($func, $args) {
10276 $this->values = $args;
10277 $this->func = $func;
10280 * Calls the callback function.
10281 * @return mixed
10283 public function method() {
10284 $args = func_get_args();
10285 return call_user_func_array($this->func, array_merge($this->values, $args));
10289 $args = func_get_args();
10290 $func = array_shift($args);
10291 $p = new partial($func, $args);
10292 return array($p, 'method');
10296 * helper function to load up and initialise the mnet environment
10297 * this must be called before you use mnet functions.
10299 * @return mnet_environment the equivalent of old $MNET global
10301 function get_mnet_environment() {
10302 global $CFG;
10303 require_once($CFG->dirroot . '/mnet/lib.php');
10304 static $instance = null;
10305 if (empty($instance)) {
10306 $instance = new mnet_environment();
10307 $instance->init();
10309 return $instance;
10313 * during xmlrpc server code execution, any code wishing to access
10314 * information about the remote peer must use this to get it.
10316 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
10318 function get_mnet_remote_client() {
10319 if (!defined('MNET_SERVER')) {
10320 debugging(get_string('notinxmlrpcserver', 'mnet'));
10321 return false;
10323 global $MNET_REMOTE_CLIENT;
10324 if (isset($MNET_REMOTE_CLIENT)) {
10325 return $MNET_REMOTE_CLIENT;
10327 return false;
10331 * during the xmlrpc server code execution, this will be called
10332 * to setup the object returned by {@link get_mnet_remote_client}
10334 * @param mnet_remote_client $client the client to set up
10335 * @throws moodle_exception
10337 function set_mnet_remote_client($client) {
10338 if (!defined('MNET_SERVER')) {
10339 throw new moodle_exception('notinxmlrpcserver', 'mnet');
10341 global $MNET_REMOTE_CLIENT;
10342 $MNET_REMOTE_CLIENT = $client;
10346 * return the jump url for a given remote user
10347 * this is used for rewriting forum post links in emails, etc
10349 * @param stdclass $user the user to get the idp url for
10351 function mnet_get_idp_jump_url($user) {
10352 global $CFG;
10354 static $mnetjumps = array();
10355 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
10356 $idp = mnet_get_peer_host($user->mnethostid);
10357 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
10358 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
10360 return $mnetjumps[$user->mnethostid];
10364 * Gets the homepage to use for the current user
10366 * @return int One of HOMEPAGE_*
10368 function get_home_page() {
10369 global $CFG;
10371 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
10372 // If dashboard is disabled, home will be set to default page.
10373 $defaultpage = get_default_home_page();
10374 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
10375 if (!empty($CFG->enabledashboard)) {
10376 return HOMEPAGE_MY;
10377 } else {
10378 return $defaultpage;
10380 } else if ($CFG->defaulthomepage == HOMEPAGE_MYCOURSES) {
10381 return HOMEPAGE_MYCOURSES;
10382 } else {
10383 $userhomepage = (int) get_user_preferences('user_home_page_preference', $defaultpage);
10384 if (empty($CFG->enabledashboard) && $userhomepage == HOMEPAGE_MY) {
10385 // If the user was using the dashboard but it's disabled, return the default home page.
10386 $userhomepage = $defaultpage;
10388 return $userhomepage;
10391 return HOMEPAGE_SITE;
10395 * Returns the default home page to display if current one is not defined or can't be applied.
10396 * The default behaviour is to return Dashboard if it's enabled or My courses page if it isn't.
10398 * @return int The default home page.
10400 function get_default_home_page(): int {
10401 global $CFG;
10403 return !empty($CFG->enabledashboard) ? HOMEPAGE_MY : HOMEPAGE_MYCOURSES;
10407 * Gets the name of a course to be displayed when showing a list of courses.
10408 * By default this is just $course->fullname but user can configure it. The
10409 * result of this function should be passed through print_string.
10410 * @param stdClass|core_course_list_element $course Moodle course object
10411 * @return string Display name of course (either fullname or short + fullname)
10413 function get_course_display_name_for_list($course) {
10414 global $CFG;
10415 if (!empty($CFG->courselistshortnames)) {
10416 if (!($course instanceof stdClass)) {
10417 $course = (object)convert_to_array($course);
10419 return get_string('courseextendednamedisplay', '', $course);
10420 } else {
10421 return $course->fullname;
10426 * Safe analogue of unserialize() that can only parse arrays
10428 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
10429 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
10430 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
10432 * @param string $expression
10433 * @return array|bool either parsed array or false if parsing was impossible.
10435 function unserialize_array($expression) {
10436 $subs = [];
10437 // Find nested arrays, parse them and store in $subs , substitute with special string.
10438 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
10439 $key = '--SUB' . count($subs) . '--';
10440 $subs[$key] = unserialize_array($matches[2]);
10441 if ($subs[$key] === false) {
10442 return false;
10444 $expression = str_replace($matches[2], $key . ';', $expression);
10447 // Check the expression is an array.
10448 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
10449 return false;
10451 // Get the size and elements of an array (key;value;key;value;....).
10452 $parts = explode(';', $matches1[2]);
10453 $size = intval($matches1[1]);
10454 if (count($parts) < $size * 2 + 1) {
10455 return false;
10457 // Analyze each part and make sure it is an integer or string or a substitute.
10458 $value = [];
10459 for ($i = 0; $i < $size * 2; $i++) {
10460 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
10461 $parts[$i] = (int)$matches2[1];
10462 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
10463 $parts[$i] = $matches3[2];
10464 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
10465 $parts[$i] = $subs[$parts[$i]];
10466 } else {
10467 return false;
10470 // Combine keys and values.
10471 for ($i = 0; $i < $size * 2; $i += 2) {
10472 $value[$parts[$i]] = $parts[$i+1];
10474 return $value;
10478 * Safe method for unserializing given input that is expected to contain only a serialized instance of an stdClass object
10480 * If any class type other than stdClass is included in the input string, it will not be instantiated and will be cast to an
10481 * stdClass object. The initial cast to array, then back to object is to ensure we are always returning the correct type,
10482 * otherwise we would return an instances of {@see __PHP_Incomplete_class} for malformed strings
10484 * @param string $input
10485 * @return stdClass
10487 function unserialize_object(string $input): stdClass {
10488 $instance = (array) unserialize($input, ['allowed_classes' => [stdClass::class]]);
10489 return (object) $instance;
10493 * The lang_string class
10495 * This special class is used to create an object representation of a string request.
10496 * It is special because processing doesn't occur until the object is first used.
10497 * The class was created especially to aid performance in areas where strings were
10498 * required to be generated but were not necessarily used.
10499 * As an example the admin tree when generated uses over 1500 strings, of which
10500 * normally only 1/3 are ever actually printed at any time.
10501 * The performance advantage is achieved by not actually processing strings that
10502 * arn't being used, as such reducing the processing required for the page.
10504 * How to use the lang_string class?
10505 * There are two methods of using the lang_string class, first through the
10506 * forth argument of the get_string function, and secondly directly.
10507 * The following are examples of both.
10508 * 1. Through get_string calls e.g.
10509 * $string = get_string($identifier, $component, $a, true);
10510 * $string = get_string('yes', 'moodle', null, true);
10511 * 2. Direct instantiation
10512 * $string = new lang_string($identifier, $component, $a, $lang);
10513 * $string = new lang_string('yes');
10515 * How do I use a lang_string object?
10516 * The lang_string object makes use of a magic __toString method so that you
10517 * are able to use the object exactly as you would use a string in most cases.
10518 * This means you are able to collect it into a variable and then directly
10519 * echo it, or concatenate it into another string, or similar.
10520 * The other thing you can do is manually get the string by calling the
10521 * lang_strings out method e.g.
10522 * $string = new lang_string('yes');
10523 * $string->out();
10524 * Also worth noting is that the out method can take one argument, $lang which
10525 * allows the developer to change the language on the fly.
10527 * When should I use a lang_string object?
10528 * The lang_string object is designed to be used in any situation where a
10529 * string may not be needed, but needs to be generated.
10530 * The admin tree is a good example of where lang_string objects should be
10531 * used.
10532 * A more practical example would be any class that requries strings that may
10533 * not be printed (after all classes get renderer by renderers and who knows
10534 * what they will do ;))
10536 * When should I not use a lang_string object?
10537 * Don't use lang_strings when you are going to use a string immediately.
10538 * There is no need as it will be processed immediately and there will be no
10539 * advantage, and in fact perhaps a negative hit as a class has to be
10540 * instantiated for a lang_string object, however get_string won't require
10541 * that.
10543 * Limitations:
10544 * 1. You cannot use a lang_string object as an array offset. Doing so will
10545 * result in PHP throwing an error. (You can use it as an object property!)
10547 * @package core
10548 * @category string
10549 * @copyright 2011 Sam Hemelryk
10550 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10552 class lang_string {
10554 /** @var string The strings identifier */
10555 protected $identifier;
10556 /** @var string The strings component. Default '' */
10557 protected $component = '';
10558 /** @var array|stdClass Any arguments required for the string. Default null */
10559 protected $a = null;
10560 /** @var string The language to use when processing the string. Default null */
10561 protected $lang = null;
10563 /** @var string The processed string (once processed) */
10564 protected $string = null;
10567 * A special boolean. If set to true then the object has been woken up and
10568 * cannot be regenerated. If this is set then $this->string MUST be used.
10569 * @var bool
10571 protected $forcedstring = false;
10574 * Constructs a lang_string object
10576 * This function should do as little processing as possible to ensure the best
10577 * performance for strings that won't be used.
10579 * @param string $identifier The strings identifier
10580 * @param string $component The strings component
10581 * @param stdClass|array $a Any arguments the string requires
10582 * @param string $lang The language to use when processing the string.
10583 * @throws coding_exception
10585 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10586 if (empty($component)) {
10587 $component = 'moodle';
10590 $this->identifier = $identifier;
10591 $this->component = $component;
10592 $this->lang = $lang;
10594 // We MUST duplicate $a to ensure that it if it changes by reference those
10595 // changes are not carried across.
10596 // To do this we always ensure $a or its properties/values are strings
10597 // and that any properties/values that arn't convertable are forgotten.
10598 if ($a !== null) {
10599 if (is_scalar($a)) {
10600 $this->a = $a;
10601 } else if ($a instanceof lang_string) {
10602 $this->a = $a->out();
10603 } else if (is_object($a) or is_array($a)) {
10604 $a = (array)$a;
10605 $this->a = array();
10606 foreach ($a as $key => $value) {
10607 // Make sure conversion errors don't get displayed (results in '').
10608 if (is_array($value)) {
10609 $this->a[$key] = '';
10610 } else if (is_object($value)) {
10611 if (method_exists($value, '__toString')) {
10612 $this->a[$key] = $value->__toString();
10613 } else {
10614 $this->a[$key] = '';
10616 } else {
10617 $this->a[$key] = (string)$value;
10623 if (debugging(false, DEBUG_DEVELOPER)) {
10624 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10625 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10627 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10628 throw new coding_exception('Invalid string compontent. Please check your string definition');
10630 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10631 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10637 * Processes the string.
10639 * This function actually processes the string, stores it in the string property
10640 * and then returns it.
10641 * You will notice that this function is VERY similar to the get_string method.
10642 * That is because it is pretty much doing the same thing.
10643 * However as this function is an upgrade it isn't as tolerant to backwards
10644 * compatibility.
10646 * @return string
10647 * @throws coding_exception
10649 protected function get_string() {
10650 global $CFG;
10652 // Check if we need to process the string.
10653 if ($this->string === null) {
10654 // Check the quality of the identifier.
10655 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10656 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);
10659 // Process the string.
10660 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10661 // Debugging feature lets you display string identifier and component.
10662 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10663 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10666 // Return the string.
10667 return $this->string;
10671 * Returns the string
10673 * @param string $lang The langauge to use when processing the string
10674 * @return string
10676 public function out($lang = null) {
10677 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10678 if ($this->forcedstring) {
10679 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10680 return $this->get_string();
10682 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10683 return $translatedstring->out();
10685 return $this->get_string();
10689 * Magic __toString method for printing a string
10691 * @return string
10693 public function __toString() {
10694 return $this->get_string();
10698 * Magic __set_state method used for var_export
10700 * @param array $array
10701 * @return self
10703 public static function __set_state(array $array): self {
10704 $tmp = new lang_string($array['identifier'], $array['component'], $array['a'], $array['lang']);
10705 $tmp->string = $array['string'];
10706 $tmp->forcedstring = $array['forcedstring'];
10707 return $tmp;
10711 * Prepares the lang_string for sleep and stores only the forcedstring and
10712 * string properties... the string cannot be regenerated so we need to ensure
10713 * it is generated for this.
10715 * @return string
10717 public function __sleep() {
10718 $this->get_string();
10719 $this->forcedstring = true;
10720 return array('forcedstring', 'string', 'lang');
10724 * Returns the identifier.
10726 * @return string
10728 public function get_identifier() {
10729 return $this->identifier;
10733 * Returns the component.
10735 * @return string
10737 public function get_component() {
10738 return $this->component;
10743 * Get human readable name describing the given callable.
10745 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10746 * It does not check if the callable actually exists.
10748 * @param callable|string|array $callable
10749 * @return string|bool Human readable name of callable, or false if not a valid callable.
10751 function get_callable_name($callable) {
10753 if (!is_callable($callable, true, $name)) {
10754 return false;
10756 } else {
10757 return $name;
10762 * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10763 * Never put your faith on this function and rely on its accuracy as there might be false positives.
10764 * It just performs some simple checks, and mainly is used for places where we want to hide some options
10765 * such as site registration when $CFG->wwwroot is not publicly accessible.
10766 * Good thing is there is no false negative.
10767 * Note that it's possible to force the result of this check by specifying $CFG->site_is_public in config.php
10769 * @return bool
10771 function site_is_public() {
10772 global $CFG;
10774 // Return early if site admin has forced this setting.
10775 if (isset($CFG->site_is_public)) {
10776 return (bool)$CFG->site_is_public;
10779 $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
10781 if ($host === 'localhost' || preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10782 $ispublic = false;
10783 } else if (\core\ip_utils::is_ip_address($host) && !ip_is_public($host)) {
10784 $ispublic = false;
10785 } else if (($address = \core\ip_utils::get_ip_address($host)) && !ip_is_public($address)) {
10786 $ispublic = false;
10787 } else {
10788 $ispublic = true;
10791 return $ispublic;