2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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
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.
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
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.
75 * PARAM_ALPHA - contains only English ascii letters [a-zA-Z].
77 define('PARAM_ALPHA', 'alpha');
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');
86 * PARAM_ALPHANUM - expected numbers 0-9 and English ascii letters [a-zA-Z] only.
88 define('PARAM_ALPHANUM', 'alphanum');
91 * PARAM_ALPHANUMEXT - expected numbers 0-9, letters (English ascii letters [a-zA-Z]) and _- only.
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
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, etc.
211 define('PARAM_SAFEPATH', 'safepath');
214 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
216 define('PARAM_SEQUENCE', 'sequence');
219 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
221 define('PARAM_TAG', 'tag');
224 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
226 define('PARAM_TAGLIST', 'taglist');
229 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
231 define('PARAM_TEXT', 'text');
234 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
236 define('PARAM_THEME', 'theme');
239 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
240 * http://localhost.localdomain/ is ok.
242 define('PARAM_URL', 'url');
245 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
246 * accounts, do NOT use when syncing with external systems!!
248 define('PARAM_USERNAME', 'username');
251 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
253 define('PARAM_STRINGID', 'stringid');
255 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
257 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
258 * It was one of the first types, that is why it is abused so much ;-)
259 * @deprecated since 2.0
261 define('PARAM_CLEAN', 'clean');
264 * PARAM_INTEGER - deprecated alias for PARAM_INT
265 * @deprecated since 2.0
267 define('PARAM_INTEGER', 'int');
270 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
271 * @deprecated since 2.0
273 define('PARAM_NUMBER', 'float');
276 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
277 * NOTE: originally alias for PARAM_APLHA
278 * @deprecated since 2.0
280 define('PARAM_ACTION', 'alphanumext');
283 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
284 * NOTE: originally alias for PARAM_APLHA
285 * @deprecated since 2.0
287 define('PARAM_FORMAT', 'alphanumext');
290 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
291 * @deprecated since 2.0
293 define('PARAM_MULTILANG', 'text');
296 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
297 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
298 * America/Port-au-Prince)
300 define('PARAM_TIMEZONE', 'timezone');
303 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
305 define('PARAM_CLEANFILE', 'file');
308 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
309 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
310 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
311 * NOTE: numbers and underscores are strongly discouraged in plugin names!
313 define('PARAM_COMPONENT', 'component');
316 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
317 * It is usually used together with context id and component.
318 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
320 define('PARAM_AREA', 'area');
323 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
324 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
325 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
327 define('PARAM_PLUGIN', 'plugin');
333 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
335 define('VALUE_REQUIRED', 1);
338 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
340 define('VALUE_OPTIONAL', 2);
343 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
345 define('VALUE_DEFAULT', 0);
348 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
350 define('NULL_NOT_ALLOWED', false);
353 * NULL_ALLOWED - the parameter can be set to null in the database
355 define('NULL_ALLOWED', true);
360 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
362 define('PAGE_COURSE_VIEW', 'course-view');
364 /** Get remote addr constant */
365 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
366 /** Get remote addr constant */
367 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
369 * GETREMOTEADDR_SKIP_DEFAULT defines the default behavior remote IP address validation.
371 define('GETREMOTEADDR_SKIP_DEFAULT', GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR|GETREMOTEADDR_SKIP_HTTP_CLIENT_IP
);
373 // Blog access level constant declaration.
374 define ('BLOG_USER_LEVEL', 1);
375 define ('BLOG_GROUP_LEVEL', 2);
376 define ('BLOG_COURSE_LEVEL', 3);
377 define ('BLOG_SITE_LEVEL', 4);
378 define ('BLOG_GLOBAL_LEVEL', 5);
383 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
384 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
385 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
387 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
389 define('TAG_MAX_LENGTH', 50);
391 // Password policy constants.
392 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
393 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
394 define ('PASSWORD_DIGITS', '0123456789');
395 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
397 // Feature constants.
398 // Used for plugin_supports() to report features that are, or are not, supported by a module.
400 /** True if module can provide a grade */
401 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
402 /** True if module supports outcomes */
403 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
404 /** True if module supports advanced grading methods */
405 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
406 /** True if module controls the grade visibility over the gradebook */
407 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
408 /** True if module supports plagiarism plugins */
409 define('FEATURE_PLAGIARISM', 'plagiarism');
411 /** True if module has code to track whether somebody viewed it */
412 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
413 /** True if module has custom completion rules */
414 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
416 /** True if module has no 'view' page (like label) */
417 define('FEATURE_NO_VIEW_LINK', 'viewlink');
418 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
419 define('FEATURE_IDNUMBER', 'idnumber');
420 /** True if module supports groups */
421 define('FEATURE_GROUPS', 'groups');
422 /** True if module supports groupings */
423 define('FEATURE_GROUPINGS', 'groupings');
425 * True if module supports groupmembersonly (which no longer exists)
426 * @deprecated Since Moodle 2.8
428 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
430 /** Type of module */
431 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
432 /** True if module supports intro editor */
433 define('FEATURE_MOD_INTRO', 'mod_intro');
434 /** True if module has default completion */
435 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
437 define('FEATURE_COMMENT', 'comment');
439 define('FEATURE_RATE', 'rate');
440 /** True if module supports backup/restore of moodle2 format */
441 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
443 /** True if module can show description on course main page */
444 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
446 /** True if module uses the question bank */
447 define('FEATURE_USES_QUESTIONS', 'usesquestions');
450 * Maximum filename char size
452 define('MAX_FILENAME_SIZE', 100);
454 /** Unspecified module archetype */
455 define('MOD_ARCHETYPE_OTHER', 0);
456 /** Resource-like type module */
457 define('MOD_ARCHETYPE_RESOURCE', 1);
458 /** Assignment module archetype */
459 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
460 /** System (not user-addable) module archetype */
461 define('MOD_ARCHETYPE_SYSTEM', 3);
464 * Security token used for allowing access
465 * from external application such as web services.
466 * Scripts do not use any session, performance is relatively
467 * low because we need to load access info in each request.
468 * Scripts are executed in parallel.
470 define('EXTERNAL_TOKEN_PERMANENT', 0);
473 * Security token used for allowing access
474 * of embedded applications, the code is executed in the
475 * active user session. Token is invalidated after user logs out.
476 * Scripts are executed serially - normal session locking is used.
478 define('EXTERNAL_TOKEN_EMBEDDED', 1);
481 * The home page should be the site home
483 define('HOMEPAGE_SITE', 0);
485 * The home page should be the users my page
487 define('HOMEPAGE_MY', 1);
489 * The home page can be chosen by the user
491 define('HOMEPAGE_USER', 2);
494 * URL of the Moodle sites registration portal.
496 defined('HUB_MOODLEORGHUBURL') ||
define('HUB_MOODLEORGHUBURL', 'https://stats.moodle.org');
499 * Moodle mobile app service name
501 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
504 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
506 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
509 * Course display settings: display all sections on one page.
511 define('COURSE_DISPLAY_SINGLEPAGE', 0);
513 * Course display settings: split pages into a page per section.
515 define('COURSE_DISPLAY_MULTIPAGE', 1);
518 * Authentication constant: String used in password field when password is not stored.
520 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
523 * Email from header to never include via information.
525 define('EMAIL_VIA_NEVER', 0);
528 * Email from header to always include via information.
530 define('EMAIL_VIA_ALWAYS', 1);
533 * Email from header to only include via information if the address is no-reply.
535 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
537 // PARAMETER HANDLING.
540 * Returns a particular value for the named variable, taken from
541 * POST or GET. If the parameter doesn't exist then an error is
542 * thrown because we require this variable.
544 * This function should be used to initialise all required values
545 * in a script that are based on parameters. Usually it will be
547 * $id = required_param('id', PARAM_INT);
549 * Please note the $type parameter is now required and the value can not be array.
551 * @param string $parname the name of the page parameter we want
552 * @param string $type expected type of parameter
554 * @throws coding_exception
556 function required_param($parname, $type) {
557 if (func_num_args() != 2 or empty($parname) or empty($type)) {
558 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
560 // POST has precedence.
561 if (isset($_POST[$parname])) {
562 $param = $_POST[$parname];
563 } else if (isset($_GET[$parname])) {
564 $param = $_GET[$parname];
566 print_error('missingparam', '', '', $parname);
569 if (is_array($param)) {
570 debugging('Invalid array parameter detected in required_param(): '.$parname);
571 // TODO: switch to fatal error in Moodle 2.3.
572 return required_param_array($parname, $type);
575 return clean_param($param, $type);
579 * Returns a particular array value for the named variable, taken from
580 * POST or GET. If the parameter doesn't exist then an error is
581 * thrown because we require this variable.
583 * This function should be used to initialise all required values
584 * in a script that are based on parameters. Usually it will be
586 * $ids = required_param_array('ids', PARAM_INT);
588 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
590 * @param string $parname the name of the page parameter we want
591 * @param string $type expected type of parameter
593 * @throws coding_exception
595 function required_param_array($parname, $type) {
596 if (func_num_args() != 2 or empty($parname) or empty($type)) {
597 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
599 // POST has precedence.
600 if (isset($_POST[$parname])) {
601 $param = $_POST[$parname];
602 } else if (isset($_GET[$parname])) {
603 $param = $_GET[$parname];
605 print_error('missingparam', '', '', $parname);
607 if (!is_array($param)) {
608 print_error('missingparam', '', '', $parname);
612 foreach ($param as $key => $value) {
613 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
614 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
617 $result[$key] = clean_param($value, $type);
624 * Returns a particular value for the named variable, taken from
625 * POST or GET, otherwise returning a given default.
627 * This function should be used to initialise all optional values
628 * in a script that are based on parameters. Usually it will be
630 * $name = optional_param('name', 'Fred', PARAM_TEXT);
632 * Please note the $type parameter is now required and the value can not be array.
634 * @param string $parname the name of the page parameter we want
635 * @param mixed $default the default value to return if nothing is found
636 * @param string $type expected type of parameter
638 * @throws coding_exception
640 function optional_param($parname, $default, $type) {
641 if (func_num_args() != 3 or empty($parname) or empty($type)) {
642 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
645 // POST has precedence.
646 if (isset($_POST[$parname])) {
647 $param = $_POST[$parname];
648 } else if (isset($_GET[$parname])) {
649 $param = $_GET[$parname];
654 if (is_array($param)) {
655 debugging('Invalid array parameter detected in required_param(): '.$parname);
656 // TODO: switch to $default in Moodle 2.3.
657 return optional_param_array($parname, $default, $type);
660 return clean_param($param, $type);
664 * Returns a particular array value for the named variable, taken from
665 * POST or GET, otherwise returning a given default.
667 * This function should be used to initialise all optional values
668 * in a script that are based on parameters. Usually it will be
670 * $ids = optional_param('id', array(), PARAM_INT);
672 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
674 * @param string $parname the name of the page parameter we want
675 * @param mixed $default the default value to return if nothing is found
676 * @param string $type expected type of parameter
678 * @throws coding_exception
680 function optional_param_array($parname, $default, $type) {
681 if (func_num_args() != 3 or empty($parname) or empty($type)) {
682 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
685 // POST has precedence.
686 if (isset($_POST[$parname])) {
687 $param = $_POST[$parname];
688 } else if (isset($_GET[$parname])) {
689 $param = $_GET[$parname];
693 if (!is_array($param)) {
694 debugging('optional_param_array() expects array parameters only: '.$parname);
699 foreach ($param as $key => $value) {
700 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
701 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
704 $result[$key] = clean_param($value, $type);
711 * Strict validation of parameter values, the values are only converted
712 * to requested PHP type. Internally it is using clean_param, the values
713 * before and after cleaning must be equal - otherwise
714 * an invalid_parameter_exception is thrown.
715 * Objects and classes are not accepted.
717 * @param mixed $param
718 * @param string $type PARAM_ constant
719 * @param bool $allownull are nulls valid value?
720 * @param string $debuginfo optional debug information
721 * @return mixed the $param value converted to PHP type
722 * @throws invalid_parameter_exception if $param is not of given type
724 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED
, $debuginfo='') {
725 if (is_null($param)) {
726 if ($allownull == NULL_ALLOWED
) {
729 throw new invalid_parameter_exception($debuginfo);
732 if (is_array($param) or is_object($param)) {
733 throw new invalid_parameter_exception($debuginfo);
736 $cleaned = clean_param($param, $type);
738 if ($type == PARAM_FLOAT
) {
739 // Do not detect precision loss here.
740 if (is_float($param) or is_int($param)) {
742 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
743 throw new invalid_parameter_exception($debuginfo);
745 } else if ((string)$param !== (string)$cleaned) {
746 // Conversion to string is usually lossless.
747 throw new invalid_parameter_exception($debuginfo);
754 * Makes sure array contains only the allowed types, this function does not validate array key names!
757 * $options = clean_param($options, PARAM_INT);
760 * @param array $param the variable array we are cleaning
761 * @param string $type expected format of param after cleaning.
762 * @param bool $recursive clean recursive arrays
764 * @throws coding_exception
766 function clean_param_array(array $param = null, $type, $recursive = false) {
767 // Convert null to empty array.
768 $param = (array)$param;
769 foreach ($param as $key => $value) {
770 if (is_array($value)) {
772 $param[$key] = clean_param_array($value, $type, true);
774 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
777 $param[$key] = clean_param($value, $type);
784 * Used by {@link optional_param()} and {@link required_param()} to
785 * clean the variables and/or cast to specific types, based on
788 * $course->format = clean_param($course->format, PARAM_ALPHA);
789 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
792 * @param mixed $param the variable we are cleaning
793 * @param string $type expected format of param after cleaning.
795 * @throws coding_exception
797 function clean_param($param, $type) {
800 if (is_array($param)) {
801 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
802 } else if (is_object($param)) {
803 if (method_exists($param, '__toString')) {
804 $param = $param->__toString();
806 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
812 // No cleaning at all.
813 $param = fix_utf8($param);
816 case PARAM_RAW_TRIMMED
:
817 // No cleaning, but strip leading and trailing whitespace.
818 $param = fix_utf8($param);
822 // General HTML cleaning, try to use more specific type if possible this is deprecated!
823 // Please use more specific type instead.
824 if (is_numeric($param)) {
827 $param = fix_utf8($param);
828 // Sweep for scripts, etc.
829 return clean_text($param);
831 case PARAM_CLEANHTML
:
832 // Clean html fragment.
833 $param = fix_utf8($param);
834 // Sweep for scripts, etc.
835 $param = clean_text($param, FORMAT_HTML
);
839 // Convert to integer.
844 return (float)$param;
846 case PARAM_LOCALISEDFLOAT
:
848 return unformat_float($param, true);
851 // Remove everything not `a-z`.
852 return preg_replace('/[^a-zA-Z]/i', '', $param);
855 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
856 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
859 // Remove everything not `a-zA-Z0-9`.
860 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
862 case PARAM_ALPHANUMEXT
:
863 // Remove everything not `a-zA-Z0-9_-`.
864 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
867 // Remove everything not `0-9,`.
868 return preg_replace('/[^0-9,]/i', '', $param);
871 // Convert to 1 or 0.
872 $tempstr = strtolower($param);
873 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
875 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
878 $param = empty($param) ?
0 : 1;
884 $param = fix_utf8($param);
885 return strip_tags($param);
888 // Leave only tags needed for multilang.
889 $param = fix_utf8($param);
890 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
891 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
893 if (strpos($param, '</lang>') !== false) {
894 // Old and future mutilang syntax.
895 $param = strip_tags($param, '<lang>');
896 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
900 foreach ($matches[0] as $match) {
901 if ($match === '</lang>') {
909 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
920 } else if (strpos($param, '</span>') !== false) {
921 // Current problematic multilang syntax.
922 $param = strip_tags($param, '<span>');
923 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
927 foreach ($matches[0] as $match) {
928 if ($match === '</span>') {
936 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
948 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
949 return strip_tags($param);
951 case PARAM_COMPONENT
:
952 // We do not want any guessing here, either the name is correct or not
953 // please note only normalised component names are accepted.
954 if (!preg_match('/^[a-z][a-z0-9]*(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
957 if (strpos($param, '__') !== false) {
960 if (strpos($param, 'mod_') === 0) {
961 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
962 if (substr_count($param, '_') != 1) {
970 // We do not want any guessing here, either the name is correct or not.
971 if (!is_valid_plugin_name($param)) {
977 // Remove everything not a-zA-Z0-9_- .
978 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
981 // Remove everything not a-zA-Z0-9/_- .
982 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
985 // Strip all suspicious characters from filename.
986 $param = fix_utf8($param);
987 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
988 if ($param === '.' ||
$param === '..') {
994 // Strip all suspicious characters from file path.
995 $param = fix_utf8($param);
996 $param = str_replace('\\', '/', $param);
998 // Explode the path and clean each element using the PARAM_FILE rules.
999 $breadcrumb = explode('/', $param);
1000 foreach ($breadcrumb as $key => $crumb) {
1001 if ($crumb === '.' && $key === 0) {
1002 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1004 $crumb = clean_param($crumb, PARAM_FILE
);
1006 $breadcrumb[$key] = $crumb;
1008 $param = implode('/', $breadcrumb);
1010 // Remove multiple current path (./././) and multiple slashes (///).
1011 $param = preg_replace('~//+~', '/', $param);
1012 $param = preg_replace('~/(\./)+~', '/', $param);
1016 // Allow FQDN or IPv4 dotted quad.
1017 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1018 // Match ipv4 dotted quad.
1019 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1020 // Confirm values are ok.
1021 if ( $match[0] > 255
1024 ||
$match[4] > 255 ) {
1025 // Hmmm, what kind of dotted quad is this?
1028 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1029 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1030 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1032 // All is ok - $param is respected.
1041 $param = fix_utf8($param);
1042 include_once($CFG->dirroot
. '/lib/validateurlsyntax.php');
1043 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1044 // All is ok, param is respected.
1051 case PARAM_LOCALURL
:
1052 // Allow http absolute, root relative and relative URLs within wwwroot.
1053 $param = clean_param($param, PARAM_URL
);
1054 if (!empty($param)) {
1056 if ($param === $CFG->wwwroot
) {
1058 } else if (preg_match(':^/:', $param)) {
1059 // Root-relative, ok!
1060 } else if (preg_match('/^' . preg_quote($CFG->wwwroot
. '/', '/') . '/i', $param)) {
1061 // Absolute, and matches our wwwroot.
1063 // Relative - let's make sure there are no tricks.
1064 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1074 $param = trim($param);
1075 // PEM formatted strings may contain letters/numbers and the symbols:
1079 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1080 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1081 list($wholething, $body) = $matches;
1082 unset($wholething, $matches);
1083 $b64 = clean_param($body, PARAM_BASE64
);
1085 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1093 if (!empty($param)) {
1094 // PEM formatted strings may contain letters/numbers and the symbols
1098 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1101 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY
);
1102 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1103 // than (or equal to) 64 characters long.
1104 for ($i=0, $j=count($lines); $i < $j; $i++
) {
1106 if (64 < strlen($lines[$i])) {
1112 if (64 != strlen($lines[$i])) {
1116 return implode("\n", $lines);
1122 $param = fix_utf8($param);
1123 // Please note it is not safe to use the tag name directly anywhere,
1124 // it must be processed with s(), urlencode() before embedding anywhere.
1125 // Remove some nasties.
1126 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1127 // Convert many whitespace chars into one.
1128 $param = preg_replace('/\s+/u', ' ', $param);
1129 $param = core_text
::substr(trim($param), 0, TAG_MAX_LENGTH
);
1133 $param = fix_utf8($param);
1134 $tags = explode(',', $param);
1136 foreach ($tags as $tag) {
1137 $res = clean_param($tag, PARAM_TAG
);
1143 return implode(',', $result);
1148 case PARAM_CAPABILITY
:
1149 if (get_capability_info($param)) {
1155 case PARAM_PERMISSION
:
1156 $param = (int)$param;
1157 if (in_array($param, array(CAP_INHERIT
, CAP_ALLOW
, CAP_PREVENT
, CAP_PROHIBIT
))) {
1164 $param = clean_param($param, PARAM_PLUGIN
);
1165 if (empty($param)) {
1167 } else if (exists_auth_plugin($param)) {
1174 $param = clean_param($param, PARAM_SAFEDIR
);
1175 if (get_string_manager()->translation_exists($param)) {
1178 // Specified language is not installed or param malformed.
1183 $param = clean_param($param, PARAM_PLUGIN
);
1184 if (empty($param)) {
1186 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1188 } else if (!empty($CFG->themedir
) and file_exists("$CFG->themedir/$param/config.php")) {
1191 // Specified theme is not installed.
1195 case PARAM_USERNAME
:
1196 $param = fix_utf8($param);
1197 $param = trim($param);
1198 // Convert uppercase to lowercase MDL-16919.
1199 $param = core_text
::strtolower($param);
1200 if (empty($CFG->extendedusernamechars
)) {
1201 $param = str_replace(" " , "", $param);
1202 // Regular expression, eliminate all chars EXCEPT:
1203 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1204 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1209 $param = fix_utf8($param);
1210 if (validate_email($param)) {
1216 case PARAM_STRINGID
:
1217 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1223 case PARAM_TIMEZONE
:
1224 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1225 $param = fix_utf8($param);
1226 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1227 if (preg_match($timezonepattern, $param)) {
1234 // Doh! throw error, switched parameters in optional_param or another serious problem.
1235 print_error("unknownparamtype", '', '', $type);
1240 * Whether the PARAM_* type is compatible in RTL.
1242 * Being compatible with RTL means that the data they contain can flow
1243 * from right-to-left or left-to-right without compromising the user experience.
1245 * Take URLs for example, they are not RTL compatible as they should always
1246 * flow from the left to the right. This also applies to numbers, email addresses,
1247 * configuration snippets, base64 strings, etc...
1249 * This function tries to best guess which parameters can contain localised strings.
1251 * @param string $paramtype Constant PARAM_*.
1254 function is_rtl_compatible($paramtype) {
1255 return $paramtype == PARAM_TEXT ||
$paramtype == PARAM_NOTAGS
;
1259 * Makes sure the data is using valid utf8, invalid characters are discarded.
1261 * Note: this function is not intended for full objects with methods and private properties.
1263 * @param mixed $value
1264 * @return mixed with proper utf-8 encoding
1266 function fix_utf8($value) {
1267 if (is_null($value) or $value === '') {
1270 } else if (is_string($value)) {
1271 if ((string)(int)$value === $value) {
1275 // No null bytes expected in our data, so let's remove it.
1276 $value = str_replace("\0", '', $value);
1278 // Note: this duplicates min_fix_utf8() intentionally.
1279 static $buggyiconv = null;
1280 if ($buggyiconv === null) {
1281 $buggyiconv = (!function_exists('iconv') or @iconv
('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1285 if (function_exists('mb_convert_encoding')) {
1286 $subst = mb_substitute_character();
1287 mb_substitute_character('none');
1288 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1289 mb_substitute_character($subst);
1292 // Warn admins on admin/index.php page.
1297 $result = @iconv
('UTF-8', 'UTF-8//IGNORE', $value);
1302 } else if (is_array($value)) {
1303 foreach ($value as $k => $v) {
1304 $value[$k] = fix_utf8($v);
1308 } else if (is_object($value)) {
1309 // Do not modify original.
1310 $value = clone($value);
1311 foreach ($value as $k => $v) {
1312 $value->$k = fix_utf8($v);
1317 // This is some other type, no utf-8 here.
1323 * Return true if given value is integer or string with integer value
1325 * @param mixed $value String or Int
1326 * @return bool true if number, false if not
1328 function is_number($value) {
1329 if (is_int($value)) {
1331 } else if (is_string($value)) {
1332 return ((string)(int)$value) === $value;
1339 * Returns host part from url.
1341 * @param string $url full url
1342 * @return string host, null if not found
1344 function get_host_from_url($url) {
1345 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1353 * Tests whether anything was returned by text editor
1355 * This function is useful for testing whether something you got back from
1356 * the HTML editor actually contains anything. Sometimes the HTML editor
1357 * appear to be empty, but actually you get back a <br> tag or something.
1359 * @param string $string a string containing HTML.
1360 * @return boolean does the string contain any actual content - that is text,
1361 * images, objects, etc.
1363 function html_is_blank($string) {
1364 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1368 * Set a key in global configuration
1370 * Set a key/value pair in both this session's {@link $CFG} global variable
1371 * and in the 'config' database table for future sessions.
1373 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1374 * In that case it doesn't affect $CFG.
1376 * A NULL value will delete the entry.
1378 * NOTE: this function is called from lib/db/upgrade.php
1380 * @param string $name the key to set
1381 * @param string $value the value to set (without magic quotes)
1382 * @param string $plugin (optional) the plugin scope, default null
1383 * @return bool true or exception
1385 function set_config($name, $value, $plugin=null) {
1388 if (empty($plugin)) {
1389 if (!array_key_exists($name, $CFG->config_php_settings
)) {
1390 // So it's defined for this invocation at least.
1391 if (is_null($value)) {
1394 // Settings from db are always strings.
1395 $CFG->$name = (string)$value;
1399 if ($DB->get_field('config', 'name', array('name' => $name))) {
1400 if ($value === null) {
1401 $DB->delete_records('config', array('name' => $name));
1403 $DB->set_field('config', 'value', $value, array('name' => $name));
1406 if ($value !== null) {
1407 $config = new stdClass();
1408 $config->name
= $name;
1409 $config->value
= $value;
1410 $DB->insert_record('config', $config, false);
1412 // When setting config during a Behat test (in the CLI script, not in the web browser
1413 // requests), remember which ones are set so that we can clear them later.
1414 if (defined('BEHAT_TEST')) {
1415 if (!property_exists($CFG, 'behat_cli_added_config')) {
1416 $CFG->behat_cli_added_config
= [];
1418 $CFG->behat_cli_added_config
[$name] = true;
1421 if ($name === 'siteidentifier') {
1422 cache_helper
::update_site_identifier($value);
1424 cache_helper
::invalidate_by_definition('core', 'config', array(), 'core');
1427 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1428 if ($value===null) {
1429 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1431 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1434 if ($value !== null) {
1435 $config = new stdClass();
1436 $config->plugin
= $plugin;
1437 $config->name
= $name;
1438 $config->value
= $value;
1439 $DB->insert_record('config_plugins', $config, false);
1442 cache_helper
::invalidate_by_definition('core', 'config', array(), $plugin);
1449 * Get configuration values from the global config table
1450 * or the config_plugins table.
1452 * If called with one parameter, it will load all the config
1453 * variables for one plugin, and return them as an object.
1455 * If called with 2 parameters it will return a string single
1456 * value or false if the value is not found.
1458 * NOTE: this function is called from lib/db/upgrade.php
1460 * @param string $plugin full component name
1461 * @param string $name default null
1462 * @return mixed hash-like object or single value, return false no config found
1463 * @throws dml_exception
1465 function get_config($plugin, $name = null) {
1468 if ($plugin === 'moodle' ||
$plugin === 'core' ||
empty($plugin)) {
1469 $forced =& $CFG->config_php_settings
;
1473 if (array_key_exists($plugin, $CFG->forced_plugin_settings
)) {
1474 $forced =& $CFG->forced_plugin_settings
[$plugin];
1481 if (!isset($CFG->siteidentifier
)) {
1483 // This may throw an exception during installation, which is how we detect the
1484 // need to install the database. For more details see {@see initialise_cfg()}.
1485 $CFG->siteidentifier
= $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1486 } catch (dml_exception
$ex) {
1487 // Set siteidentifier to false. We don't want to trip this continually.
1488 $siteidentifier = false;
1493 if (!empty($name)) {
1494 if (array_key_exists($name, $forced)) {
1495 return (string)$forced[$name];
1496 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1497 return $CFG->siteidentifier
;
1501 $cache = cache
::make('core', 'config');
1502 $result = $cache->get($plugin);
1503 if ($result === false) {
1504 // The user is after a recordset.
1506 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1508 // This part is not really used any more, but anyway...
1509 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1511 $cache->set($plugin, $result);
1514 if (!empty($name)) {
1515 if (array_key_exists($name, $result)) {
1516 return $result[$name];
1521 if ($plugin === 'core') {
1522 $result['siteidentifier'] = $CFG->siteidentifier
;
1525 foreach ($forced as $key => $value) {
1526 if (is_null($value) or is_array($value) or is_object($value)) {
1527 // We do not want any extra mess here, just real settings that could be saved in db.
1528 unset($result[$key]);
1530 // Convert to string as if it went through the DB.
1531 $result[$key] = (string)$value;
1535 return (object)$result;
1539 * Removes a key from global configuration.
1541 * NOTE: this function is called from lib/db/upgrade.php
1543 * @param string $name the key to set
1544 * @param string $plugin (optional) the plugin scope
1545 * @return boolean whether the operation succeeded.
1547 function unset_config($name, $plugin=null) {
1550 if (empty($plugin)) {
1552 $DB->delete_records('config', array('name' => $name));
1553 cache_helper
::invalidate_by_definition('core', 'config', array(), 'core');
1555 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1556 cache_helper
::invalidate_by_definition('core', 'config', array(), $plugin);
1563 * Remove all the config variables for a given plugin.
1565 * NOTE: this function is called from lib/db/upgrade.php
1567 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1568 * @return boolean whether the operation succeeded.
1570 function unset_all_config_for_plugin($plugin) {
1572 // Delete from the obvious config_plugins first.
1573 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1574 // Next delete any suspect settings from config.
1575 $like = $DB->sql_like('name', '?', true, true, false, '|');
1576 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1577 $DB->delete_records_select('config', $like, $params);
1578 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1579 cache_helper
::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1585 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1587 * All users are verified if they still have the necessary capability.
1589 * @param string $value the value of the config setting.
1590 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1591 * @param bool $includeadmins include administrators.
1592 * @return array of user objects.
1594 function get_users_from_config($value, $capability, $includeadmins = true) {
1595 if (empty($value) or $value === '$@NONE@$') {
1599 // We have to make sure that users still have the necessary capability,
1600 // it should be faster to fetch them all first and then test if they are present
1601 // instead of validating them one-by-one.
1602 $users = get_users_by_capability(context_system
::instance(), $capability);
1603 if ($includeadmins) {
1604 $admins = get_admins();
1605 foreach ($admins as $admin) {
1606 $users[$admin->id
] = $admin;
1610 if ($value === '$@ALL@$') {
1614 $result = array(); // Result in correct order.
1615 $allowed = explode(',', $value);
1616 foreach ($allowed as $uid) {
1617 if (isset($users[$uid])) {
1618 $user = $users[$uid];
1619 $result[$user->id
] = $user;
1628 * Invalidates browser caches and cached data in temp.
1632 function purge_all_caches() {
1637 * Selectively invalidate different types of cache.
1639 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1640 * areas alone or in combination.
1642 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1643 * 'muc' Purge MUC caches?
1644 * 'theme' Purge theme cache?
1645 * 'lang' Purge language string cache?
1646 * 'js' Purge javascript cache?
1647 * 'filter' Purge text filter cache?
1648 * 'other' Purge all other caches?
1650 function purge_caches($options = []) {
1651 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1652 if (empty(array_filter($options))) {
1653 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1655 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1657 if ($options['muc']) {
1658 cache_helper
::purge_all();
1660 if ($options['theme']) {
1661 theme_reset_all_caches();
1663 if ($options['lang']) {
1664 get_string_manager()->reset_caches();
1666 if ($options['js']) {
1667 js_reset_all_caches();
1669 if ($options['template']) {
1670 template_reset_all_caches();
1672 if ($options['filter']) {
1673 reset_text_filters_cache();
1675 if ($options['other']) {
1676 purge_other_caches();
1681 * Purge all non-MUC caches not otherwise purged in purge_caches.
1683 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1684 * {@link phpunit_util::reset_dataroot()}
1686 function purge_other_caches() {
1688 if (class_exists('core_plugin_manager')) {
1689 core_plugin_manager
::reset_caches();
1692 // Bump up cacherev field for all courses.
1694 increment_revision_number('course', 'cacherev', '');
1695 } catch (moodle_exception
$e) {
1696 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1699 $DB->reset_caches();
1701 // Purge all other caches: rss, simplepie, etc.
1703 remove_dir($CFG->cachedir
.'', true);
1705 // Make sure cache dir is writable, throws exception if not.
1706 make_cache_directory('');
1708 // This is the only place where we purge local caches, we are only adding files there.
1709 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1710 remove_dir($CFG->localcachedir
, true);
1711 set_config('localcachedirpurged', time());
1712 make_localcache_directory('', true);
1713 \core\task\manager
::clear_static_caches();
1717 * Get volatile flags
1719 * @param string $type
1720 * @param int $changedsince default null
1721 * @return array records array
1723 function get_cache_flags($type, $changedsince = null) {
1726 $params = array('type' => $type, 'expiry' => time());
1727 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1728 if ($changedsince !== null) {
1729 $params['changedsince'] = $changedsince;
1730 $sqlwhere .= " AND timemodified > :changedsince";
1733 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1734 foreach ($flags as $flag) {
1735 $cf[$flag->name
] = $flag->value
;
1742 * Get volatile flags
1744 * @param string $type
1745 * @param string $name
1746 * @param int $changedsince default null
1747 * @return string|false The cache flag value or false
1749 function get_cache_flag($type, $name, $changedsince=null) {
1752 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1754 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1755 if ($changedsince !== null) {
1756 $params['changedsince'] = $changedsince;
1757 $sqlwhere .= " AND timemodified > :changedsince";
1760 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1764 * Set a volatile flag
1766 * @param string $type the "type" namespace for the key
1767 * @param string $name the key to set
1768 * @param string $value the value to set (without magic quotes) - null will remove the flag
1769 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1770 * @return bool Always returns true
1772 function set_cache_flag($type, $name, $value, $expiry = null) {
1775 $timemodified = time();
1776 if ($expiry === null ||
$expiry < $timemodified) {
1777 $expiry = $timemodified +
24 * 60 * 60;
1779 $expiry = (int)$expiry;
1782 if ($value === null) {
1783 unset_cache_flag($type, $name);
1787 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE
)) {
1788 // This is a potential problem in DEBUG_DEVELOPER.
1789 if ($f->value
== $value and $f->expiry
== $expiry and $f->timemodified
== $timemodified) {
1790 return true; // No need to update.
1793 $f->expiry
= $expiry;
1794 $f->timemodified
= $timemodified;
1795 $DB->update_record('cache_flags', $f);
1797 $f = new stdClass();
1798 $f->flagtype
= $type;
1801 $f->expiry
= $expiry;
1802 $f->timemodified
= $timemodified;
1803 $DB->insert_record('cache_flags', $f);
1809 * Removes a single volatile flag
1811 * @param string $type the "type" namespace for the key
1812 * @param string $name the key to set
1815 function unset_cache_flag($type, $name) {
1817 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1822 * Garbage-collect volatile flags
1824 * @return bool Always returns true
1826 function gc_cache_flags() {
1828 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1832 // USER PREFERENCE API.
1835 * Refresh user preference cache. This is used most often for $USER
1836 * object that is stored in session, but it also helps with performance in cron script.
1838 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1841 * @category preference
1843 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1844 * @param int $cachelifetime Cache life time on the current page (in seconds)
1845 * @throws coding_exception
1848 function check_user_preferences_loaded(stdClass
$user, $cachelifetime = 120) {
1850 // Static cache, we need to check on each page load, not only every 2 minutes.
1851 static $loadedusers = array();
1853 if (!isset($user->id
)) {
1854 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1857 if (empty($user->id
) or isguestuser($user->id
)) {
1858 // No permanent storage for not-logged-in users and guest.
1859 if (!isset($user->preference
)) {
1860 $user->preference
= array();
1867 if (isset($loadedusers[$user->id
]) and isset($user->preference
) and isset($user->preference
['_lastloaded'])) {
1868 // Already loaded at least once on this page. Are we up to date?
1869 if ($user->preference
['_lastloaded'] +
$cachelifetime > $timenow) {
1870 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1873 } else if (!get_cache_flag('userpreferenceschanged', $user->id
, $user->preference
['_lastloaded'])) {
1874 // No change since the lastcheck on this page.
1875 $user->preference
['_lastloaded'] = $timenow;
1880 // OK, so we have to reload all preferences.
1881 $loadedusers[$user->id
] = true;
1882 $user->preference
= $DB->get_records_menu('user_preferences', array('userid' => $user->id
), '', 'name,value'); // All values.
1883 $user->preference
['_lastloaded'] = $timenow;
1887 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1889 * NOTE: internal function, do not call from other code.
1893 * @param integer $userid the user whose prefs were changed.
1895 function mark_user_preferences_changed($userid) {
1898 if (empty($userid) or isguestuser($userid)) {
1899 // No cache flags for guest and not-logged-in users.
1903 set_cache_flag('userpreferenceschanged', $userid, 1, time() +
$CFG->sessiontimeout
);
1907 * Sets a preference for the specified user.
1909 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1911 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1914 * @category preference
1916 * @param string $name The key to set as preference for the specified user
1917 * @param string $value The value to set for the $name key in the specified user's
1918 * record, null means delete current value.
1919 * @param stdClass|int|null $user A moodle user object or id, null means current user
1920 * @throws coding_exception
1921 * @return bool Always true or exception
1923 function set_user_preference($name, $value, $user = null) {
1926 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1927 throw new coding_exception('Invalid preference name in set_user_preference() call');
1930 if (is_null($value)) {
1931 // Null means delete current.
1932 return unset_user_preference($name, $user);
1933 } else if (is_object($value)) {
1934 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1935 } else if (is_array($value)) {
1936 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1938 // Value column maximum length is 1333 characters.
1939 $value = (string)$value;
1940 if (core_text
::strlen($value) > 1333) {
1941 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1944 if (is_null($user)) {
1946 } else if (isset($user->id
)) {
1947 // It is a valid object.
1948 } else if (is_numeric($user)) {
1949 $user = (object)array('id' => (int)$user);
1951 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1954 check_user_preferences_loaded($user);
1956 if (empty($user->id
) or isguestuser($user->id
)) {
1957 // No permanent storage for not-logged-in users and guest.
1958 $user->preference
[$name] = $value;
1962 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => $name))) {
1963 if ($preference->value
=== $value and isset($user->preference
[$name]) and $user->preference
[$name] === $value) {
1964 // Preference already set to this value.
1967 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id
));
1970 $preference = new stdClass();
1971 $preference->userid
= $user->id
;
1972 $preference->name
= $name;
1973 $preference->value
= $value;
1974 $DB->insert_record('user_preferences', $preference);
1977 // Update value in cache.
1978 $user->preference
[$name] = $value;
1979 // Update the $USER in case where we've not a direct reference to $USER.
1980 if ($user !== $USER && $user->id
== $USER->id
) {
1981 $USER->preference
[$name] = $value;
1984 // Set reload flag for other sessions.
1985 mark_user_preferences_changed($user->id
);
1991 * Sets a whole array of preferences for the current user
1993 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1996 * @category preference
1998 * @param array $prefarray An array of key/value pairs to be set
1999 * @param stdClass|int|null $user A moodle user object or id, null means current user
2000 * @return bool Always true or exception
2002 function set_user_preferences(array $prefarray, $user = null) {
2003 foreach ($prefarray as $name => $value) {
2004 set_user_preference($name, $value, $user);
2010 * Unsets a preference completely by deleting it from the database
2012 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2015 * @category preference
2017 * @param string $name The key to unset as preference for the specified user
2018 * @param stdClass|int|null $user A moodle user object or id, null means current user
2019 * @throws coding_exception
2020 * @return bool Always true or exception
2022 function unset_user_preference($name, $user = null) {
2025 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2026 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2029 if (is_null($user)) {
2031 } else if (isset($user->id
)) {
2032 // It is a valid object.
2033 } else if (is_numeric($user)) {
2034 $user = (object)array('id' => (int)$user);
2036 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2039 check_user_preferences_loaded($user);
2041 if (empty($user->id
) or isguestuser($user->id
)) {
2042 // No permanent storage for not-logged-in user and guest.
2043 unset($user->preference
[$name]);
2048 $DB->delete_records('user_preferences', array('userid' => $user->id
, 'name' => $name));
2050 // Delete the preference from cache.
2051 unset($user->preference
[$name]);
2052 // Update the $USER in case where we've not a direct reference to $USER.
2053 if ($user !== $USER && $user->id
== $USER->id
) {
2054 unset($USER->preference
[$name]);
2057 // Set reload flag for other sessions.
2058 mark_user_preferences_changed($user->id
);
2064 * Used to fetch user preference(s)
2066 * If no arguments are supplied this function will return
2067 * all of the current user preferences as an array.
2069 * If a name is specified then this function
2070 * attempts to return that particular preference value. If
2071 * none is found, then the optional value $default is returned,
2074 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2077 * @category preference
2079 * @param string $name Name of the key to use in finding a preference value
2080 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2081 * @param stdClass|int|null $user A moodle user object or id, null means current user
2082 * @throws coding_exception
2083 * @return string|mixed|null A string containing the value of a single preference. An
2084 * array with all of the preferences or null
2086 function get_user_preferences($name = null, $default = null, $user = null) {
2089 if (is_null($name)) {
2091 } else if (is_numeric($name) or $name === '_lastloaded') {
2092 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2095 if (is_null($user)) {
2097 } else if (isset($user->id
)) {
2098 // Is a valid object.
2099 } else if (is_numeric($user)) {
2100 if ($USER->id
== $user) {
2103 $user = (object)array('id' => (int)$user);
2106 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2109 check_user_preferences_loaded($user);
2113 return $user->preference
;
2114 } else if (isset($user->preference
[$name])) {
2115 // The single string value.
2116 return $user->preference
[$name];
2118 // Default value (null if not specified).
2123 // FUNCTIONS FOR HANDLING TIME.
2126 * Given Gregorian date parts in user time produce a GMT timestamp.
2130 * @param int $year The year part to create timestamp of
2131 * @param int $month The month part to create timestamp of
2132 * @param int $day The day part to create timestamp of
2133 * @param int $hour The hour part to create timestamp of
2134 * @param int $minute The minute part to create timestamp of
2135 * @param int $second The second part to create timestamp of
2136 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2137 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2138 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2139 * applied only if timezone is 99 or string.
2140 * @return int GMT timestamp
2142 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2143 $date = new DateTime('now', core_date
::get_user_timezone_object($timezone));
2144 $date->setDate((int)$year, (int)$month, (int)$day);
2145 $date->setTime((int)$hour, (int)$minute, (int)$second);
2147 $time = $date->getTimestamp();
2149 if ($time === false) {
2150 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2151 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2154 // Moodle BC DST stuff.
2156 $time +
= dst_offset_on($time, $timezone);
2164 * Format a date/time (seconds) as weeks, days, hours etc as needed
2166 * Given an amount of time in seconds, returns string
2167 * formatted nicely as years, days, hours etc as needed
2175 * @param int $totalsecs Time in seconds
2176 * @param stdClass $str Should be a time object
2177 * @return string A nicely formatted date/time string
2179 function format_time($totalsecs, $str = null) {
2181 $totalsecs = abs($totalsecs);
2184 // Create the str structure the slow way.
2185 $str = new stdClass();
2186 $str->day
= get_string('day');
2187 $str->days
= get_string('days');
2188 $str->hour
= get_string('hour');
2189 $str->hours
= get_string('hours');
2190 $str->min
= get_string('min');
2191 $str->mins
= get_string('mins');
2192 $str->sec
= get_string('sec');
2193 $str->secs
= get_string('secs');
2194 $str->year
= get_string('year');
2195 $str->years
= get_string('years');
2198 $years = floor($totalsecs/YEARSECS
);
2199 $remainder = $totalsecs - ($years*YEARSECS
);
2200 $days = floor($remainder/DAYSECS
);
2201 $remainder = $totalsecs - ($days*DAYSECS
);
2202 $hours = floor($remainder/HOURSECS
);
2203 $remainder = $remainder - ($hours*HOURSECS
);
2204 $mins = floor($remainder/MINSECS
);
2205 $secs = $remainder - ($mins*MINSECS
);
2207 $ss = ($secs == 1) ?
$str->sec
: $str->secs
;
2208 $sm = ($mins == 1) ?
$str->min
: $str->mins
;
2209 $sh = ($hours == 1) ?
$str->hour
: $str->hours
;
2210 $sd = ($days == 1) ?
$str->day
: $str->days
;
2211 $sy = ($years == 1) ?
$str->year
: $str->years
;
2220 $oyears = $years .' '. $sy;
2223 $odays = $days .' '. $sd;
2226 $ohours = $hours .' '. $sh;
2229 $omins = $mins .' '. $sm;
2232 $osecs = $secs .' '. $ss;
2236 return trim($oyears .' '. $odays);
2239 return trim($odays .' '. $ohours);
2242 return trim($ohours .' '. $omins);
2245 return trim($omins .' '. $osecs);
2250 return get_string('now');
2254 * Returns a formatted string that represents a date in user time.
2258 * @param int $date the timestamp in UTC, as obtained from the database.
2259 * @param string $format strftime format. You should probably get this using
2260 * get_string('strftime...', 'langconfig');
2261 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2262 * not 99 then daylight saving will not be added.
2263 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2264 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2265 * If false then the leading zero is maintained.
2266 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2267 * @return string the formatted date/time.
2269 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2270 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2271 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2275 * Returns a html "time" tag with both the exact user date with timezone information
2276 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2280 * @param int $date the timestamp in UTC, as obtained from the database.
2281 * @param string $format strftime format. You should probably get this using
2282 * get_string('strftime...', 'langconfig');
2283 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2284 * not 99 then daylight saving will not be added.
2285 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2286 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2287 * If false then the leading zero is maintained.
2288 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2289 * @return string the formatted date/time.
2291 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2292 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2293 if (CLI_SCRIPT
&& !PHPUNIT_TEST
) {
2294 return $userdatestr;
2296 $machinedate = new DateTime();
2297 $machinedate->setTimestamp(intval($date));
2298 $machinedate->setTimezone(core_date
::get_user_timezone_object());
2300 return html_writer
::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime
::W3C
)]);
2304 * Returns a formatted date ensuring it is UTF-8.
2306 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2307 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2309 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2310 * @param string $format strftime format.
2311 * @param int|float|string $tz the user timezone
2312 * @return string the formatted date/time.
2313 * @since Moodle 2.3.3
2315 function date_format_string($date, $format, $tz = 99) {
2318 $localewincharset = null;
2319 // Get the calendar type user is using.
2320 if ($CFG->ostype
== 'WINDOWS') {
2321 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2322 $localewincharset = $calendartype->locale_win_charset();
2325 if ($localewincharset) {
2326 $format = core_text
::convert($format, 'utf-8', $localewincharset);
2329 date_default_timezone_set(core_date
::get_user_timezone($tz));
2330 $datestring = strftime($format, $date);
2331 core_date
::set_default_server_timezone();
2333 if ($localewincharset) {
2334 $datestring = core_text
::convert($datestring, $localewincharset, 'utf-8');
2341 * Given a $time timestamp in GMT (seconds since epoch),
2342 * returns an array that represents the Gregorian date in user time
2346 * @param int $time Timestamp in GMT
2347 * @param float|int|string $timezone user timezone
2348 * @return array An array that represents the date in user time
2350 function usergetdate($time, $timezone=99) {
2351 if ($time === null) {
2352 // PHP8 and PHP7 return different results when getdate(null) is called.
2353 // Display warning and cast to 0 to make sure the usergetdate() behaves consistently on all versions of PHP.
2354 // In the future versions of Moodle we may consider adding a strict typehint.
2355 debugging('usergetdate() expects parameter $time to be int, null given', DEBUG_DEVELOPER
);
2359 date_default_timezone_set(core_date
::get_user_timezone($timezone));
2360 $result = getdate($time);
2361 core_date
::set_default_server_timezone();
2367 * Given a GMT timestamp (seconds since epoch), offsets it by
2368 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2370 * NOTE: this function does not include DST properly,
2371 * you should use the PHP date stuff instead!
2375 * @param int $date Timestamp in GMT
2376 * @param float|int|string $timezone user timezone
2379 function usertime($date, $timezone=99) {
2380 $userdate = new DateTime('@' . $date);
2381 $userdate->setTimezone(core_date
::get_user_timezone_object($timezone));
2382 $dst = dst_offset_on($date, $timezone);
2384 return $date - $userdate->getOffset() +
$dst;
2388 * Get a formatted string representation of an interval between two unix timestamps.
2391 * $intervalstring = get_time_interval_string(12345600, 12345660);
2392 * Will produce the string:
2395 * @param int $time1 unix timestamp
2396 * @param int $time2 unix timestamp
2397 * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2398 * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2400 function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
2401 $dtdate = new DateTime();
2402 $dtdate->setTimeStamp($time1);
2403 $dtdate2 = new DateTime();
2404 $dtdate2->setTimeStamp($time2);
2405 $interval = $dtdate2->diff($dtdate);
2406 $format = empty($format) ?
get_string('dateintervaldayshoursmins', 'langconfig') : $format;
2407 return $interval->format($format);
2411 * Given a time, return the GMT timestamp of the most recent midnight
2412 * for the current user.
2416 * @param int $date Timestamp in GMT
2417 * @param float|int|string $timezone user timezone
2418 * @return int Returns a GMT timestamp
2420 function usergetmidnight($date, $timezone=99) {
2422 $userdate = usergetdate($date, $timezone);
2424 // Time of midnight of this user's day, in GMT.
2425 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2430 * Returns a string that prints the user's timezone
2434 * @param float|int|string $timezone user timezone
2437 function usertimezone($timezone=99) {
2438 $tz = core_date
::get_user_timezone($timezone);
2439 return core_date
::get_localised_timezone($tz);
2443 * Returns a float or a string which denotes the user's timezone
2444 * 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)
2445 * means that for this timezone there are also DST rules to be taken into account
2446 * Checks various settings and picks the most dominant of those which have a value
2450 * @param float|int|string $tz timezone to calculate GMT time offset before
2451 * calculating user timezone, 99 is default user timezone
2452 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2453 * @return float|string
2455 function get_user_timezone($tz = 99) {
2460 isset($CFG->forcetimezone
) ?
$CFG->forcetimezone
: 99,
2461 isset($USER->timezone
) ?
$USER->timezone
: 99,
2462 isset($CFG->timezone
) ?
$CFG->timezone
: 99,
2467 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2468 foreach ($timezones as $nextvalue) {
2469 if ((empty($tz) && !is_numeric($tz)) ||
$tz == 99) {
2473 return is_numeric($tz) ?
(float) $tz : $tz;
2477 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2478 * - Note: Daylight saving only works for string timezones and not for float.
2482 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2483 * @param int|float|string $strtimezone user timezone
2486 function dst_offset_on($time, $strtimezone = null) {
2487 $tz = core_date
::get_user_timezone($strtimezone);
2488 $date = new DateTime('@' . $time);
2489 $date->setTimezone(new DateTimeZone($tz));
2490 if ($date->format('I') == '1') {
2491 if ($tz === 'Australia/Lord_Howe') {
2500 * Calculates when the day appears in specific month
2504 * @param int $startday starting day of the month
2505 * @param int $weekday The day when week starts (normally taken from user preferences)
2506 * @param int $month The month whose day is sought
2507 * @param int $year The year of the month whose day is sought
2510 function find_day_in_month($startday, $weekday, $month, $year) {
2511 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2513 $daysinmonth = days_in_month($month, $year);
2514 $daysinweek = count($calendartype->get_weekdays());
2516 if ($weekday == -1) {
2517 // Don't care about weekday, so return:
2518 // abs($startday) if $startday != -1
2519 // $daysinmonth otherwise.
2520 return ($startday == -1) ?
$daysinmonth : abs($startday);
2523 // From now on we 're looking for a specific weekday.
2524 // Give "end of month" its actual value, since we know it.
2525 if ($startday == -1) {
2526 $startday = -1 * $daysinmonth;
2529 // Starting from day $startday, the sign is the direction.
2530 if ($startday < 1) {
2531 $startday = abs($startday);
2532 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2534 // This is the last such weekday of the month.
2535 $lastinmonth = $daysinmonth +
$weekday - $lastmonthweekday;
2536 if ($lastinmonth > $daysinmonth) {
2537 $lastinmonth -= $daysinweek;
2540 // Find the first such weekday <= $startday.
2541 while ($lastinmonth > $startday) {
2542 $lastinmonth -= $daysinweek;
2545 return $lastinmonth;
2547 $indexweekday = dayofweek($startday, $month, $year);
2549 $diff = $weekday - $indexweekday;
2551 $diff +
= $daysinweek;
2554 // This is the first such weekday of the month equal to or after $startday.
2555 $firstfromindex = $startday +
$diff;
2557 return $firstfromindex;
2562 * Calculate the number of days in a given month
2566 * @param int $month The month whose day count is sought
2567 * @param int $year The year of the month whose day count is sought
2570 function days_in_month($month, $year) {
2571 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2572 return $calendartype->get_num_days_in_month($year, $month);
2576 * Calculate the position in the week of a specific calendar day
2580 * @param int $day The day of the date whose position in the week is sought
2581 * @param int $month The month of the date whose position in the week is sought
2582 * @param int $year The year of the date whose position in the week is sought
2585 function dayofweek($day, $month, $year) {
2586 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2587 return $calendartype->get_weekday($year, $month, $day);
2590 // USER AUTHENTICATION AND LOGIN.
2593 * Returns full login url.
2595 * Any form submissions for authentication to this URL must include username,
2596 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2598 * @return string login url
2600 function get_login_url() {
2603 return "$CFG->wwwroot/login/index.php";
2607 * This function checks that the current user is logged in and has the
2608 * required privileges
2610 * This function checks that the current user is logged in, and optionally
2611 * whether they are allowed to be in a particular course and view a particular
2613 * If they are not logged in, then it redirects them to the site login unless
2614 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2615 * case they are automatically logged in as guests.
2616 * If $courseid is given and the user is not enrolled in that course then the
2617 * user is redirected to the course enrolment page.
2618 * If $cm is given and the course module is hidden and the user is not a teacher
2619 * in the course then the user is redirected to the course home page.
2621 * When $cm parameter specified, this function sets page layout to 'module'.
2622 * You need to change it manually later if some other layout needed.
2624 * @package core_access
2627 * @param mixed $courseorid id of the course or course object
2628 * @param bool $autologinguest default true
2629 * @param object $cm course module object
2630 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2631 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2632 * in order to keep redirects working properly. MDL-14495
2633 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2634 * @return mixed Void, exit, and die depending on path
2635 * @throws coding_exception
2636 * @throws require_login_exception
2637 * @throws moodle_exception
2639 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2640 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2642 // Must not redirect when byteserving already started.
2643 if (!empty($_SERVER['HTTP_RANGE'])) {
2644 $preventredirect = true;
2648 // We cannot redirect for AJAX scripts either.
2649 $preventredirect = true;
2652 // Setup global $COURSE, themes, language and locale.
2653 if (!empty($courseorid)) {
2654 if (is_object($courseorid)) {
2655 $course = $courseorid;
2656 } else if ($courseorid == SITEID
) {
2657 $course = clone($SITE);
2659 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST
);
2662 if ($cm->course
!= $course->id
) {
2663 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2665 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2666 if (!($cm instanceof cm_info
)) {
2667 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2668 // db queries so this is not really a performance concern, however it is obviously
2669 // better if you use get_fast_modinfo to get the cm before calling this.
2670 $modinfo = get_fast_modinfo($course);
2671 $cm = $modinfo->get_cm($cm->id
);
2675 // Do not touch global $COURSE via $PAGE->set_course(),
2676 // the reasons is we need to be able to call require_login() at any time!!
2679 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2683 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2684 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2685 // risk leading the user back to the AJAX request URL.
2686 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT
) {
2687 $setwantsurltome = false;
2690 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2691 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out
) && !empty($CFG->dbsessions
)) {
2692 if ($preventredirect) {
2693 throw new require_login_session_timeout_exception();
2695 if ($setwantsurltome) {
2696 $SESSION->wantsurl
= qualified_me();
2698 redirect(get_login_url());
2702 // If the user is not even logged in yet then make sure they are.
2703 if (!isloggedin()) {
2704 if ($autologinguest and !empty($CFG->guestloginbutton
) and !empty($CFG->autologinguests
)) {
2705 if (!$guest = get_complete_user_data('id', $CFG->siteguest
)) {
2706 // Misconfigured site guest, just redirect to login page.
2707 redirect(get_login_url());
2708 exit; // Never reached.
2710 $lang = isset($SESSION->lang
) ?
$SESSION->lang
: $CFG->lang
;
2711 complete_user_login($guest);
2712 $USER->autologinguest
= true;
2713 $SESSION->lang
= $lang;
2715 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2716 if ($preventredirect) {
2717 throw new require_login_exception('You are not logged in');
2720 if ($setwantsurltome) {
2721 $SESSION->wantsurl
= qualified_me();
2724 $referer = get_local_referer(false);
2725 if (!empty($referer)) {
2726 $SESSION->fromurl
= $referer;
2729 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2730 $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
2731 foreach($authsequence as $authname) {
2732 $authplugin = get_auth_plugin($authname);
2733 $authplugin->pre_loginpage_hook();
2736 $modinfo = get_fast_modinfo($course);
2737 $cm = $modinfo->get_cm($cm->id
);
2739 set_access_log_user();
2744 // If we're still not logged in then go to the login page
2745 if (!isloggedin()) {
2746 redirect(get_login_url());
2747 exit; // Never reached.
2752 // Loginas as redirection if needed.
2753 if ($course->id
!= SITEID
and \core\session\manager
::is_loggedinas()) {
2754 if ($USER->loginascontext
->contextlevel
== CONTEXT_COURSE
) {
2755 if ($USER->loginascontext
->instanceid
!= $course->id
) {
2756 print_error('loginasonecourse', '', $CFG->wwwroot
.'/course/view.php?id='.$USER->loginascontext
->instanceid
);
2761 // Check whether the user should be changing password (but only if it is REALLY them).
2762 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager
::is_loggedinas()) {
2763 $userauth = get_auth_plugin($USER->auth
);
2764 if ($userauth->can_change_password() and !$preventredirect) {
2765 if ($setwantsurltome) {
2766 $SESSION->wantsurl
= qualified_me();
2768 if ($changeurl = $userauth->change_password_url()) {
2769 // Use plugin custom url.
2770 redirect($changeurl);
2772 // Use moodle internal method.
2773 redirect($CFG->wwwroot
.'/login/change_password.php');
2775 } else if ($userauth->can_change_password()) {
2776 throw new moodle_exception('forcepasswordchangenotice');
2778 throw new moodle_exception('nopasswordchangeforced', 'auth');
2782 // Check that the user account is properly set up. If we can't redirect to
2783 // edit their profile and this is not a WS request, perform just the lax check.
2784 // It will allow them to use filepicker on the profile edit page.
2786 if ($preventredirect && !WS_SERVER
) {
2787 $usernotfullysetup = user_not_fully_set_up($USER, false);
2789 $usernotfullysetup = user_not_fully_set_up($USER, true);
2792 if ($usernotfullysetup) {
2793 if ($preventredirect) {
2794 throw new moodle_exception('usernotfullysetup');
2796 if ($setwantsurltome) {
2797 $SESSION->wantsurl
= qualified_me();
2799 redirect($CFG->wwwroot
.'/user/edit.php?id='. $USER->id
.'&course='. SITEID
);
2802 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2805 if (\core\session\manager
::is_loggedinas()) {
2806 // During a "logged in as" session we should force all content to be cleaned because the
2807 // logged in user will be viewing potentially malicious user generated content.
2808 // See MDL-63786 for more details.
2809 $CFG->forceclean
= true;
2812 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2814 // Do not bother admins with any formalities, except for activities pending deletion.
2815 if (is_siteadmin() && !($cm && $cm->deletioninprogress
)) {
2816 // Set the global $COURSE.
2818 $PAGE->set_cm($cm, $course);
2819 $PAGE->set_pagelayout('incourse');
2820 } else if (!empty($courseorid)) {
2821 $PAGE->set_course($course);
2823 // Set accesstime or the user will appear offline which messes up messaging.
2824 // Do not update access time for webservice or ajax requests.
2825 if (!WS_SERVER
&& !AJAX_SCRIPT
) {
2826 user_accesstime_log($course->id
);
2829 foreach ($afterlogins as $plugintype => $plugins) {
2830 foreach ($plugins as $pluginfunction) {
2831 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2837 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2838 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2839 if (!defined('NO_SITEPOLICY_CHECK')) {
2840 define('NO_SITEPOLICY_CHECK', false);
2843 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2844 // Do not test if the script explicitly asked for skipping the site policies check.
2845 if (!$USER->policyagreed
&& !is_siteadmin() && !NO_SITEPOLICY_CHECK
) {
2846 $manager = new \core_privacy\local\sitepolicy\
manager();
2847 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2848 if ($preventredirect) {
2849 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2851 if ($setwantsurltome) {
2852 $SESSION->wantsurl
= qualified_me();
2854 redirect($policyurl);
2858 // Fetch the system context, the course context, and prefetch its child contexts.
2859 $sysctx = context_system
::instance();
2860 $coursecontext = context_course
::instance($course->id
, MUST_EXIST
);
2862 $cmcontext = context_module
::instance($cm->id
, MUST_EXIST
);
2867 // If the site is currently under maintenance, then print a message.
2868 if (!empty($CFG->maintenance_enabled
) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2869 if ($preventredirect) {
2870 throw new require_login_exception('Maintenance in progress');
2872 $PAGE->set_context(null);
2873 print_maintenance_message();
2876 // Make sure the course itself is not hidden.
2877 if ($course->id
== SITEID
) {
2878 // Frontpage can not be hidden.
2880 if (is_role_switched($course->id
)) {
2881 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2883 if (!$course->visible
and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2884 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2885 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2886 if ($preventredirect) {
2887 throw new require_login_exception('Course is hidden');
2889 $PAGE->set_context(null);
2890 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2891 // the navigation will mess up when trying to find it.
2892 navigation_node
::override_active_url(new moodle_url('/'));
2893 notice(get_string('coursehidden'), $CFG->wwwroot
.'/');
2898 // Is the user enrolled?
2899 if ($course->id
== SITEID
) {
2900 // Everybody is enrolled on the frontpage.
2902 if (\core\session\manager
::is_loggedinas()) {
2903 // Make sure the REAL person can access this course first.
2904 $realuser = \core\session\manager
::get_realuser();
2905 if (!is_enrolled($coursecontext, $realuser->id
, '', true) and
2906 !is_viewing($coursecontext, $realuser->id
) and !is_siteadmin($realuser->id
)) {
2907 if ($preventredirect) {
2908 throw new require_login_exception('Invalid course login-as access');
2910 $PAGE->set_context(null);
2911 echo $OUTPUT->header();
2912 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot
.'/');
2918 if (is_role_switched($course->id
)) {
2919 // Ok, user had to be inside this course before the switch.
2922 } else if (is_viewing($coursecontext, $USER)) {
2923 // Ok, no need to mess with enrol.
2927 if (isset($USER->enrol
['enrolled'][$course->id
])) {
2928 if ($USER->enrol
['enrolled'][$course->id
] > time()) {
2930 if (isset($USER->enrol
['tempguest'][$course->id
])) {
2931 unset($USER->enrol
['tempguest'][$course->id
]);
2932 remove_temp_course_roles($coursecontext);
2936 unset($USER->enrol
['enrolled'][$course->id
]);
2939 if (isset($USER->enrol
['tempguest'][$course->id
])) {
2940 if ($USER->enrol
['tempguest'][$course->id
] == 0) {
2942 } else if ($USER->enrol
['tempguest'][$course->id
] > time()) {
2946 unset($USER->enrol
['tempguest'][$course->id
]);
2947 remove_temp_course_roles($coursecontext);
2953 $until = enrol_get_enrolment_end($coursecontext->instanceid
, $USER->id
);
2954 if ($until !== false) {
2955 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2957 $until = ENROL_MAX_TIMESTAMP
;
2959 $USER->enrol
['enrolled'][$course->id
] = $until;
2962 } else if (core_course_category
::can_view_course_info($course)) {
2963 $params = array('courseid' => $course->id
, 'status' => ENROL_INSTANCE_ENABLED
);
2964 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2965 $enrols = enrol_get_plugins(true);
2966 // First ask all enabled enrol instances in course if they want to auto enrol user.
2967 foreach ($instances as $instance) {
2968 if (!isset($enrols[$instance->enrol
])) {
2971 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2972 $until = $enrols[$instance->enrol
]->try_autoenrol($instance);
2973 if ($until !== false) {
2975 $until = ENROL_MAX_TIMESTAMP
;
2977 $USER->enrol
['enrolled'][$course->id
] = $until;
2982 // If not enrolled yet try to gain temporary guest access.
2984 foreach ($instances as $instance) {
2985 if (!isset($enrols[$instance->enrol
])) {
2988 // Get a duration for the guest access, a timestamp in the future or false.
2989 $until = $enrols[$instance->enrol
]->try_guestaccess($instance);
2990 if ($until !== false and $until > time()) {
2991 $USER->enrol
['tempguest'][$course->id
] = $until;
2998 // User is not enrolled and is not allowed to browse courses here.
2999 if ($preventredirect) {
3000 throw new require_login_exception('Course is not available');
3002 $PAGE->set_context(null);
3003 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3004 // the navigation will mess up when trying to find it.
3005 navigation_node
::override_active_url(new moodle_url('/'));
3006 notice(get_string('coursehidden'), $CFG->wwwroot
.'/');
3012 if ($preventredirect) {
3013 throw new require_login_exception('Not enrolled');
3015 if ($setwantsurltome) {
3016 $SESSION->wantsurl
= qualified_me();
3018 redirect($CFG->wwwroot
.'/enrol/index.php?id='. $course->id
);
3022 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3023 if ($cm && $cm->deletioninprogress
) {
3024 if ($preventredirect) {
3025 throw new moodle_exception('activityisscheduledfordeletion');
3027 require_once($CFG->dirroot
. '/course/lib.php');
3028 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3031 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3032 if ($cm && !$cm->uservisible
) {
3033 if ($preventredirect) {
3034 throw new require_login_exception('Activity is hidden');
3036 // Get the error message that activity is not available and why (if explanation can be shown to the user).
3037 $PAGE->set_course($course);
3038 $renderer = $PAGE->get_renderer('course');
3039 $message = $renderer->course_section_cm_unavailable_error_message($cm);
3040 redirect(course_get_url($course), $message, null, \core\output\notification
::NOTIFY_ERROR
);
3043 // Set the global $COURSE.
3045 $PAGE->set_cm($cm, $course);
3046 $PAGE->set_pagelayout('incourse');
3047 } else if (!empty($courseorid)) {
3048 $PAGE->set_course($course);
3051 foreach ($afterlogins as $plugintype => $plugins) {
3052 foreach ($plugins as $pluginfunction) {
3053 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3057 // Finally access granted, update lastaccess times.
3058 // Do not update access time for webservice or ajax requests.
3059 if (!WS_SERVER
&& !AJAX_SCRIPT
) {
3060 user_accesstime_log($course->id
);
3065 * A convenience function for where we must be logged in as admin
3068 function require_admin() {
3069 require_login(null, false);
3070 require_capability('moodle/site:config', context_system
::instance());
3074 * This function just makes sure a user is logged out.
3076 * @package core_access
3079 function require_logout() {
3082 if (!isloggedin()) {
3083 // This should not happen often, no need for hooks or events here.
3084 \core\session\manager
::terminate_current();
3088 // Execute hooks before action.
3089 $authplugins = array();
3090 $authsequence = get_enabled_auth_plugins();
3091 foreach ($authsequence as $authname) {
3092 $authplugins[$authname] = get_auth_plugin($authname);
3093 $authplugins[$authname]->prelogout_hook();
3096 // Store info that gets removed during logout.
3097 $sid = session_id();
3098 $event = \core\event\user_loggedout
::create(
3100 'userid' => $USER->id
,
3101 'objectid' => $USER->id
,
3102 'other' => array('sessionid' => $sid),
3105 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3106 $event->add_record_snapshot('sessions', $session);
3109 // Clone of $USER object to be used by auth plugins.
3110 $user = fullclone($USER);
3112 // Delete session record and drop $_SESSION content.
3113 \core\session\manager
::terminate_current();
3115 // Trigger event AFTER action.
3118 // Hook to execute auth plugins redirection after event trigger.
3119 foreach ($authplugins as $authplugin) {
3120 $authplugin->postlogout_hook($user);
3125 * Weaker version of require_login()
3127 * This is a weaker version of {@link require_login()} which only requires login
3128 * when called from within a course rather than the site page, unless
3129 * the forcelogin option is turned on.
3130 * @see require_login()
3132 * @package core_access
3135 * @param mixed $courseorid The course object or id in question
3136 * @param bool $autologinguest Allow autologin guests if that is wanted
3137 * @param object $cm Course activity module if known
3138 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3139 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3140 * in order to keep redirects working properly. MDL-14495
3141 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3143 * @throws coding_exception
3145 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3146 global $CFG, $PAGE, $SITE;
3147 $issite = ((is_object($courseorid) and $courseorid->id
== SITEID
)
3148 or (!is_object($courseorid) and $courseorid == SITEID
));
3149 if ($issite && !empty($cm) && !($cm instanceof cm_info
)) {
3150 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3151 // db queries so this is not really a performance concern, however it is obviously
3152 // better if you use get_fast_modinfo to get the cm before calling this.
3153 if (is_object($courseorid)) {
3154 $course = $courseorid;
3156 $course = clone($SITE);
3158 $modinfo = get_fast_modinfo($course);
3159 $cm = $modinfo->get_cm($cm->id
);
3161 if (!empty($CFG->forcelogin
)) {
3162 // Login required for both SITE and courses.
3163 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3165 } else if ($issite && !empty($cm) and !$cm->uservisible
) {
3166 // Always login for hidden activities.
3167 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3169 } else if (isloggedin() && !isguestuser()) {
3170 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3171 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3173 } else if ($issite) {
3174 // Login for SITE not required.
3175 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3176 if (!empty($courseorid)) {
3177 if (is_object($courseorid)) {
3178 $course = $courseorid;
3180 $course = clone $SITE;
3183 if ($cm->course
!= $course->id
) {
3184 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3186 $PAGE->set_cm($cm, $course);
3187 $PAGE->set_pagelayout('incourse');
3189 $PAGE->set_course($course);
3192 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3193 $PAGE->set_course($PAGE->course
);
3195 // Do not update access time for webservice or ajax requests.
3196 if (!WS_SERVER
&& !AJAX_SCRIPT
) {
3197 user_accesstime_log(SITEID
);
3202 // Course login always required.
3203 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3208 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3210 * @param string $keyvalue the key value
3211 * @param string $script unique script identifier
3212 * @param int $instance instance id
3213 * @return stdClass the key entry in the user_private_key table
3215 * @throws moodle_exception
3217 function validate_user_key($keyvalue, $script, $instance) {
3220 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3221 print_error('invalidkey');
3224 if (!empty($key->validuntil
) and $key->validuntil
< time()) {
3225 print_error('expiredkey');
3228 if ($key->iprestriction
) {
3229 $remoteaddr = getremoteaddr(null);
3230 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction
)) {
3231 print_error('ipmismatch');
3238 * Require key login. Function terminates with error if key not found or incorrect.
3240 * @uses NO_MOODLE_COOKIES
3241 * @uses PARAM_ALPHANUM
3242 * @param string $script unique script identifier
3243 * @param int $instance optional instance id
3244 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3245 * @return int Instance ID
3247 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3250 if (!NO_MOODLE_COOKIES
) {
3251 print_error('sessioncookiesdisable');
3255 \core\session\manager
::write_close();
3257 if (null === $keyvalue) {
3258 $keyvalue = required_param('key', PARAM_ALPHANUM
);
3261 $key = validate_user_key($keyvalue, $script, $instance);
3263 if (!$user = $DB->get_record('user', array('id' => $key->userid
))) {
3264 print_error('invaliduserid');
3267 core_user
::require_active_user($user, true, true);
3269 // Emulate normal session.
3270 enrol_check_plugins($user);
3271 \core\session\manager
::set_user($user);
3273 // Note we are not using normal login.
3274 if (!defined('USER_KEY_LOGIN')) {
3275 define('USER_KEY_LOGIN', true);
3278 // Return instance id - it might be empty.
3279 return $key->instance
;
3283 * Creates a new private user access key.
3285 * @param string $script unique target identifier
3286 * @param int $userid
3287 * @param int $instance optional instance id
3288 * @param string $iprestriction optional ip restricted access
3289 * @param int $validuntil key valid only until given data
3290 * @return string access key value
3292 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3295 $key = new stdClass();
3296 $key->script
= $script;
3297 $key->userid
= $userid;
3298 $key->instance
= $instance;
3299 $key->iprestriction
= $iprestriction;
3300 $key->validuntil
= $validuntil;
3301 $key->timecreated
= time();
3303 // Something long and unique.
3304 $key->value
= md5($userid.'_'.time().random_string(40));
3305 while ($DB->record_exists('user_private_key', array('value' => $key->value
))) {
3307 $key->value
= md5($userid.'_'.time().random_string(40));
3309 $DB->insert_record('user_private_key', $key);
3314 * Delete the user's new private user access keys for a particular script.
3316 * @param string $script unique target identifier
3317 * @param int $userid
3320 function delete_user_key($script, $userid) {
3322 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3326 * Gets a private user access key (and creates one if one doesn't exist).
3328 * @param string $script unique target identifier
3329 * @param int $userid
3330 * @param int $instance optional instance id
3331 * @param string $iprestriction optional ip restricted access
3332 * @param int $validuntil key valid only until given date
3333 * @return string access key value
3335 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3338 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3339 'instance' => $instance, 'iprestriction' => $iprestriction,
3340 'validuntil' => $validuntil))) {
3343 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3349 * Modify the user table by setting the currently logged in user's last login to now.
3351 * @return bool Always returns true
3353 function update_user_login_times() {
3354 global $USER, $DB, $SESSION;
3356 if (isguestuser()) {
3357 // Do not update guest access times/ips for performance.
3363 $user = new stdClass();
3364 $user->id
= $USER->id
;
3366 // Make sure all users that logged in have some firstaccess.
3367 if ($USER->firstaccess
== 0) {
3368 $USER->firstaccess
= $user->firstaccess
= $now;
3371 // Store the previous current as lastlogin.
3372 $USER->lastlogin
= $user->lastlogin
= $USER->currentlogin
;
3374 $USER->currentlogin
= $user->currentlogin
= $now;
3376 // Function user_accesstime_log() may not update immediately, better do it here.
3377 $USER->lastaccess
= $user->lastaccess
= $now;
3378 $SESSION->userpreviousip
= $USER->lastip
;
3379 $USER->lastip
= $user->lastip
= getremoteaddr();
3381 // Note: do not call user_update_user() here because this is part of the login process,
3382 // the login event means that these fields were updated.
3383 $DB->update_record('user', $user);
3388 * Determines if a user has completed setting up their account.
3390 * The lax mode (with $strict = false) has been introduced for special cases
3391 * only where we want to skip certain checks intentionally. This is valid in
3392 * certain mnet or ajax scenarios when the user cannot / should not be
3393 * redirected to edit their profile. In most cases, you should perform the
3396 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3397 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3400 function user_not_fully_set_up($user, $strict = true) {
3402 require_once($CFG->dirroot
.'/user/profile/lib.php');
3404 if (isguestuser($user)) {
3408 if (empty($user->firstname
) or empty($user->lastname
) or empty($user->email
) or over_bounce_threshold($user)) {
3413 if (empty($user->id
)) {
3414 // Strict mode can be used with existing accounts only.
3417 if (!profile_has_required_custom_fields_set($user->id
)) {
3426 * Check whether the user has exceeded the bounce threshold
3428 * @param stdClass $user A {@link $USER} object
3429 * @return bool true => User has exceeded bounce threshold
3431 function over_bounce_threshold($user) {
3434 if (empty($CFG->handlebounces
)) {
3438 if (empty($user->id
)) {
3439 // No real (DB) user, nothing to do here.
3443 // Set sensible defaults.
3444 if (empty($CFG->minbounces
)) {
3445 $CFG->minbounces
= 10;
3447 if (empty($CFG->bounceratio
)) {
3448 $CFG->bounceratio
= .20;
3452 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id
, 'name' => 'email_bounce_count'))) {
3453 $bouncecount = $bounce->value
;
3455 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_send_count'))) {
3456 $sendcount = $send->value
;
3458 return ($bouncecount >= $CFG->minbounces
&& $bouncecount/$sendcount >= $CFG->bounceratio
);
3462 * Used to increment or reset email sent count
3464 * @param stdClass $user object containing an id
3465 * @param bool $reset will reset the count to 0
3468 function set_send_count($user, $reset=false) {
3471 if (empty($user->id
)) {
3472 // No real (DB) user, nothing to do here.
3476 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_send_count'))) {
3477 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3478 $DB->update_record('user_preferences', $pref);
3479 } else if (!empty($reset)) {
3480 // If it's not there and we're resetting, don't bother. Make a new one.
3481 $pref = new stdClass();
3482 $pref->name
= 'email_send_count';
3484 $pref->userid
= $user->id
;
3485 $DB->insert_record('user_preferences', $pref, false);
3490 * Increment or reset user's email bounce count
3492 * @param stdClass $user object containing an id
3493 * @param bool $reset will reset the count to 0
3495 function set_bounce_count($user, $reset=false) {
3498 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_bounce_count'))) {
3499 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3500 $DB->update_record('user_preferences', $pref);
3501 } else if (!empty($reset)) {
3502 // If it's not there and we're resetting, don't bother. Make a new one.
3503 $pref = new stdClass();
3504 $pref->name
= 'email_bounce_count';
3506 $pref->userid
= $user->id
;
3507 $DB->insert_record('user_preferences', $pref, false);
3512 * Determines if the logged in user is currently moving an activity
3514 * @param int $courseid The id of the course being tested
3517 function ismoving($courseid) {
3520 if (!empty($USER->activitycopy
)) {
3521 return ($USER->activitycopycourse
== $courseid);
3527 * Returns a persons full name
3529 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3530 * The result may depend on system settings or language. 'override' will force the alternativefullnameformat to be used. In
3531 * English, fullname as well as alternativefullnameformat is set to 'firstname lastname' by default. But you could have
3532 * fullname set to 'firstname lastname' and alternativefullnameformat set to 'firstname middlename alternatename lastname'.
3534 * @param stdClass $user A {@link $USER} object to get full name of.
3535 * @param bool $override If true then the alternativefullnameformat format rather than fullnamedisplay format will be used.
3538 function fullname($user, $override=false) {
3539 global $CFG, $SESSION;
3541 if (!isset($user->firstname
) and !isset($user->lastname
)) {
3545 // Get all of the name fields.
3546 $allnames = \core_user\fields
::get_name_fields();
3547 if ($CFG->debugdeveloper
) {
3548 foreach ($allnames as $allname) {
3549 if (!property_exists($user, $allname)) {
3550 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3551 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER
);
3552 // Message has been sent, no point in sending the message multiple times.
3559 if (!empty($CFG->forcefirstname
)) {
3560 $user->firstname
= $CFG->forcefirstname
;
3562 if (!empty($CFG->forcelastname
)) {
3563 $user->lastname
= $CFG->forcelastname
;
3567 if (!empty($SESSION->fullnamedisplay
)) {
3568 $CFG->fullnamedisplay
= $SESSION->fullnamedisplay
;
3572 // If the fullnamedisplay setting is available, set the template to that.
3573 if (isset($CFG->fullnamedisplay
)) {
3574 $template = $CFG->fullnamedisplay
;
3576 // If the template is empty, or set to language, return the language string.
3577 if ((empty($template) ||
$template == 'language') && !$override) {
3578 return get_string('fullnamedisplay', null, $user);
3581 // Check to see if we are displaying according to the alternative full name format.
3583 if (empty($CFG->alternativefullnameformat
) ||
$CFG->alternativefullnameformat
== 'language') {
3584 // Default to show just the user names according to the fullnamedisplay string.
3585 return get_string('fullnamedisplay', null, $user);
3587 // If the override is true, then change the template to use the complete name.
3588 $template = $CFG->alternativefullnameformat
;
3592 $requirednames = array();
3593 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3594 foreach ($allnames as $allname) {
3595 if (strpos($template, $allname) !== false) {
3596 $requirednames[] = $allname;
3600 $displayname = $template;
3601 // Switch in the actual data into the template.
3602 foreach ($requirednames as $altname) {
3603 if (isset($user->$altname)) {
3604 // Using empty() on the below if statement causes breakages.
3605 if ((string)$user->$altname == '') {
3606 $displayname = str_replace($altname, 'EMPTY', $displayname);
3608 $displayname = str_replace($altname, $user->$altname, $displayname);
3611 $displayname = str_replace($altname, 'EMPTY', $displayname);
3614 // Tidy up any misc. characters (Not perfect, but gets most characters).
3615 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3616 // katakana and parenthesis.
3617 $patterns = array();
3618 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3619 // filled in by a user.
3620 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3621 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3622 // This regular expression is to remove any double spaces in the display name.
3623 $patterns[] = '/\s{2,}/u';
3624 foreach ($patterns as $pattern) {
3625 $displayname = preg_replace($pattern, ' ', $displayname);
3628 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3629 $displayname = trim($displayname);
3630 if (empty($displayname)) {
3631 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3632 // people in general feel is a good setting to fall back on.
3633 $displayname = $user->firstname
;
3635 return $displayname;
3639 * Reduces lines of duplicated code for getting user name fields.
3641 * See also {@link user_picture::unalias()}
3643 * @param object $addtoobject Object to add user name fields to.
3644 * @param object $secondobject Object that contains user name field information.
3645 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3646 * @param array $additionalfields Additional fields to be matched with data in the second object.
3647 * The key can be set to the user table field name.
3648 * @return object User name fields.
3650 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3652 foreach (\core_user\fields
::get_name_fields() as $field) {
3653 $fields[$field] = $prefix . $field;
3655 if ($additionalfields) {
3656 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3657 // the key is a number and then sets the key to the array value.
3658 foreach ($additionalfields as $key => $value) {
3659 if (is_numeric($key)) {
3660 $additionalfields[$value] = $prefix . $value;
3661 unset($additionalfields[$key]);
3663 $additionalfields[$key] = $prefix . $value;
3666 $fields = array_merge($fields, $additionalfields);
3668 foreach ($fields as $key => $field) {
3669 // Important that we have all of the user name fields present in the object that we are sending back.
3670 $addtoobject->$key = '';
3671 if (isset($secondobject->$field)) {
3672 $addtoobject->$key = $secondobject->$field;
3675 return $addtoobject;
3679 * Returns an array of values in order of occurance in a provided string.
3680 * The key in the result is the character postion in the string.
3682 * @param array $values Values to be found in the string format
3683 * @param string $stringformat The string which may contain values being searched for.
3684 * @return array An array of values in order according to placement in the string format.
3686 function order_in_string($values, $stringformat) {
3687 $valuearray = array();
3688 foreach ($values as $value) {
3689 $pattern = "/$value\b/";
3690 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3691 if (preg_match($pattern, $stringformat)) {
3692 $replacement = "thing";
3693 // Replace the value with something more unique to ensure we get the right position when using strpos().
3694 $newformat = preg_replace($pattern, $replacement, $stringformat);
3695 $position = strpos($newformat, $replacement);
3696 $valuearray[$position] = $value;
3704 * Returns whether a given authentication plugin exists.
3706 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3707 * @return boolean Whether the plugin is available.
3709 function exists_auth_plugin($auth) {
3712 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3713 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3719 * Checks if a given plugin is in the list of enabled authentication plugins.
3721 * @param string $auth Authentication plugin.
3722 * @return boolean Whether the plugin is enabled.
3724 function is_enabled_auth($auth) {
3729 $enabled = get_enabled_auth_plugins();
3731 return in_array($auth, $enabled);
3735 * Returns an authentication plugin instance.
3737 * @param string $auth name of authentication plugin
3738 * @return auth_plugin_base An instance of the required authentication plugin.
3740 function get_auth_plugin($auth) {
3743 // Check the plugin exists first.
3744 if (! exists_auth_plugin($auth)) {
3745 print_error('authpluginnotfound', 'debug', '', $auth);
3748 // Return auth plugin instance.
3749 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3750 $class = "auth_plugin_$auth";
3755 * Returns array of active auth plugins.
3757 * @param bool $fix fix $CFG->auth if needed. Only set if logged in as admin.
3760 function get_enabled_auth_plugins($fix=false) {
3763 $default = array('manual', 'nologin');
3765 if (empty($CFG->auth
)) {
3768 $auths = explode(',', $CFG->auth
);
3771 $auths = array_unique($auths);
3772 $oldauthconfig = implode(',', $auths);
3773 foreach ($auths as $k => $authname) {
3774 if (in_array($authname, $default)) {
3775 // The manual and nologin plugin never need to be stored.
3777 } else if (!exists_auth_plugin($authname)) {
3778 debugging(get_string('authpluginnotfound', 'debug', $authname));
3783 // Ideally only explicit interaction from a human admin should trigger a
3784 // change in auth config, see MDL-70424 for details.
3786 $newconfig = implode(',', $auths);
3787 if (!isset($CFG->auth
) or $newconfig != $CFG->auth
) {
3788 add_to_config_log('auth', $oldauthconfig, $newconfig, 'core');
3789 set_config('auth', $newconfig);
3793 return (array_merge($default, $auths));
3797 * Returns true if an internal authentication method is being used.
3798 * if method not specified then, global default is assumed
3800 * @param string $auth Form of authentication required
3803 function is_internal_auth($auth) {
3804 // Throws error if bad $auth.
3805 $authplugin = get_auth_plugin($auth);
3806 return $authplugin->is_internal();
3810 * Returns true if the user is a 'restored' one.
3812 * Used in the login process to inform the user and allow him/her to reset the password
3814 * @param string $username username to be checked
3817 function is_restored_user($username) {
3820 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'password' => 'restored'));
3824 * Returns an array of user fields
3826 * @return array User field/column names
3828 function get_user_fieldnames() {
3831 $fieldarray = $DB->get_columns('user');
3832 unset($fieldarray['id']);
3833 $fieldarray = array_keys($fieldarray);
3839 * Returns the string of the language for the new user.
3841 * @return string language for the new user
3843 function get_newuser_language() {
3844 global $CFG, $SESSION;
3845 return (!empty($CFG->autolangusercreation
) && !empty($SESSION->lang
)) ?
$SESSION->lang
: $CFG->lang
;
3849 * Creates a bare-bones user record
3851 * @todo Outline auth types and provide code example
3853 * @param string $username New user's username to add to record
3854 * @param string $password New user's password to add to record
3855 * @param string $auth Form of authentication required
3856 * @return stdClass A complete user object
3858 function create_user_record($username, $password, $auth = 'manual') {
3859 global $CFG, $DB, $SESSION;
3860 require_once($CFG->dirroot
.'/user/profile/lib.php');
3861 require_once($CFG->dirroot
.'/user/lib.php');
3863 // Just in case check text case.
3864 $username = trim(core_text
::strtolower($username));
3866 $authplugin = get_auth_plugin($auth);
3867 $customfields = $authplugin->get_custom_user_profile_fields();
3868 $newuser = new stdClass();
3869 if ($newinfo = $authplugin->get_userinfo($username)) {
3870 $newinfo = truncate_userinfo($newinfo);
3871 foreach ($newinfo as $key => $value) {
3872 if (in_array($key, $authplugin->userfields
) ||
(in_array($key, $customfields))) {
3873 $newuser->$key = $value;
3878 if (!empty($newuser->email
)) {
3879 if (email_is_not_allowed($newuser->email
)) {
3880 unset($newuser->email
);
3884 if (!isset($newuser->city
)) {
3885 $newuser->city
= '';
3888 $newuser->auth
= $auth;
3889 $newuser->username
= $username;
3892 // user CFG lang for user if $newuser->lang is empty
3893 // or $user->lang is not an installed language.
3894 if (empty($newuser->lang
) ||
!get_string_manager()->translation_exists($newuser->lang
)) {
3895 $newuser->lang
= get_newuser_language();
3897 $newuser->confirmed
= 1;
3898 $newuser->lastip
= getremoteaddr();
3899 $newuser->timecreated
= time();
3900 $newuser->timemodified
= $newuser->timecreated
;
3901 $newuser->mnethostid
= $CFG->mnet_localhost_id
;
3903 $newuser->id
= user_create_user($newuser, false, false);
3905 // Save user profile data.
3906 profile_save_data($newuser);
3908 $user = get_complete_user_data('id', $newuser->id
);
3909 if (!empty($CFG->{'auth_'.$newuser->auth
.'_forcechangepassword'})) {
3910 set_user_preference('auth_forcepasswordchange', 1, $user);
3912 // Set the password.
3913 update_internal_user_password($user, $password);
3916 \core\event\user_created
::create_from_userid($newuser->id
)->trigger();
3922 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3924 * @param string $username user's username to update the record
3925 * @return stdClass A complete user object
3927 function update_user_record($username) {
3929 // Just in case check text case.
3930 $username = trim(core_text
::strtolower($username));
3932 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
), '*', MUST_EXIST
);
3933 return update_user_record_by_id($oldinfo->id
);
3937 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3939 * @param int $id user id
3940 * @return stdClass A complete user object
3942 function update_user_record_by_id($id) {
3944 require_once($CFG->dirroot
."/user/profile/lib.php");
3945 require_once($CFG->dirroot
.'/user/lib.php');
3947 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'id' => $id, 'deleted' => 0);
3948 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST
);
3951 $userauth = get_auth_plugin($oldinfo->auth
);
3953 if ($newinfo = $userauth->get_userinfo($oldinfo->username
)) {
3954 $newinfo = truncate_userinfo($newinfo);
3955 $customfields = $userauth->get_custom_user_profile_fields();
3957 foreach ($newinfo as $key => $value) {
3958 $iscustom = in_array($key, $customfields);
3960 $key = strtolower($key);
3962 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3963 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3964 // Unknown or must not be changed.
3967 if (empty($userauth->config
->{'field_updatelocal_' . $key}) ||
empty($userauth->config
->{'field_lock_' . $key})) {
3970 $confval = $userauth->config
->{'field_updatelocal_' . $key};
3971 $lockval = $userauth->config
->{'field_lock_' . $key};
3972 if ($confval === 'onlogin') {
3973 // MDL-4207 Don't overwrite modified user profile values with
3974 // empty LDAP values when 'unlocked if empty' is set. The purpose
3975 // of the setting 'unlocked if empty' is to allow the user to fill
3976 // in a value for the selected field _if LDAP is giving
3977 // nothing_ for this field. Thus it makes sense to let this value
3978 // stand in until LDAP is giving a value for this field.
3979 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3980 if ($iscustom ||
(in_array($key, $userauth->userfields
) &&
3981 ((string)$oldinfo->$key !== (string)$value))) {
3982 $newuser[$key] = (string)$value;
3988 $newuser['id'] = $oldinfo->id
;
3989 $newuser['timemodified'] = time();
3990 user_update_user((object) $newuser, false, false);
3992 // Save user profile data.
3993 profile_save_data((object) $newuser);
3996 \core\event\user_updated
::create_from_userid($newuser['id'])->trigger();
4000 return get_complete_user_data('id', $oldinfo->id
);
4004 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4006 * @param array $info Array of user properties to truncate if needed
4007 * @return array The now truncated information that was passed in
4009 function truncate_userinfo(array $info) {
4010 // Define the limits.
4019 'institution' => 255,
4020 'department' => 255,
4026 // Apply where needed.
4027 foreach (array_keys($info) as $key) {
4028 if (!empty($limit[$key])) {
4029 $info[$key] = trim(core_text
::substr($info[$key], 0, $limit[$key]));
4037 * Marks user deleted in internal user database and notifies the auth plugin.
4038 * Also unenrols user from all roles and does other cleanup.
4040 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4042 * @param stdClass $user full user object before delete
4043 * @return boolean success
4044 * @throws coding_exception if invalid $user parameter detected
4046 function delete_user(stdClass
$user) {
4047 global $CFG, $DB, $SESSION;
4048 require_once($CFG->libdir
.'/grouplib.php');
4049 require_once($CFG->libdir
.'/gradelib.php');
4050 require_once($CFG->dirroot
.'/message/lib.php');
4051 require_once($CFG->dirroot
.'/user/lib.php');
4053 // Make sure nobody sends bogus record type as parameter.
4054 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4055 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4058 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4059 if (!$user = $DB->get_record('user', array('id' => $user->id
))) {
4060 debugging('Attempt to delete unknown user account.');
4064 // There must be always exactly one guest record, originally the guest account was identified by username only,
4065 // now we use $CFG->siteguest for performance reasons.
4066 if ($user->username
=== 'guest' or isguestuser($user)) {
4067 debugging('Guest user account can not be deleted.');
4071 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4072 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4073 if ($user->auth
=== 'manual' and is_siteadmin($user)) {
4074 debugging('Local administrator accounts can not be deleted.');
4078 // Allow plugins to use this user object before we completely delete it.
4079 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4080 foreach ($pluginsfunction as $plugintype => $plugins) {
4081 foreach ($plugins as $pluginfunction) {
4082 $pluginfunction($user);
4087 // Keep user record before updating it, as we have to pass this to user_deleted event.
4088 $olduser = clone $user;
4090 // Keep a copy of user context, we need it for event.
4091 $usercontext = context_user
::instance($user->id
);
4093 // Delete all grades - backup is kept in grade_grades_history table.
4094 grade_user_delete($user->id
);
4096 // TODO: remove from cohorts using standard API here.
4098 // Remove user tags.
4099 core_tag_tag
::remove_all_item_tags('core', 'user', $user->id
);
4101 // Unconditionally unenrol from all courses.
4102 enrol_user_delete($user);
4104 // Unenrol from all roles in all contexts.
4105 // This might be slow but it is really needed - modules might do some extra cleanup!
4106 role_unassign_all(array('userid' => $user->id
));
4108 // Notify the competency subsystem.
4109 \core_competency\api
::hook_user_deleted($user->id
);
4111 // Now do a brute force cleanup.
4113 // Delete all user events and subscription events.
4114 $DB->delete_records_select('event', 'userid = :userid AND subscriptionid IS NOT NULL', ['userid' => $user->id
]);
4116 // Now, delete all calendar subscription from the user.
4117 $DB->delete_records('event_subscriptions', ['userid' => $user->id
]);
4119 // Remove from all cohorts.
4120 $DB->delete_records('cohort_members', array('userid' => $user->id
));
4122 // Remove from all groups.
4123 $DB->delete_records('groups_members', array('userid' => $user->id
));
4125 // Brute force unenrol from all courses.
4126 $DB->delete_records('user_enrolments', array('userid' => $user->id
));
4128 // Purge user preferences.
4129 $DB->delete_records('user_preferences', array('userid' => $user->id
));
4131 // Purge user extra profile info.
4132 $DB->delete_records('user_info_data', array('userid' => $user->id
));
4134 // Purge log of previous password hashes.
4135 $DB->delete_records('user_password_history', array('userid' => $user->id
));
4137 // Last course access not necessary either.
4138 $DB->delete_records('user_lastaccess', array('userid' => $user->id
));
4139 // Remove all user tokens.
4140 $DB->delete_records('external_tokens', array('userid' => $user->id
));
4142 // Unauthorise the user for all services.
4143 $DB->delete_records('external_services_users', array('userid' => $user->id
));
4145 // Remove users private keys.
4146 $DB->delete_records('user_private_key', array('userid' => $user->id
));
4148 // Remove users customised pages.
4149 $DB->delete_records('my_pages', array('userid' => $user->id
, 'private' => 1));
4151 // Remove user's oauth2 refresh tokens, if present.
4152 $DB->delete_records('oauth2_refresh_token', array('userid' => $user->id
));
4154 // Delete user from $SESSION->bulk_users.
4155 if (isset($SESSION->bulk_users
[$user->id
])) {
4156 unset($SESSION->bulk_users
[$user->id
]);
4159 // Force logout - may fail if file based sessions used, sorry.
4160 \core\session\manager
::kill_user_sessions($user->id
);
4162 // Generate username from email address, or a fake email.
4163 $delemail = !empty($user->email
) ?
$user->email
: $user->username
. '.' . $user->id
. '@unknownemail.invalid';
4166 $deltimelength = core_text
::strlen((string) $deltime);
4168 // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
4169 $delname = clean_param($delemail, PARAM_USERNAME
);
4170 $delname = core_text
::substr($delname, 0, 100 - ($deltimelength +
1)) . ".{$deltime}";
4172 // Workaround for bulk deletes of users with the same email address.
4173 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4177 // Mark internal user record as "deleted".
4178 $updateuser = new stdClass();
4179 $updateuser->id
= $user->id
;
4180 $updateuser->deleted
= 1;
4181 $updateuser->username
= $delname; // Remember it just in case.
4182 $updateuser->email
= md5($user->username
);// Store hash of username, useful importing/restoring users.
4183 $updateuser->idnumber
= ''; // Clear this field to free it up.
4184 $updateuser->picture
= 0;
4185 $updateuser->timemodified
= $deltime;
4187 // Don't trigger update event, as user is being deleted.
4188 user_update_user($updateuser, false, false);
4190 // Delete all content associated with the user context, but not the context itself.
4191 $usercontext->delete_content();
4193 // Delete any search data.
4194 \core_search\manager
::context_deleted($usercontext);
4196 // Any plugin that needs to cleanup should register this event.
4198 $event = \core\event\user_deleted
::create(
4200 'objectid' => $user->id
,
4201 'relateduserid' => $user->id
,
4202 'context' => $usercontext,
4204 'username' => $user->username
,
4205 'email' => $user->email
,
4206 'idnumber' => $user->idnumber
,
4207 'picture' => $user->picture
,
4208 'mnethostid' => $user->mnethostid
4212 $event->add_record_snapshot('user', $olduser);
4215 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4216 // should know about this updated property persisted to the user's table.
4217 $user->timemodified
= $updateuser->timemodified
;
4219 // Notify auth plugin - do not block the delete even when plugin fails.
4220 $authplugin = get_auth_plugin($user->auth
);
4221 $authplugin->user_delete($user);
4227 * Retrieve the guest user object.
4229 * @return stdClass A {@link $USER} object
4231 function guest_user() {
4234 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest
))) {
4235 $newuser->confirmed
= 1;
4236 $newuser->lang
= get_newuser_language();
4237 $newuser->lastip
= getremoteaddr();
4244 * Authenticates a user against the chosen authentication mechanism
4246 * Given a username and password, this function looks them
4247 * up using the currently selected authentication mechanism,
4248 * and if the authentication is successful, it returns a
4249 * valid $user object from the 'user' table.
4251 * Uses auth_ functions from the currently active auth module
4253 * After authenticate_user_login() returns success, you will need to
4254 * log that the user has logged in, and call complete_user_login() to set
4257 * Note: this function works only with non-mnet accounts!
4259 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4260 * @param string $password User's password
4261 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4262 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4263 * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4264 * @return stdClass|false A {@link $USER} object or false if error
4266 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4267 global $CFG, $DB, $PAGE;
4268 require_once("$CFG->libdir/authlib.php");
4270 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id
)) {
4271 // we have found the user
4273 } else if (!empty($CFG->authloginviaemail
)) {
4274 if ($email = clean_param($username, PARAM_EMAIL
)) {
4275 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4276 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'email' => $email);
4277 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4278 if (count($users) === 1) {
4279 // Use email for login only if unique.
4280 $user = reset($users);
4281 $user = get_complete_user_data('id', $user->id
);
4282 $username = $user->username
;
4288 // Make sure this request came from the login form.
4289 if (!\core\session\manager
::validate_login_token($logintoken)) {
4290 $failurereason = AUTH_LOGIN_FAILED
;
4292 // Trigger login failed event (specifying the ID of the found user, if available).
4293 \core\event\user_login_failed
::create([
4294 'userid' => ($user->id ??
0),
4296 'username' => $username,
4297 'reason' => $failurereason,
4301 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4305 $authsenabled = get_enabled_auth_plugins();
4308 // Use manual if auth not set.
4309 $auth = empty($user->auth
) ?
'manual' : $user->auth
;
4311 if (in_array($user->auth
, $authsenabled)) {
4312 $authplugin = get_auth_plugin($user->auth
);
4313 $authplugin->pre_user_login_hook($user);
4316 if (!empty($user->suspended
)) {
4317 $failurereason = AUTH_LOGIN_SUSPENDED
;
4319 // Trigger login failed event.
4320 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4321 'other' => array('username' => $username, 'reason' => $failurereason)));
4323 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4326 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4327 // Legacy way to suspend user.
4328 $failurereason = AUTH_LOGIN_SUSPENDED
;
4330 // Trigger login failed event.
4331 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4332 'other' => array('username' => $username, 'reason' => $failurereason)));
4334 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4337 $auths = array($auth);
4340 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4341 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'deleted' => 1))) {
4342 $failurereason = AUTH_LOGIN_NOUSER
;
4344 // Trigger login failed event.
4345 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4346 'reason' => $failurereason)));
4348 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4352 // User does not exist.
4353 $auths = $authsenabled;
4354 $user = new stdClass();
4358 if ($ignorelockout) {
4359 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4360 // or this function is called from a SSO script.
4361 } else if ($user->id
) {
4362 // Verify login lockout after other ways that may prevent user login.
4363 if (login_is_lockedout($user)) {
4364 $failurereason = AUTH_LOGIN_LOCKOUT
;
4366 // Trigger login failed event.
4367 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4368 'other' => array('username' => $username, 'reason' => $failurereason)));
4371 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4375 // We can not lockout non-existing accounts.
4378 foreach ($auths as $auth) {
4379 $authplugin = get_auth_plugin($auth);
4381 // On auth fail fall through to the next plugin.
4382 if (!$authplugin->user_login($username, $password)) {
4386 // Before performing login actions, check if user still passes password policy, if admin setting is enabled.
4387 if (!empty($CFG->passwordpolicycheckonlogin
)) {
4389 $passed = check_password_policy($password, $errmsg, $user);
4391 // First trigger event for failure.
4392 $failedevent = \core\event\user_password_policy_failed
::create_from_user($user);
4393 $failedevent->trigger();
4395 // If able to change password, set flag and move on.
4396 if ($authplugin->can_change_password()) {
4397 // Check if we are on internal change password page, or service is external, don't show notification.
4398 $internalchangeurl = new moodle_url('/login/change_password.php');
4399 if (!($PAGE->has_set_url() && $internalchangeurl->compare($PAGE->url
)) && $authplugin->is_internal()) {
4400 \core\notification
::error(get_string('passwordpolicynomatch', '', $errmsg));
4402 set_user_preference('auth_forcepasswordchange', 1, $user);
4403 } else if ($authplugin->can_reset_password()) {
4404 // Else force a reset if possible.
4405 \core\notification
::error(get_string('forcepasswordresetnotice', '', $errmsg));
4406 redirect(new moodle_url('/login/forgot_password.php'));
4408 $notifymsg = get_string('forcepasswordresetfailurenotice', '', $errmsg);
4409 // If support page is set, add link for help.
4410 if (!empty($CFG->supportpage
)) {
4411 $link = \html_writer
::link($CFG->supportpage
, $CFG->supportpage
);
4412 $link = \html_writer
::tag('p', $link);
4413 $notifymsg .= $link;
4416 // If no change or reset is possible, add a notification for user.
4417 \core\notification
::error($notifymsg);
4422 // Successful authentication.
4424 // User already exists in database.
4425 if (empty($user->auth
)) {
4426 // For some reason auth isn't set yet.
4427 $DB->set_field('user', 'auth', $auth, array('id' => $user->id
));
4428 $user->auth
= $auth;
4431 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4432 // the current hash algorithm while we have access to the user's password.
4433 update_internal_user_password($user, $password);
4435 if ($authplugin->is_synchronised_with_external()) {
4436 // Update user record from external DB.
4437 $user = update_user_record_by_id($user->id
);
4440 // The user is authenticated but user creation may be disabled.
4441 if (!empty($CFG->authpreventaccountcreation
)) {
4442 $failurereason = AUTH_LOGIN_UNAUTHORISED
;
4444 // Trigger login failed event.
4445 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4446 'reason' => $failurereason)));
4449 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4450 $_SERVER['HTTP_USER_AGENT']);
4453 $user = create_user_record($username, $password, $auth);
4457 $authplugin->sync_roles($user);
4459 foreach ($authsenabled as $hau) {
4460 $hauth = get_auth_plugin($hau);
4461 $hauth->user_authenticated_hook($user, $username, $password);
4464 if (empty($user->id
)) {
4465 $failurereason = AUTH_LOGIN_NOUSER
;
4466 // Trigger login failed event.
4467 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4468 'reason' => $failurereason)));
4473 if (!empty($user->suspended
)) {
4474 // Just in case some auth plugin suspended account.
4475 $failurereason = AUTH_LOGIN_SUSPENDED
;
4476 // Trigger login failed event.
4477 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4478 'other' => array('username' => $username, 'reason' => $failurereason)));
4480 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4484 login_attempt_valid($user);
4485 $failurereason = AUTH_LOGIN_OK
;
4489 // Failed if all the plugins have failed.
4490 if (debugging('', DEBUG_ALL
)) {
4491 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4495 login_attempt_failed($user);
4496 $failurereason = AUTH_LOGIN_FAILED
;
4497 // Trigger login failed event.
4498 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4499 'other' => array('username' => $username, 'reason' => $failurereason)));
4502 $failurereason = AUTH_LOGIN_NOUSER
;
4503 // Trigger login failed event.
4504 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4505 'reason' => $failurereason)));
4513 * Call to complete the user login process after authenticate_user_login()
4514 * has succeeded. It will setup the $USER variable and other required bits
4518 * - It will NOT log anything -- up to the caller to decide what to log.
4519 * - this function does not set any cookies any more!
4521 * @param stdClass $user
4522 * @return stdClass A {@link $USER} object - BC only, do not use
4524 function complete_user_login($user) {
4525 global $CFG, $DB, $USER, $SESSION;
4527 \core\session\manager
::login_user($user);
4529 // Reload preferences from DB.
4530 unset($USER->preference
);
4531 check_user_preferences_loaded($USER);
4533 // Update login times.
4534 update_user_login_times();
4536 // Extra session prefs init.
4537 set_login_session_preferences();
4539 // Trigger login event.
4540 $event = \core\event\user_loggedin
::create(
4542 'userid' => $USER->id
,
4543 'objectid' => $USER->id
,
4544 'other' => array('username' => $USER->username
),
4549 // Check if the user is using a new browser or session (a new MoodleSession cookie is set in that case).
4550 // If the user is accessing from the same IP, ignore everything (most of the time will be a new session in the same browser).
4551 // Skip Web Service requests, CLI scripts, AJAX scripts, and request from the mobile app itself.
4552 $loginip = getremoteaddr();
4553 $isnewip = isset($SESSION->userpreviousip
) && $SESSION->userpreviousip
!= $loginip;
4554 $isvalidenv = (!WS_SERVER
&& !CLI_SCRIPT
&& !NO_MOODLE_COOKIES
) || PHPUNIT_TEST
;
4556 if (!empty($SESSION->isnewsessioncookie
) && $isnewip && $isvalidenv && !\core_useragent
::is_moodle_app()) {
4558 $logintime = time();
4559 $ismoodleapp = false;
4560 $useragent = \core_useragent
::get_user_agent_string();
4562 // Schedule adhoc task to sent a login notification to the user.
4563 $task = new \core\task\
send_login_notifications();
4564 $task->set_userid($USER->id
);
4565 $task->set_custom_data(compact('ismoodleapp', 'useragent', 'loginip', 'logintime'));
4566 $task->set_component('core');
4567 \core\task\manager
::queue_adhoc_task($task);
4570 // Queue migrating the messaging data, if we need to.
4571 if (!get_user_preferences('core_message_migrate_data', false, $USER->id
)) {
4572 // Check if there are any legacy messages to migrate.
4573 if (\core_message\helper
::legacy_messages_exist($USER->id
)) {
4574 \core_message\task\migrate_message_data
::queue_task($USER->id
);
4576 set_user_preference('core_message_migrate_data', true, $USER->id
);
4580 if (isguestuser()) {
4581 // No need to continue when user is THE guest.
4586 // We can redirect to password change URL only in browser.
4590 // Select password change url.
4591 $userauth = get_auth_plugin($USER->auth
);
4593 // Check whether the user should be changing password.
4594 if (get_user_preferences('auth_forcepasswordchange', false)) {
4595 if ($userauth->can_change_password()) {
4596 if ($changeurl = $userauth->change_password_url()) {
4597 redirect($changeurl);
4599 require_once($CFG->dirroot
. '/login/lib.php');
4600 $SESSION->wantsurl
= core_login_get_return_url();
4601 redirect($CFG->wwwroot
.'/login/change_password.php');
4604 print_error('nopasswordchangeforced', 'auth');
4611 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4613 * @param string $password String to check.
4614 * @return boolean True if the $password matches the format of an md5 sum.
4616 function password_is_legacy_hash($password) {
4617 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4621 * Compare password against hash stored in user object to determine if it is valid.
4623 * If necessary it also updates the stored hash to the current format.
4625 * @param stdClass $user (Password property may be updated).
4626 * @param string $password Plain text password.
4627 * @return bool True if password is valid.
4629 function validate_internal_user_password($user, $password) {
4632 if ($user->password
=== AUTH_PASSWORD_NOT_CACHED
) {
4633 // Internal password is not used at all, it can not validate.
4637 // If hash isn't a legacy (md5) hash, validate using the library function.
4638 if (!password_is_legacy_hash($user->password
)) {
4639 return password_verify($password, $user->password
);
4642 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4643 // is valid we can then update it to the new algorithm.
4645 $sitesalt = isset($CFG->passwordsaltmain
) ?
$CFG->passwordsaltmain
: '';
4648 if ($user->password
=== md5($password.$sitesalt)
4649 or $user->password
=== md5($password)
4650 or $user->password
=== md5(addslashes($password).$sitesalt)
4651 or $user->password
=== md5(addslashes($password))) {
4652 // Note: we are intentionally using the addslashes() here because we
4653 // need to accept old password hashes of passwords with magic quotes.
4657 for ($i=1; $i<=20; $i++
) { // 20 alternative salts should be enough, right?
4658 $alt = 'passwordsaltalt'.$i;
4659 if (!empty($CFG->$alt)) {
4660 if ($user->password
=== md5($password.$CFG->$alt) or $user->password
=== md5(addslashes($password).$CFG->$alt)) {
4669 // If the password matches the existing md5 hash, update to the
4670 // current hash algorithm while we have access to the user's password.
4671 update_internal_user_password($user, $password);
4678 * Calculate hash for a plain text password.
4680 * @param string $password Plain text password to be hashed.
4681 * @param bool $fasthash If true, use a low cost factor when generating the hash
4682 * This is much faster to generate but makes the hash
4683 * less secure. It is used when lots of hashes need to
4684 * be generated quickly.
4685 * @return string The hashed password.
4687 * @throws moodle_exception If a problem occurs while generating the hash.
4689 function hash_internal_user_password($password, $fasthash = false) {
4692 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4693 $options = ($fasthash) ?
array('cost' => 4) : array();
4695 $generatedhash = password_hash($password, PASSWORD_DEFAULT
, $options);
4697 if ($generatedhash === false ||
$generatedhash === null) {
4698 throw new moodle_exception('Failed to generate password hash.');
4701 return $generatedhash;
4705 * Update password hash in user object (if necessary).
4707 * The password is updated if:
4708 * 1. The password has changed (the hash of $user->password is different
4709 * to the hash of $password).
4710 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4713 * Updating the password will modify the $user object and the database
4714 * record to use the current hashing algorithm.
4715 * It will remove Web Services user tokens too.
4717 * @param stdClass $user User object (password property may be updated).
4718 * @param string $password Plain text password.
4719 * @param bool $fasthash If true, use a low cost factor when generating the hash
4720 * This is much faster to generate but makes the hash
4721 * less secure. It is used when lots of hashes need to
4722 * be generated quickly.
4723 * @return bool Always returns true.
4725 function update_internal_user_password($user, $password, $fasthash = false) {
4728 // Figure out what the hashed password should be.
4729 if (!isset($user->auth
)) {
4730 debugging('User record in update_internal_user_password() must include field auth',
4732 $user->auth
= $DB->get_field('user', 'auth', array('id' => $user->id
));
4734 $authplugin = get_auth_plugin($user->auth
);
4735 if ($authplugin->prevent_local_passwords()) {
4736 $hashedpassword = AUTH_PASSWORD_NOT_CACHED
;
4738 $hashedpassword = hash_internal_user_password($password, $fasthash);
4741 $algorithmchanged = false;
4743 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED
) {
4744 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4745 $passwordchanged = ($user->password
!== $hashedpassword);
4747 } else if (isset($user->password
)) {
4748 // If verification fails then it means the password has changed.
4749 $passwordchanged = !password_verify($password, $user->password
);
4750 $algorithmchanged = password_needs_rehash($user->password
, PASSWORD_DEFAULT
);
4752 // While creating new user, password in unset in $user object, to avoid
4753 // saving it with user_create()
4754 $passwordchanged = true;
4757 if ($passwordchanged ||
$algorithmchanged) {
4758 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id
));
4759 $user->password
= $hashedpassword;
4762 $user = $DB->get_record('user', array('id' => $user->id
));
4763 \core\event\user_password_updated
::create_from_user($user)->trigger();
4765 // Remove WS user tokens.
4766 if (!empty($CFG->passwordchangetokendeletion
)) {
4767 require_once($CFG->dirroot
.'/webservice/lib.php');
4768 webservice
::delete_user_ws_tokens($user->id
);
4776 * Get a complete user record, which includes all the info in the user record.
4778 * Intended for setting as $USER session variable
4780 * @param string $field The user field to be checked for a given value.
4781 * @param string $value The value to match for $field.
4782 * @param int $mnethostid
4783 * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4784 * found. Otherwise, it will just return false.
4785 * @return mixed False, or A {@link $USER} object.
4787 function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4790 if (!$field ||
!$value) {
4794 // Change the field to lowercase.
4795 $field = core_text
::strtolower($field);
4797 // List of case insensitive fields.
4798 $caseinsensitivefields = ['email'];
4800 // Username input is forced to lowercase and should be case sensitive.
4801 if ($field == 'username') {
4802 $value = core_text
::strtolower($value);
4805 // Build the WHERE clause for an SQL query.
4806 $params = array('fieldval' => $value);
4808 // Do a case-insensitive query, if necessary. These are generally very expensive. The performance can be improved on some DBs
4809 // such as MySQL by pre-filtering users with accent-insensitive subselect.
4810 if (in_array($field, $caseinsensitivefields)) {
4811 $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4812 $idsubselect = $DB->sql_equal($field, ':fieldval2', false, false);
4813 $params['fieldval2'] = $value;
4815 $fieldselect = "$field = :fieldval";
4818 $constraints = "$fieldselect AND deleted <> 1";
4820 // If we are loading user data based on anything other than id,
4821 // we must also restrict our search based on mnet host.
4822 if ($field != 'id') {
4823 if (empty($mnethostid)) {
4824 // If empty, we restrict to local users.
4825 $mnethostid = $CFG->mnet_localhost_id
;
4828 if (!empty($mnethostid)) {
4829 $params['mnethostid'] = $mnethostid;
4830 $constraints .= " AND mnethostid = :mnethostid";
4834 $constraints .= " AND id IN (SELECT id FROM {user} WHERE {$idsubselect})";
4837 // Get all the basic user data.
4839 // Make sure that there's only a single record that matches our query.
4840 // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4841 // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4842 $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST
);
4843 } catch (dml_exception
$exception) {
4844 if ($throwexception) {
4847 // Return false when no records or multiple records were found.
4852 // Get various settings and preferences.
4854 // Preload preference cache.
4855 check_user_preferences_loaded($user);
4857 // Load course enrolment related stuff.
4858 $user->lastcourseaccess
= array(); // During last session.
4859 $user->currentcourseaccess
= array(); // During current session.
4860 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id
))) {
4861 foreach ($lastaccesses as $lastaccess) {
4862 $user->lastcourseaccess
[$lastaccess->courseid
] = $lastaccess->timeaccess
;
4866 $sql = "SELECT g.id, g.courseid
4867 FROM {groups} g, {groups_members} gm
4868 WHERE gm.groupid=g.id AND gm.userid=?";
4870 // This is a special hack to speedup calendar display.
4871 $user->groupmember
= array();
4872 if (!isguestuser($user)) {
4873 if ($groups = $DB->get_records_sql($sql, array($user->id
))) {
4874 foreach ($groups as $group) {
4875 if (!array_key_exists($group->courseid
, $user->groupmember
)) {
4876 $user->groupmember
[$group->courseid
] = array();
4878 $user->groupmember
[$group->courseid
][$group->id
] = $group->id
;
4883 // Add cohort theme.
4884 if (!empty($CFG->allowcohortthemes
)) {
4885 require_once($CFG->dirroot
. '/cohort/lib.php');
4886 if ($cohorttheme = cohort_get_user_cohort_theme($user->id
)) {
4887 $user->cohorttheme
= $cohorttheme;
4891 // Add the custom profile fields to the user record.
4892 $user->profile
= array();
4893 if (!isguestuser($user)) {
4894 require_once($CFG->dirroot
.'/user/profile/lib.php');
4895 profile_load_custom_fields($user);
4898 // Rewrite some variables if necessary.
4899 if (!empty($user->description
)) {
4900 // No need to cart all of it around.
4901 $user->description
= true;
4903 if (isguestuser($user)) {
4904 // Guest language always same as site.
4905 $user->lang
= get_newuser_language();
4906 // Name always in current language.
4907 $user->firstname
= get_string('guestuser');
4908 $user->lastname
= ' ';
4915 * Validate a password against the configured password policy
4917 * @param string $password the password to be checked against the password policy
4918 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4919 * @param stdClass $user the user object to perform password validation against. Defaults to null if not provided.
4921 * @return bool true if the password is valid according to the policy. false otherwise.
4923 function check_password_policy($password, &$errmsg, $user = null) {
4926 if (!empty($CFG->passwordpolicy
)) {
4928 if (core_text
::strlen($password) < $CFG->minpasswordlength
) {
4929 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength
) .'</div>';
4931 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits
) {
4932 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits
) .'</div>';
4934 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower
) {
4935 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower
) .'</div>';
4937 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper
) {
4938 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper
) .'</div>';
4940 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum
) {
4941 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
) .'</div>';
4943 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars
)) {
4944 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars
) .'</div>';
4947 // Fire any additional password policy functions from plugins.
4948 // Plugin functions should output an error message string or empty string for success.
4949 $pluginsfunction = get_plugins_with_function('check_password_policy');
4950 foreach ($pluginsfunction as $plugintype => $plugins) {
4951 foreach ($plugins as $pluginfunction) {
4952 $pluginerr = $pluginfunction($password, $user);
4954 $errmsg .= '<div>'. $pluginerr .'</div>';
4960 if ($errmsg == '') {
4969 * When logging in, this function is run to set certain preferences for the current SESSION.
4971 function set_login_session_preferences() {
4974 $SESSION->justloggedin
= true;
4976 unset($SESSION->lang
);
4977 unset($SESSION->forcelang
);
4978 unset($SESSION->load_navigation_admin
);
4983 * Delete a course, including all related data from the database, and any associated files.
4985 * @param mixed $courseorid The id of the course or course object to delete.
4986 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4987 * @return bool true if all the removals succeeded. false if there were any failures. If this
4988 * method returns false, some of the removals will probably have succeeded, and others
4989 * failed, but you have no way of knowing which.
4991 function delete_course($courseorid, $showfeedback = true) {
4994 if (is_object($courseorid)) {
4995 $courseid = $courseorid->id
;
4996 $course = $courseorid;
4998 $courseid = $courseorid;
4999 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
5003 $context = context_course
::instance($courseid);
5005 // Frontpage course can not be deleted!!
5006 if ($courseid == SITEID
) {
5010 // Allow plugins to use this course before we completely delete it.
5011 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
5012 foreach ($pluginsfunction as $plugintype => $plugins) {
5013 foreach ($plugins as $pluginfunction) {
5014 $pluginfunction($course);
5019 // Tell the search manager we are about to delete a course. This prevents us sending updates
5020 // for each individual context being deleted.
5021 \core_search\manager
::course_deleting_start($courseid);
5023 $handler = core_course\customfield\course_handler
::create();
5024 $handler->delete_instance($courseid);
5026 // Make the course completely empty.
5027 remove_course_contents($courseid, $showfeedback);
5029 // Delete the course and related context instance.
5030 context_helper
::delete_instance(CONTEXT_COURSE
, $courseid);
5032 $DB->delete_records("course", array("id" => $courseid));
5033 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5035 // Reset all course related caches here.
5036 core_courseformat\base
::reset_course_cache($courseid);
5038 // Tell search that we have deleted the course so it can delete course data from the index.
5039 \core_search\manager
::course_deleting_finish($courseid);
5041 // Trigger a course deleted event.
5042 $event = \core\event\course_deleted
::create(array(
5043 'objectid' => $course->id
,
5044 'context' => $context,
5046 'shortname' => $course->shortname
,
5047 'fullname' => $course->fullname
,
5048 'idnumber' => $course->idnumber
5051 $event->add_record_snapshot('course', $course);
5058 * Clear a course out completely, deleting all content but don't delete the course itself.
5060 * This function does not verify any permissions.
5062 * Please note this function also deletes all user enrolments,
5063 * enrolment instances and role assignments by default.
5066 * - 'keep_roles_and_enrolments' - false by default
5067 * - 'keep_groups_and_groupings' - false by default
5069 * @param int $courseid The id of the course that is being deleted
5070 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5071 * @param array $options extra options
5072 * @return bool true if all the removals succeeded. false if there were any failures. If this
5073 * method returns false, some of the removals will probably have succeeded, and others
5074 * failed, but you have no way of knowing which.
5076 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5077 global $CFG, $DB, $OUTPUT;
5079 require_once($CFG->libdir
.'/badgeslib.php');
5080 require_once($CFG->libdir
.'/completionlib.php');
5081 require_once($CFG->libdir
.'/questionlib.php');
5082 require_once($CFG->libdir
.'/gradelib.php');
5083 require_once($CFG->dirroot
.'/group/lib.php');
5084 require_once($CFG->dirroot
.'/comment/lib.php');
5085 require_once($CFG->dirroot
.'/rating/lib.php');
5086 require_once($CFG->dirroot
.'/notes/lib.php');
5088 // Handle course badges.
5089 badges_handle_course_deletion($courseid);
5091 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5092 $strdeleted = get_string('deleted').' - ';
5094 // Some crazy wishlist of stuff we should skip during purging of course content.
5095 $options = (array)$options;
5097 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST
);
5098 $coursecontext = context_course
::instance($courseid);
5099 $fs = get_file_storage();
5101 // Delete course completion information, this has to be done before grades and enrols.
5102 $cc = new completion_info($course);
5103 $cc->clear_criteria();
5104 if ($showfeedback) {
5105 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5108 // Remove all data from gradebook - this needs to be done before course modules
5109 // because while deleting this information, the system may need to reference
5110 // the course modules that own the grades.
5111 remove_course_grades($courseid, $showfeedback);
5112 remove_grade_letters($coursecontext, $showfeedback);
5114 // Delete course blocks in any all child contexts,
5115 // they may depend on modules so delete them first.
5116 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5117 foreach ($childcontexts as $childcontext) {
5118 blocks_delete_all_for_context($childcontext->id
);
5120 unset($childcontexts);
5121 blocks_delete_all_for_context($coursecontext->id
);
5122 if ($showfeedback) {
5123 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5126 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $courseid]);
5127 rebuild_course_cache($courseid, true);
5129 // Get the list of all modules that are properly installed.
5130 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5132 // Delete every instance of every module,
5133 // this has to be done before deleting of course level stuff.
5134 $locations = core_component
::get_plugin_list('mod');
5135 foreach ($locations as $modname => $moddir) {
5136 if ($modname === 'NEWMODULE') {
5139 if (array_key_exists($modname, $allmodules)) {
5140 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5141 FROM {".$modname."} m
5142 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5143 WHERE m.course = :courseid";
5144 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id
,
5145 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5147 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5148 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5151 foreach ($instances as $cm) {
5153 // Delete activity context questions and question categories.
5154 question_delete_activity($cm);
5155 // Notify the competency subsystem.
5156 \core_competency\api
::hook_course_module_deleted($cm);
5158 if (function_exists($moddelete)) {
5159 // This purges all module data in related tables, extra user prefs, settings, etc.
5160 $moddelete($cm->modinstance
);
5162 // NOTE: we should not allow installation of modules with missing delete support!
5163 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5164 $DB->delete_records($modname, array('id' => $cm->modinstance
));
5168 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5169 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
5170 $DB->delete_records('course_modules_completion', ['coursemoduleid' => $cm->id
]);
5171 $DB->delete_records('course_modules', array('id' => $cm->id
));
5172 rebuild_course_cache($cm->course
, true);
5176 if ($instances and $showfeedback) {
5177 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5180 // Ooops, this module is not properly installed, force-delete it in the next block.
5184 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5186 // Delete completion defaults.
5187 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5189 // Remove all data from availability and completion tables that is associated
5190 // with course-modules belonging to this course. Note this is done even if the
5191 // features are not enabled now, in case they were enabled previously.
5192 $DB->delete_records_subquery('course_modules_completion', 'coursemoduleid', 'id',
5193 'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
5195 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5196 $cms = $DB->get_records('course_modules', array('course' => $course->id
));
5197 $allmodulesbyid = array_flip($allmodules);
5198 foreach ($cms as $cm) {
5199 if (array_key_exists($cm->module
, $allmodulesbyid)) {
5201 $DB->delete_records($allmodulesbyid[$cm->module
], array('id' => $cm->instance
));
5202 } catch (Exception
$e) {
5203 // Ignore weird or missing table problems.
5206 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
5207 $DB->delete_records('course_modules', array('id' => $cm->id
));
5208 rebuild_course_cache($cm->course
, true);
5211 if ($showfeedback) {
5212 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5215 // Delete questions and question categories.
5216 question_delete_course($course);
5217 if ($showfeedback) {
5218 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5221 // Delete content bank contents.
5222 $cb = new \core_contentbank\
contentbank();
5223 $cbdeleted = $cb->delete_contents($coursecontext);
5224 if ($showfeedback && $cbdeleted) {
5225 echo $OUTPUT->notification($strdeleted.get_string('contentbank', 'contentbank'), 'notifysuccess');
5228 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5229 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5230 foreach ($childcontexts as $childcontext) {
5231 $childcontext->delete();
5233 unset($childcontexts);
5235 // Remove roles and enrolments by default.
5236 if (empty($options['keep_roles_and_enrolments'])) {
5237 // This hack is used in restore when deleting contents of existing course.
5238 // During restore, we should remove only enrolment related data that the user performing the restore has a
5239 // permission to remove.
5240 $userid = $options['userid'] ??
null;
5241 enrol_course_delete($course, $userid);
5242 role_unassign_all(array('contextid' => $coursecontext->id
, 'component' => ''), true);
5243 if ($showfeedback) {
5244 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5248 // Delete any groups, removing members and grouping/course links first.
5249 if (empty($options['keep_groups_and_groupings'])) {
5250 groups_delete_groupings($course->id
, $showfeedback);
5251 groups_delete_groups($course->id
, $showfeedback);
5255 filter_delete_all_for_context($coursecontext->id
);
5257 // Notes, you shall not pass!
5258 note_delete_all($course->id
);
5261 comment
::delete_comments($coursecontext->id
);
5263 // Ratings are history too.
5264 $delopt = new stdclass();
5265 $delopt->contextid
= $coursecontext->id
;
5266 $rm = new rating_manager();
5267 $rm->delete_ratings($delopt);
5269 // Delete course tags.
5270 core_tag_tag
::remove_all_item_tags('core', 'course', $course->id
);
5272 // Give the course format the opportunity to remove its obscure data.
5273 $format = course_get_format($course);
5274 $format->delete_format_data();
5276 // Notify the competency subsystem.
5277 \core_competency\api
::hook_course_deleted($course);
5279 // Delete calendar events.
5280 $DB->delete_records('event', array('courseid' => $course->id
));
5281 $fs->delete_area_files($coursecontext->id
, 'calendar');
5283 // Delete all related records in other core tables that may have a courseid
5284 // This array stores the tables that need to be cleared, as
5285 // table_name => column_name that contains the course id.
5286 $tablestoclear = array(
5287 'backup_courses' => 'courseid', // Scheduled backup stuff.
5288 'user_lastaccess' => 'courseid', // User access info.
5290 foreach ($tablestoclear as $table => $col) {
5291 $DB->delete_records($table, array($col => $course->id
));
5294 // Delete all course backup files.
5295 $fs->delete_area_files($coursecontext->id
, 'backup');
5297 // Cleanup course record - remove links to deleted stuff.
5298 $oldcourse = new stdClass();
5299 $oldcourse->id
= $course->id
;
5300 $oldcourse->summary
= '';
5301 $oldcourse->cacherev
= 0;
5302 $oldcourse->legacyfiles
= 0;
5303 if (!empty($options['keep_groups_and_groupings'])) {
5304 $oldcourse->defaultgroupingid
= 0;
5306 $DB->update_record('course', $oldcourse);
5308 // Delete course sections.
5309 $DB->delete_records('course_sections', array('course' => $course->id
));
5311 // Delete legacy, section and any other course files.
5312 $fs->delete_area_files($coursecontext->id
, 'course'); // Files from summary and section.
5314 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5315 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5316 // Easy, do not delete the context itself...
5317 $coursecontext->delete_content();
5320 // We can not drop all context stuff because it would bork enrolments and roles,
5321 // there might be also files used by enrol plugins...
5324 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5325 // also some non-standard unsupported plugins may try to store something there.
5326 fulldelete($CFG->dataroot
.'/'.$course->id
);
5328 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5329 $cachemodinfo = cache
::make('core', 'coursemodinfo');
5330 $cachemodinfo->delete($courseid);
5332 // Trigger a course content deleted event.
5333 $event = \core\event\course_content_deleted
::create(array(
5334 'objectid' => $course->id
,
5335 'context' => $coursecontext,
5336 'other' => array('shortname' => $course->shortname
,
5337 'fullname' => $course->fullname
,
5338 'options' => $options) // Passing this for legacy reasons.
5340 $event->add_record_snapshot('course', $course);
5347 * Change dates in module - used from course reset.
5349 * @param string $modname forum, assignment, etc
5350 * @param array $fields array of date fields from mod table
5351 * @param int $timeshift time difference
5352 * @param int $courseid
5353 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5354 * @return bool success
5356 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5358 include_once($CFG->dirroot
.'/mod/'.$modname.'/lib.php');
5361 $params = array($timeshift, $courseid);
5362 foreach ($fields as $field) {
5363 $updatesql = "UPDATE {".$modname."}
5364 SET $field = $field + ?
5365 WHERE course=? AND $field<>0";
5367 $updatesql .= ' AND id=?';
5370 $return = $DB->execute($updatesql, $params) && $return;
5377 * This function will empty a course of user data.
5378 * It will retain the activities and the structure of the course.
5380 * @param object $data an object containing all the settings including courseid (without magic quotes)
5381 * @return array status array of array component, item, error
5383 function reset_course_userdata($data) {
5385 require_once($CFG->libdir
.'/gradelib.php');
5386 require_once($CFG->libdir
.'/completionlib.php');
5387 require_once($CFG->dirroot
.'/completion/criteria/completion_criteria_date.php');
5388 require_once($CFG->dirroot
.'/group/lib.php');
5390 $data->courseid
= $data->id
;
5391 $context = context_course
::instance($data->courseid
);
5393 $eventparams = array(
5394 'context' => $context,
5395 'courseid' => $data->id
,
5397 'reset_options' => (array) $data
5400 $event = \core\event\course_reset_started
::create($eventparams);
5403 // Calculate the time shift of dates.
5404 if (!empty($data->reset_start_date
)) {
5405 // Time part of course startdate should be zero.
5406 $data->timeshift
= $data->reset_start_date
- usergetmidnight($data->reset_start_date_old
);
5408 $data->timeshift
= 0;
5411 // Result array: component, item, error.
5414 // Start the resetting.
5415 $componentstr = get_string('general');
5417 // Move the course start time.
5418 if (!empty($data->reset_start_date
) and $data->timeshift
) {
5419 // Change course start data.
5420 $DB->set_field('course', 'startdate', $data->reset_start_date
, array('id' => $data->courseid
));
5421 // Update all course and group events - do not move activity events.
5422 $updatesql = "UPDATE {event}
5423 SET timestart = timestart + ?
5424 WHERE courseid=? AND instance=0";
5425 $DB->execute($updatesql, array($data->timeshift
, $data->courseid
));
5427 // Update any date activity restrictions.
5428 if ($CFG->enableavailability
) {
5429 \availability_date\condition
::update_all_dates($data->courseid
, $data->timeshift
);
5432 // Update completion expected dates.
5433 if ($CFG->enablecompletion
) {
5434 $modinfo = get_fast_modinfo($data->courseid
);
5436 foreach ($modinfo->get_cms() as $cm) {
5437 if ($cm->completion
&& !empty($cm->completionexpected
)) {
5438 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected +
$data->timeshift
,
5439 array('id' => $cm->id
));
5444 // Clear course cache if changes made.
5446 rebuild_course_cache($data->courseid
, true);
5449 // Update course date completion criteria.
5450 \completion_criteria_date
::update_date($data->courseid
, $data->timeshift
);
5453 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5456 if (!empty($data->reset_end_date
)) {
5457 // If the user set a end date value respect it.
5458 $DB->set_field('course', 'enddate', $data->reset_end_date
, array('id' => $data->courseid
));
5459 } else if ($data->timeshift
> 0 && $data->reset_end_date_old
) {
5460 // If there is a time shift apply it to the end date as well.
5461 $enddate = $data->reset_end_date_old +
$data->timeshift
;
5462 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid
));
5465 if (!empty($data->reset_events
)) {
5466 $DB->delete_records('event', array('courseid' => $data->courseid
));
5467 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5470 if (!empty($data->reset_notes
)) {
5471 require_once($CFG->dirroot
.'/notes/lib.php');
5472 note_delete_all($data->courseid
);
5473 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5476 if (!empty($data->delete_blog_associations
)) {
5477 require_once($CFG->dirroot
.'/blog/lib.php');
5478 blog_remove_associations_for_course($data->courseid
);
5479 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5482 if (!empty($data->reset_completion
)) {
5483 // Delete course and activity completion information.
5484 $course = $DB->get_record('course', array('id' => $data->courseid
));
5485 $cc = new completion_info($course);
5486 $cc->delete_all_completion_data();
5487 $status[] = array('component' => $componentstr,
5488 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5491 if (!empty($data->reset_competency_ratings
)) {
5492 \core_competency\api
::hook_course_reset_competency_ratings($data->courseid
);
5493 $status[] = array('component' => $componentstr,
5494 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5497 $componentstr = get_string('roles');
5499 if (!empty($data->reset_roles_overrides
)) {
5500 $children = $context->get_child_contexts();
5501 foreach ($children as $child) {
5502 $child->delete_capabilities();
5504 $context->delete_capabilities();
5505 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5508 if (!empty($data->reset_roles_local
)) {
5509 $children = $context->get_child_contexts();
5510 foreach ($children as $child) {
5511 role_unassign_all(array('contextid' => $child->id
));
5513 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5516 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5517 $data->unenrolled
= array();
5518 if (!empty($data->unenrol_users
)) {
5519 $plugins = enrol_get_plugins(true);
5520 $instances = enrol_get_instances($data->courseid
, true);
5521 foreach ($instances as $key => $instance) {
5522 if (!isset($plugins[$instance->enrol
])) {
5523 unset($instances[$key]);
5528 $usersroles = enrol_get_course_users_roles($data->courseid
);
5529 foreach ($data->unenrol_users
as $withroleid) {
5532 FROM {user_enrolments} ue
5533 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5534 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5535 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5536 $params = array('courseid' => $data->courseid
, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE
);
5539 // Without any role assigned at course context.
5541 FROM {user_enrolments} ue
5542 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5543 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5544 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5545 WHERE ra.id IS null";
5546 $params = array('courseid' => $data->courseid
, 'courselevel' => CONTEXT_COURSE
);
5549 $rs = $DB->get_recordset_sql($sql, $params);
5550 foreach ($rs as $ue) {
5551 if (!isset($instances[$ue->enrolid
])) {
5554 $instance = $instances[$ue->enrolid
];
5555 $plugin = $plugins[$instance->enrol
];
5556 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5560 if ($withroleid && count($usersroles[$ue->userid
]) > 1) {
5561 // If we don't remove all roles and user has more than one role, just remove this role.
5562 role_unassign($withroleid, $ue->userid
, $context->id
);
5564 unset($usersroles[$ue->userid
][$withroleid]);
5566 // If we remove all roles or user has only one role, unenrol user from course.
5567 $plugin->unenrol_user($instance, $ue->userid
);
5569 $data->unenrolled
[$ue->userid
] = $ue->userid
;
5574 if (!empty($data->unenrolled
)) {
5576 'component' => $componentstr,
5577 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled
).')',
5582 $componentstr = get_string('groups');
5584 // Remove all group members.
5585 if (!empty($data->reset_groups_members
)) {
5586 groups_delete_group_members($data->courseid
);
5587 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5590 // Remove all groups.
5591 if (!empty($data->reset_groups_remove
)) {
5592 groups_delete_groups($data->courseid
, false);
5593 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5596 // Remove all grouping members.
5597 if (!empty($data->reset_groupings_members
)) {
5598 groups_delete_groupings_groups($data->courseid
, false);
5599 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5602 // Remove all groupings.
5603 if (!empty($data->reset_groupings_remove
)) {
5604 groups_delete_groupings($data->courseid
, false);
5605 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5608 // Look in every instance of every module for data to delete.
5609 $unsupportedmods = array();
5610 if ($allmods = $DB->get_records('modules') ) {
5611 foreach ($allmods as $mod) {
5612 $modname = $mod->name
;
5613 $modfile = $CFG->dirroot
.'/mod/'. $modname.'/lib.php';
5614 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5615 if (file_exists($modfile)) {
5616 if (!$DB->count_records($modname, array('course' => $data->courseid
))) {
5617 continue; // Skip mods with no instances.
5619 include_once($modfile);
5620 if (function_exists($moddeleteuserdata)) {
5621 $modstatus = $moddeleteuserdata($data);
5622 if (is_array($modstatus)) {
5623 $status = array_merge($status, $modstatus);
5625 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5628 $unsupportedmods[] = $mod;
5631 debugging('Missing lib.php in '.$modname.' module!');
5633 // Update calendar events for all modules.
5634 course_module_bulk_update_calendar_events($modname, $data->courseid
);
5638 // Mention unsupported mods.
5639 if (!empty($unsupportedmods)) {
5640 foreach ($unsupportedmods as $mod) {
5642 'component' => get_string('modulenameplural', $mod->name
),
5644 'error' => get_string('resetnotimplemented')
5649 $componentstr = get_string('gradebook', 'grades');
5650 // Reset gradebook,.
5651 if (!empty($data->reset_gradebook_items
)) {
5652 remove_course_grades($data->courseid
, false);
5653 grade_grab_course_grades($data->courseid
);
5654 grade_regrade_final_grades($data->courseid
);
5655 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5657 } else if (!empty($data->reset_gradebook_grades
)) {
5658 grade_course_reset($data->courseid
);
5659 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5662 if (!empty($data->reset_comments
)) {
5663 require_once($CFG->dirroot
.'/comment/lib.php');
5664 comment
::reset_course_page_comments($context);
5667 $event = \core\event\course_reset_ended
::create($eventparams);
5674 * Generate an email processing address.
5677 * @param string $modargs
5678 * @return string Returns email processing address
5680 function generate_email_processing_address($modid, $modargs) {
5683 $header = $CFG->mailprefix
. substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5684 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain
;
5690 * @todo Finish documenting this function
5692 * @param string $modargs
5693 * @param string $body Currently unused
5695 function moodle_process_email($modargs, $body) {
5698 // The first char should be an unencoded letter. We'll take this as an action.
5699 switch ($modargs[0]) {
5700 case 'B': { // Bounce.
5701 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5702 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5703 // Check the half md5 of their email.
5704 $md5check = substr(md5($user->email
), 0, 16);
5705 if ($md5check == substr($modargs, -16)) {
5706 set_bounce_count($user);
5708 // Else maybe they've already changed it?
5712 // Maybe more later?
5719 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5721 * @param string $action 'get', 'buffer', 'close' or 'flush'
5722 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5724 function get_mailer($action='get') {
5727 /** @var moodle_phpmailer $mailer */
5728 static $mailer = null;
5729 static $counter = 0;
5731 if (!isset($CFG->smtpmaxbulk
)) {
5732 $CFG->smtpmaxbulk
= 1;
5735 if ($action == 'get') {
5736 $prevkeepalive = false;
5738 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5739 if ($counter < $CFG->smtpmaxbulk
and !$mailer->isError()) {
5741 // Reset the mailer.
5742 $mailer->Priority
= 3;
5743 $mailer->CharSet
= 'UTF-8'; // Our default.
5744 $mailer->ContentType
= "text/plain";
5745 $mailer->Encoding
= "8bit";
5746 $mailer->From
= "root@localhost";
5747 $mailer->FromName
= "Root User";
5748 $mailer->Sender
= "";
5749 $mailer->Subject
= "";
5751 $mailer->AltBody
= "";
5752 $mailer->ConfirmReadingTo
= "";
5754 $mailer->clearAllRecipients();
5755 $mailer->clearReplyTos();
5756 $mailer->clearAttachments();
5757 $mailer->clearCustomHeaders();
5761 $prevkeepalive = $mailer->SMTPKeepAlive
;
5762 get_mailer('flush');
5765 require_once($CFG->libdir
.'/phpmailer/moodle_phpmailer.php');
5766 $mailer = new moodle_phpmailer();
5770 if ($CFG->smtphosts
== 'qmail') {
5771 // Use Qmail system.
5774 } else if (empty($CFG->smtphosts
)) {
5775 // Use PHP mail() = sendmail.
5779 // Use SMTP directly.
5781 if (!empty($CFG->debugsmtp
) && (!empty($CFG->debugdeveloper
))) {
5782 $mailer->SMTPDebug
= 3;
5784 // Specify main and backup servers.
5785 $mailer->Host
= $CFG->smtphosts
;
5786 // Specify secure connection protocol.
5787 $mailer->SMTPSecure
= $CFG->smtpsecure
;
5788 // Use previous keepalive.
5789 $mailer->SMTPKeepAlive
= $prevkeepalive;
5791 if ($CFG->smtpuser
) {
5792 // Use SMTP authentication.
5793 $mailer->SMTPAuth
= true;
5794 $mailer->Username
= $CFG->smtpuser
;
5795 $mailer->Password
= $CFG->smtppass
;
5804 // Keep smtp session open after sending.
5805 if ($action == 'buffer') {
5806 if (!empty($CFG->smtpmaxbulk
)) {
5807 get_mailer('flush');
5809 if ($m->Mailer
== 'smtp') {
5810 $m->SMTPKeepAlive
= true;
5816 // Close smtp session, but continue buffering.
5817 if ($action == 'flush') {
5818 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5819 if (!empty($mailer->SMTPDebug
)) {
5822 $mailer->SmtpClose();
5823 if (!empty($mailer->SMTPDebug
)) {
5830 // Close smtp session, do not buffer anymore.
5831 if ($action == 'close') {
5832 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5833 get_mailer('flush');
5834 $mailer->SMTPKeepAlive
= false;
5836 $mailer = null; // Better force new instance.
5842 * A helper function to test for email diversion
5844 * @param string $email
5845 * @return bool Returns true if the email should be diverted
5847 function email_should_be_diverted($email) {
5850 if (empty($CFG->divertallemailsto
)) {
5854 if (empty($CFG->divertallemailsexcept
)) {
5858 $patterns = array_map('trim', preg_split("/[\s,]+/", $CFG->divertallemailsexcept
));
5859 foreach ($patterns as $pattern) {
5860 if (preg_match("/$pattern/", $email)) {
5869 * Generate a unique email Message-ID using the moodle domain and install path
5871 * @param string $localpart An optional unique message id prefix.
5872 * @return string The formatted ID ready for appending to the email headers.
5874 function generate_email_messageid($localpart = null) {
5877 $urlinfo = parse_url($CFG->wwwroot
);
5878 $base = '@' . $urlinfo['host'];
5880 // If multiple moodles are on the same domain we want to tell them
5881 // apart so we add the install path to the local part. This means
5882 // that the id local part should never contain a / character so
5883 // we can correctly parse the id to reassemble the wwwroot.
5884 if (isset($urlinfo['path'])) {
5885 $base = $urlinfo['path'] . $base;
5888 if (empty($localpart)) {
5889 $localpart = uniqid('', true);
5892 // Because we may have an option /installpath suffix to the local part
5893 // of the id we need to escape any / chars which are in the $localpart.
5894 $localpart = str_replace('/', '%2F', $localpart);
5896 return '<' . $localpart . $base . '>';
5900 * Send an email to a specified user
5902 * @param stdClass $user A {@link $USER} object
5903 * @param stdClass $from A {@link $USER} object
5904 * @param string $subject plain text subject line of the email
5905 * @param string $messagetext plain text version of the message
5906 * @param string $messagehtml complete html version of the message (optional)
5907 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in one of
5908 * the following directories: $CFG->cachedir, $CFG->dataroot, $CFG->dirroot, $CFG->localcachedir, $CFG->tempdir
5909 * @param string $attachname the name of the file (extension indicates MIME)
5910 * @param bool $usetrueaddress determines whether $from email address should
5911 * be sent out. Will be overruled by user profile setting for maildisplay
5912 * @param string $replyto Email address to reply to
5913 * @param string $replytoname Name of reply to recipient
5914 * @param int $wordwrapwidth custom word wrap width, default 79
5915 * @return bool Returns true if mail was sent OK and false if there was an error.
5917 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5918 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5920 global $CFG, $PAGE, $SITE;
5922 if (empty($user) or empty($user->id
)) {
5923 debugging('Can not send email to null user', DEBUG_DEVELOPER
);
5927 if (empty($user->email
)) {
5928 debugging('Can not send email to user without email: '.$user->id
, DEBUG_DEVELOPER
);
5932 if (!empty($user->deleted
)) {
5933 debugging('Can not send email to deleted user: '.$user->id
, DEBUG_DEVELOPER
);
5937 if (defined('BEHAT_SITE_RUNNING')) {
5938 // Fake email sending in behat.
5942 if (!empty($CFG->noemailever
)) {
5943 // Hidden setting for development sites, set in config.php if needed.
5944 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL
);
5948 if (email_should_be_diverted($user->email
)) {
5949 $subject = "[DIVERTED {$user->email}] $subject";
5950 $user = clone($user);
5951 $user->email
= $CFG->divertallemailsto
;
5954 // Skip mail to suspended users.
5955 if ((isset($user->auth
) && $user->auth
=='nologin') or (isset($user->suspended
) && $user->suspended
)) {
5959 if (!validate_email($user->email
)) {
5960 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5961 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5965 if (over_bounce_threshold($user)) {
5966 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5970 // TLD .invalid is specifically reserved for invalid domain names.
5971 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5972 if (substr($user->email
, -8) == '.invalid') {
5973 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5974 return true; // This is not an error.
5977 // If the user is a remote mnet user, parse the email text for URL to the
5978 // wwwroot and modify the url to direct the user's browser to login at their
5979 // home site (identity provider - idp) before hitting the link itself.
5980 if (is_mnet_remote_user($user)) {
5981 require_once($CFG->dirroot
.'/mnet/lib.php');
5983 $jumpurl = mnet_get_idp_jump_url($user);
5984 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5986 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5989 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5993 $mail = get_mailer();
5995 if (!empty($mail->SMTPDebug
)) {
5996 echo '<pre>' . "\n";
5999 $temprecipients = array();
6000 $tempreplyto = array();
6002 // Make sure that we fall back onto some reasonable no-reply address.
6003 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot
);
6004 $noreplyaddress = empty($CFG->noreplyaddress
) ?
$noreplyaddressdefault : $CFG->noreplyaddress
;
6006 if (!validate_email($noreplyaddress)) {
6007 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
6008 $noreplyaddress = $noreplyaddressdefault;
6011 // Make up an email address for handling bounces.
6012 if (!empty($CFG->handlebounces
)) {
6013 $modargs = 'B'.base64_encode(pack('V', $user->id
)).substr(md5($user->email
), 0, 16);
6014 $mail->Sender
= generate_email_processing_address(0, $modargs);
6016 $mail->Sender
= $noreplyaddress;
6019 // Make sure that the explicit replyto is valid, fall back to the implicit one.
6020 if (!empty($replyto) && !validate_email($replyto)) {
6021 debugging('email_to_user: Invalid replyto-email '.s($replyto));
6022 $replyto = $noreplyaddress;
6025 if (is_string($from)) { // So we can pass whatever we want if there is need.
6026 $mail->From
= $noreplyaddress;
6027 $mail->FromName
= $from;
6028 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
6029 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6030 // in a course with the sender.
6031 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
6032 if (!validate_email($from->email
)) {
6033 debugging('email_to_user: Invalid from-email '.s($from->email
).' - not sending');
6034 // Better not to use $noreplyaddress in this case.
6037 $mail->From
= $from->email
;
6038 $fromdetails = new stdClass();
6039 $fromdetails->name
= fullname($from);
6040 $fromdetails->url
= preg_replace('#^https?://#', '', $CFG->wwwroot
);
6041 $fromdetails->siteshortname
= format_string($SITE->shortname
);
6042 $fromstring = $fromdetails->name
;
6043 if ($CFG->emailfromvia
== EMAIL_VIA_ALWAYS
) {
6044 $fromstring = get_string('emailvia', 'core', $fromdetails);
6046 $mail->FromName
= $fromstring;
6047 if (empty($replyto)) {
6048 $tempreplyto[] = array($from->email
, fullname($from));
6051 $mail->From
= $noreplyaddress;
6052 $fromdetails = new stdClass();
6053 $fromdetails->name
= fullname($from);
6054 $fromdetails->url
= preg_replace('#^https?://#', '', $CFG->wwwroot
);
6055 $fromdetails->siteshortname
= format_string($SITE->shortname
);
6056 $fromstring = $fromdetails->name
;
6057 if ($CFG->emailfromvia
!= EMAIL_VIA_NEVER
) {
6058 $fromstring = get_string('emailvia', 'core', $fromdetails);
6060 $mail->FromName
= $fromstring;
6061 if (empty($replyto)) {
6062 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
6066 if (!empty($replyto)) {
6067 $tempreplyto[] = array($replyto, $replytoname);
6070 $temprecipients[] = array($user->email
, fullname($user));
6073 $mail->WordWrap
= $wordwrapwidth;
6075 if (!empty($from->customheaders
)) {
6076 // Add custom headers.
6077 if (is_array($from->customheaders
)) {
6078 foreach ($from->customheaders
as $customheader) {
6079 $mail->addCustomHeader($customheader);
6082 $mail->addCustomHeader($from->customheaders
);
6086 // If the X-PHP-Originating-Script email header is on then also add an additional
6087 // header with details of where exactly in moodle the email was triggered from,
6088 // either a call to message_send() or to email_to_user().
6089 if (ini_get('mail.add_x_header')) {
6091 $stack = debug_backtrace(false);
6092 $origin = $stack[0];
6094 foreach ($stack as $depth => $call) {
6095 if ($call['function'] == 'message_send') {
6100 $originheader = $CFG->wwwroot
. ' => ' . gethostname() . ':'
6101 . str_replace($CFG->dirroot
. '/', '', $origin['file']) . ':' . $origin['line'];
6102 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
6105 if (!empty($CFG->emailheaders
)) {
6106 $headers = array_map('trim', explode("\n", $CFG->emailheaders
));
6107 foreach ($headers as $header) {
6108 if (!empty($header)) {
6109 $mail->addCustomHeader($header);
6114 if (!empty($from->priority
)) {
6115 $mail->Priority
= $from->priority
;
6118 $renderer = $PAGE->get_renderer('core');
6120 'sitefullname' => $SITE->fullname
,
6121 'siteshortname' => $SITE->shortname
,
6122 'sitewwwroot' => $CFG->wwwroot
,
6123 'subject' => $subject,
6124 'prefix' => $CFG->emailsubjectprefix
,
6125 'to' => $user->email
,
6126 'toname' => fullname($user),
6127 'from' => $mail->From
,
6128 'fromname' => $mail->FromName
,
6130 if (!empty($tempreplyto[0])) {
6131 $context['replyto'] = $tempreplyto[0][0];
6132 $context['replytoname'] = $tempreplyto[0][1];
6134 if ($user->id
> 0) {
6135 $context['touserid'] = $user->id
;
6136 $context['tousername'] = $user->username
;
6139 if (!empty($user->mailformat
) && $user->mailformat
== 1) {
6140 // Only process html templates if the user preferences allow html email.
6142 if (!$messagehtml) {
6143 // If no html has been given, BUT there is an html wrapping template then
6144 // auto convert the text to html and then wrap it.
6145 $messagehtml = trim(text_to_html($messagetext));
6147 $context['body'] = $messagehtml;
6148 $messagehtml = $renderer->render_from_template('core/email_html', $context);
6151 $context['body'] = html_to_text(nl2br($messagetext));
6152 $mail->Subject
= $renderer->render_from_template('core/email_subject', $context);
6153 $mail->FromName
= $renderer->render_from_template('core/email_fromname', $context);
6154 $messagetext = $renderer->render_from_template('core/email_text', $context);
6156 // Autogenerate a MessageID if it's missing.
6157 if (empty($mail->MessageID
)) {
6158 $mail->MessageID
= generate_email_messageid();
6161 if ($messagehtml && !empty($user->mailformat
) && $user->mailformat
== 1) {
6162 // Don't ever send HTML to users who don't want it.
6163 $mail->isHTML(true);
6164 $mail->Encoding
= 'quoted-printable';
6165 $mail->Body
= $messagehtml;
6166 $mail->AltBody
= "\n$messagetext\n";
6168 $mail->IsHTML(false);
6169 $mail->Body
= "\n$messagetext\n";
6172 if ($attachment && $attachname) {
6173 if (preg_match( "~\\.\\.~" , $attachment )) {
6174 // Security check for ".." in dir path.
6175 $supportuser = core_user
::get_support_user();
6176 $temprecipients[] = array($supportuser->email
, fullname($supportuser, true));
6177 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6179 require_once($CFG->libdir
.'/filelib.php');
6180 $mimetype = mimeinfo('type', $attachname);
6182 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6183 // The absolute (real) path is also fetched to ensure that comparisons to allowed paths are compared equally.
6184 $attachpath = str_replace('\\', '/', realpath($attachment));
6186 // Build an array of all filepaths from which attachments can be added (normalised slashes, absolute/real path).
6187 $allowedpaths = array_map(function(string $path): string {
6188 return str_replace('\\', '/', realpath($path));
6193 $CFG->localcachedir
,
6195 $CFG->localrequestdir
,
6198 // Set addpath to true.
6201 // Check if attachment includes one of the allowed paths.
6202 foreach (array_filter($allowedpaths) as $allowedpath) {
6203 // Set addpath to false if the attachment includes one of the allowed paths.
6204 if (strpos($attachpath, $allowedpath) === 0) {
6210 // If the attachment is a full path to a file in the multiple allowed paths, use it as is,
6211 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6212 if ($addpath == true) {
6213 $attachment = $CFG->dataroot
. '/' . $attachment;
6216 $mail->addAttachment($attachment, $attachname, 'base64', $mimetype);
6220 // Check if the email should be sent in an other charset then the default UTF-8.
6221 if ((!empty($CFG->sitemailcharset
) ||
!empty($CFG->allowusermailcharset
))) {
6223 // Use the defined site mail charset or eventually the one preferred by the recipient.
6224 $charset = $CFG->sitemailcharset
;
6225 if (!empty($CFG->allowusermailcharset
)) {
6226 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id
)) {
6227 $charset = $useremailcharset;
6231 // Convert all the necessary strings if the charset is supported.
6232 $charsets = get_list_of_charsets();
6233 unset($charsets['UTF-8']);
6234 if (in_array($charset, $charsets)) {
6235 $mail->CharSet
= $charset;
6236 $mail->FromName
= core_text
::convert($mail->FromName
, 'utf-8', strtolower($charset));
6237 $mail->Subject
= core_text
::convert($mail->Subject
, 'utf-8', strtolower($charset));
6238 $mail->Body
= core_text
::convert($mail->Body
, 'utf-8', strtolower($charset));
6239 $mail->AltBody
= core_text
::convert($mail->AltBody
, 'utf-8', strtolower($charset));
6241 foreach ($temprecipients as $key => $values) {
6242 $temprecipients[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
6244 foreach ($tempreplyto as $key => $values) {
6245 $tempreplyto[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
6250 foreach ($temprecipients as $values) {
6251 $mail->addAddress($values[0], $values[1]);
6253 foreach ($tempreplyto as $values) {
6254 $mail->addReplyTo($values[0], $values[1]);
6257 if (!empty($CFG->emaildkimselector
)) {
6258 $domain = substr(strrchr($mail->From
, "@"), 1);
6259 $pempath = "{$CFG->dataroot}/dkim/{$domain}/{$CFG->emaildkimselector}.private";
6260 if (file_exists($pempath)) {
6261 $mail->DKIM_domain
= $domain;
6262 $mail->DKIM_private
= $pempath;
6263 $mail->DKIM_selector
= $CFG->emaildkimselector
;
6264 $mail->DKIM_identity
= $mail->From
;
6266 debugging("Email DKIM selector chosen due to {$mail->From} but no certificate found at $pempath", DEBUG_DEVELOPER
);
6270 if ($mail->send()) {
6271 set_send_count($user);
6272 if (!empty($mail->SMTPDebug
)) {
6277 // Trigger event for failing to send email.
6278 $event = \core\event\email_failed
::create(array(
6279 'context' => context_system
::instance(),
6280 'userid' => $from->id
,
6281 'relateduserid' => $user->id
,
6283 'subject' => $subject,
6284 'message' => $messagetext,
6285 'errorinfo' => $mail->ErrorInfo
6290 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo
);
6292 if (!empty($mail->SMTPDebug
)) {
6300 * Check to see if a user's real email address should be used for the "From" field.
6302 * @param object $from The user object for the user we are sending the email from.
6303 * @param object $user The user object that we are sending the email to.
6304 * @param array $unused No longer used.
6305 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6307 function can_send_from_real_email_address($from, $user, $unused = null) {
6309 if (!isset($CFG->allowedemaildomains
) ||
empty(trim($CFG->allowedemaildomains
))) {
6312 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains
));
6313 // Email is in the list of allowed domains for sending email,
6314 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6315 // in a course with the sender.
6316 if (\core\ip_utils
::is_domain_in_allowed_list(substr($from->email
, strpos($from->email
, '@') +
1), $alloweddomains)
6317 && ($from->maildisplay
== core_user
::MAILDISPLAY_EVERYONE
6318 ||
($from->maildisplay
== core_user
::MAILDISPLAY_COURSE_MEMBERS_ONLY
6319 && enrol_get_shared_courses($user, $from, false, true)))) {
6326 * Generate a signoff for emails based on support settings
6330 function generate_email_signoff() {
6334 if (!empty($CFG->supportname
)) {
6335 $signoff .= $CFG->supportname
."\n";
6337 if (!empty($CFG->supportemail
)) {
6338 $signoff .= $CFG->supportemail
."\n";
6340 if (!empty($CFG->supportpage
)) {
6341 $signoff .= $CFG->supportpage
."\n";
6347 * Sets specified user's password and send the new password to the user via email.
6349 * @param stdClass $user A {@link $USER} object
6350 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6351 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6353 function setnew_password_and_mail($user, $fasthash = false) {
6356 // We try to send the mail in language the user understands,
6357 // unfortunately the filter_string() does not support alternative langs yet
6358 // so multilang will not work properly for site->fullname.
6359 $lang = empty($user->lang
) ?
get_newuser_language() : $user->lang
;
6363 $supportuser = core_user
::get_support_user();
6365 $newpassword = generate_password();
6367 update_internal_user_password($user, $newpassword, $fasthash);
6369 $a = new stdClass();
6370 $a->firstname
= fullname($user, true);
6371 $a->sitename
= format_string($site->fullname
);
6372 $a->username
= $user->username
;
6373 $a->newpassword
= $newpassword;
6374 $a->link
= $CFG->wwwroot
.'/login/?lang='.$lang;
6375 $a->signoff
= generate_email_signoff();
6377 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6379 $subject = format_string($site->fullname
) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6381 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6382 return email_to_user($user, $supportuser, $subject, $message);
6387 * Resets specified user's password and send the new password to the user via email.
6389 * @param stdClass $user A {@link $USER} object
6390 * @return bool Returns true if mail was sent OK and false if there was an error.
6392 function reset_password_and_mail($user) {
6396 $supportuser = core_user
::get_support_user();
6398 $userauth = get_auth_plugin($user->auth
);
6399 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth
)) {
6400 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6404 $newpassword = generate_password();
6406 if (!$userauth->user_update_password($user, $newpassword)) {
6407 print_error("cannotsetpassword");
6410 $a = new stdClass();
6411 $a->firstname
= $user->firstname
;
6412 $a->lastname
= $user->lastname
;
6413 $a->sitename
= format_string($site->fullname
);
6414 $a->username
= $user->username
;
6415 $a->newpassword
= $newpassword;
6416 $a->link
= $CFG->wwwroot
.'/login/change_password.php';
6417 $a->signoff
= generate_email_signoff();
6419 $message = get_string('newpasswordtext', '', $a);
6421 $subject = format_string($site->fullname
) .': '. get_string('changedpassword');
6423 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6425 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6426 return email_to_user($user, $supportuser, $subject, $message);
6430 * Send email to specified user with confirmation text and activation link.
6432 * @param stdClass $user A {@link $USER} object
6433 * @param string $confirmationurl user confirmation URL
6434 * @return bool Returns true if mail was sent OK and false if there was an error.
6436 function send_confirmation_email($user, $confirmationurl = null) {
6440 $supportuser = core_user
::get_support_user();
6442 $data = new stdClass();
6443 $data->sitename
= format_string($site->fullname
);
6444 $data->admin
= generate_email_signoff();
6446 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname
));
6448 if (empty($confirmationurl)) {
6449 $confirmationurl = '/login/confirm.php';
6452 $confirmationurl = new moodle_url($confirmationurl);
6453 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6454 $confirmationurl->remove_params('data');
6455 $confirmationpath = $confirmationurl->out(false);
6457 // We need to custom encode the username to include trailing dots in the link.
6458 // Because of this custom encoding we can't use moodle_url directly.
6459 // Determine if a query string is present in the confirmation url.
6460 $hasquerystring = strpos($confirmationpath, '?') !== false;
6461 // Perform normal url encoding of the username first.
6462 $username = urlencode($user->username
);
6463 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6464 $username = str_replace('.', '%2E', $username);
6466 $data->link
= $confirmationpath . ( $hasquerystring ?
'&' : '?') . 'data='. $user->secret
.'/'. $username;
6468 $message = get_string('emailconfirmation', '', $data);
6469 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6471 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6472 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6476 * Sends a password change confirmation email.
6478 * @param stdClass $user A {@link $USER} object
6479 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6480 * @return bool Returns true if mail was sent OK and false if there was an error.
6482 function send_password_change_confirmation_email($user, $resetrecord) {
6486 $supportuser = core_user
::get_support_user();
6487 $pwresetmins = isset($CFG->pwresettime
) ?
floor($CFG->pwresettime
/ MINSECS
) : 30;
6489 $data = new stdClass();
6490 $data->firstname
= $user->firstname
;
6491 $data->lastname
= $user->lastname
;
6492 $data->username
= $user->username
;
6493 $data->sitename
= format_string($site->fullname
);
6494 $data->link
= $CFG->wwwroot
.'/login/forgot_password.php?token='. $resetrecord->token
;
6495 $data->admin
= generate_email_signoff();
6496 $data->resetminutes
= $pwresetmins;
6498 $message = get_string('emailresetconfirmation', '', $data);
6499 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname
));
6501 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6502 return email_to_user($user, $supportuser, $subject, $message);
6507 * Sends an email containing information on how to change your password.
6509 * @param stdClass $user A {@link $USER} object
6510 * @return bool Returns true if mail was sent OK and false if there was an error.
6512 function send_password_change_info($user) {
6514 $supportuser = core_user
::get_support_user();
6516 $data = new stdClass();
6517 $data->firstname
= $user->firstname
;
6518 $data->lastname
= $user->lastname
;
6519 $data->username
= $user->username
;
6520 $data->sitename
= format_string($site->fullname
);
6521 $data->admin
= generate_email_signoff();
6523 if (!is_enabled_auth($user->auth
)) {
6524 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6525 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6526 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6527 return email_to_user($user, $supportuser, $subject, $message);
6530 $userauth = get_auth_plugin($user->auth
);
6531 ['subject' => $subject, 'message' => $message] = $userauth->get_password_change_info($user);
6533 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6534 return email_to_user($user, $supportuser, $subject, $message);
6538 * Check that an email is allowed. It returns an error message if there was a problem.
6540 * @param string $email Content of email
6541 * @return string|false
6543 function email_is_not_allowed($email) {
6546 // Comparing lowercase domains.
6547 $email = strtolower($email);
6548 if (!empty($CFG->allowemailaddresses
)) {
6549 $allowed = explode(' ', strtolower($CFG->allowemailaddresses
));
6550 foreach ($allowed as $allowedpattern) {
6551 $allowedpattern = trim($allowedpattern);
6552 if (!$allowedpattern) {
6555 if (strpos($allowedpattern, '.') === 0) {
6556 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6557 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6561 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6565 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses
);
6567 } else if (!empty($CFG->denyemailaddresses
)) {
6568 $denied = explode(' ', strtolower($CFG->denyemailaddresses
));
6569 foreach ($denied as $deniedpattern) {
6570 $deniedpattern = trim($deniedpattern);
6571 if (!$deniedpattern) {
6574 if (strpos($deniedpattern, '.') === 0) {
6575 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6576 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6577 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
6580 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6581 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
6592 * Returns local file storage instance
6594 * @return file_storage
6596 function get_file_storage($reset = false) {
6610 require_once("$CFG->libdir/filelib.php");
6612 $fs = new file_storage();
6618 * Returns local file storage instance
6620 * @return file_browser
6622 function get_file_browser() {
6631 require_once("$CFG->libdir/filelib.php");
6633 $fb = new file_browser();
6639 * Returns file packer
6641 * @param string $mimetype default application/zip
6642 * @return file_packer
6644 function get_file_packer($mimetype='application/zip') {
6647 static $fp = array();
6649 if (isset($fp[$mimetype])) {
6650 return $fp[$mimetype];
6653 switch ($mimetype) {
6654 case 'application/zip':
6655 case 'application/vnd.moodle.profiling':
6656 $classname = 'zip_packer';
6659 case 'application/x-gzip' :
6660 $classname = 'tgz_packer';
6663 case 'application/vnd.moodle.backup':
6664 $classname = 'mbz_packer';
6671 require_once("$CFG->libdir/filestorage/$classname.php");
6672 $fp[$mimetype] = new $classname();
6674 return $fp[$mimetype];
6678 * Returns current name of file on disk if it exists.
6680 * @param string $newfile File to be verified
6681 * @return string Current name of file on disk if true
6683 function valid_uploaded_file($newfile) {
6684 if (empty($newfile)) {
6687 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6688 return $newfile['tmp_name'];
6695 * Returns the maximum size for uploading files.
6697 * There are seven possible upload limits:
6698 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6699 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6700 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6701 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6702 * 5. by the Moodle admin in $CFG->maxbytes
6703 * 6. by the teacher in the current course $course->maxbytes
6704 * 7. by the teacher for the current module, eg $assignment->maxbytes
6706 * These last two are passed to this function as arguments (in bytes).
6707 * Anything defined as 0 is ignored.
6708 * The smallest of all the non-zero numbers is returned.
6710 * @todo Finish documenting this function
6712 * @param int $sitebytes Set maximum size
6713 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6714 * @param int $modulebytes Current module ->maxbytes (in bytes)
6715 * @param bool $unused This parameter has been deprecated and is not used any more.
6716 * @return int The maximum size for uploading files.
6718 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6720 if (! $filesize = ini_get('upload_max_filesize')) {
6723 $minimumsize = get_real_size($filesize);
6725 if ($postsize = ini_get('post_max_size')) {
6726 $postsize = get_real_size($postsize);
6727 if ($postsize < $minimumsize) {
6728 $minimumsize = $postsize;
6732 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6733 $minimumsize = $sitebytes;
6736 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6737 $minimumsize = $coursebytes;
6740 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6741 $minimumsize = $modulebytes;
6744 return $minimumsize;
6748 * Returns the maximum size for uploading files for the current user
6750 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6752 * @param context $context The context in which to check user capabilities
6753 * @param int $sitebytes Set maximum size
6754 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6755 * @param int $modulebytes Current module ->maxbytes (in bytes)
6756 * @param stdClass $user The user
6757 * @param bool $unused This parameter has been deprecated and is not used any more.
6758 * @return int The maximum size for uploading files.
6760 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6768 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6769 return USER_CAN_IGNORE_FILE_SIZE_LIMITS
;
6772 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6776 * Returns an array of possible sizes in local language
6778 * Related to {@link get_max_upload_file_size()} - this function returns an
6779 * array of possible sizes in an array, translated to the
6782 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6784 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6785 * with the value set to 0. This option will be the first in the list.
6787 * @uses SORT_NUMERIC
6788 * @param int $sitebytes Set maximum size
6789 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6790 * @param int $modulebytes Current module ->maxbytes (in bytes)
6791 * @param int|array $custombytes custom upload size/s which will be added to list,
6792 * Only value/s smaller then maxsize will be added to list.
6795 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6798 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6802 if ($sitebytes == 0) {
6803 // Will get the minimum of upload_max_filesize or post_max_size.
6804 $sitebytes = get_max_upload_file_size();
6807 $filesize = array();
6808 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6809 5242880, 10485760, 20971520, 52428800, 104857600,
6810 262144000, 524288000, 786432000, 1073741824,
6811 2147483648, 4294967296, 8589934592);
6813 // If custombytes is given and is valid then add it to the list.
6814 if (is_number($custombytes) and $custombytes > 0) {
6815 $custombytes = (int)$custombytes;
6816 if (!in_array($custombytes, $sizelist)) {
6817 $sizelist[] = $custombytes;
6819 } else if (is_array($custombytes)) {
6820 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6823 // Allow maxbytes to be selected if it falls outside the above boundaries.
6824 if (isset($CFG->maxbytes
) && !in_array(get_real_size($CFG->maxbytes
), $sizelist)) {
6825 // Note: get_real_size() is used in order to prevent problems with invalid values.
6826 $sizelist[] = get_real_size($CFG->maxbytes
);
6829 foreach ($sizelist as $sizebytes) {
6830 if ($sizebytes < $maxsize && $sizebytes > 0) {
6831 $filesize[(string)intval($sizebytes)] = display_size($sizebytes, 0);
6838 (($modulebytes < $coursebytes ||
$coursebytes == 0) &&
6839 ($modulebytes < $sitebytes ||
$sitebytes == 0))) {
6840 $limitlevel = get_string('activity', 'core');
6841 $displaysize = display_size($modulebytes, 0);
6842 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6844 } else if ($coursebytes && ($coursebytes < $sitebytes ||
$sitebytes == 0)) {
6845 $limitlevel = get_string('course', 'core');
6846 $displaysize = display_size($coursebytes, 0);
6847 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6849 } else if ($sitebytes) {
6850 $limitlevel = get_string('site', 'core');
6851 $displaysize = display_size($sitebytes, 0);
6852 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6855 krsort($filesize, SORT_NUMERIC
);
6857 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6858 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) +
$filesize;
6865 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6867 * If excludefiles is defined, then that file/directory is ignored
6868 * If getdirs is true, then (sub)directories are included in the output
6869 * If getfiles is true, then files are included in the output
6870 * (at least one of these must be true!)
6872 * @todo Finish documenting this function. Add examples of $excludefile usage.
6874 * @param string $rootdir A given root directory to start from
6875 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6876 * @param bool $descend If true then subdirectories are recursed as well
6877 * @param bool $getdirs If true then (sub)directories are included in the output
6878 * @param bool $getfiles If true then files are included in the output
6879 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6881 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6885 if (!$getdirs and !$getfiles) { // Nothing to show.
6889 if (!is_dir($rootdir)) { // Must be a directory.
6893 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6897 if (!is_array($excludefiles)) {
6898 $excludefiles = array($excludefiles);
6901 while (false !== ($file = readdir($dir))) {
6902 $firstchar = substr($file, 0, 1);
6903 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6906 $fullfile = $rootdir .'/'. $file;
6907 if (filetype($fullfile) == 'dir') {
6912 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6913 foreach ($subdirs as $subdir) {
6914 $dirs[] = $file .'/'. $subdir;
6917 } else if ($getfiles) {
6930 * Adds up all the files in a directory and works out the size.
6932 * @param string $rootdir The directory to start from
6933 * @param string $excludefile A file to exclude when summing directory size
6934 * @return int The summed size of all files and subfiles within the root directory
6936 function get_directory_size($rootdir, $excludefile='') {
6939 // Do it this way if we can, it's much faster.
6940 if (!empty($CFG->pathtodu
) && is_executable(trim($CFG->pathtodu
))) {
6941 $command = trim($CFG->pathtodu
).' -sk '.escapeshellarg($rootdir);
6944 exec($command, $output, $return);
6945 if (is_array($output)) {
6946 // We told it to return k.
6947 return get_real_size(intval($output[0]).'k');
6951 if (!is_dir($rootdir)) {
6952 // Must be a directory.
6956 if (!$dir = @opendir
($rootdir)) {
6957 // Can't open it for some reason.
6963 while (false !== ($file = readdir($dir))) {
6964 $firstchar = substr($file, 0, 1);
6965 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6968 $fullfile = $rootdir .'/'. $file;
6969 if (filetype($fullfile) == 'dir') {
6970 $size +
= get_directory_size($fullfile, $excludefile);
6972 $size +
= filesize($fullfile);
6981 * Converts bytes into display form
6983 * @param int $size The size to convert to human readable form
6984 * @param int $decimalplaces If specified, uses fixed number of decimal places
6985 * @param string $fixedunits If specified, uses fixed units (e.g. 'KB')
6986 * @return string Display version of size
6988 function display_size($size, int $decimalplaces = 1, string $fixedunits = ''): string {
6992 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS
) {
6993 return get_string('unlimited');
6996 if (empty($units)) {
6997 $units[] = get_string('sizeb');
6998 $units[] = get_string('sizekb');
6999 $units[] = get_string('sizemb');
7000 $units[] = get_string('sizegb');
7001 $units[] = get_string('sizetb');
7002 $units[] = get_string('sizepb');
7005 switch ($fixedunits) {
7025 $magnitude = floor(log($size, 1024));
7026 $magnitude = max(0, min(5, $magnitude));
7029 throw new coding_exception('Unknown fixed units value: ' . $fixedunits);
7032 // Special case for magnitude 0 (bytes) - never use decimal places.
7034 if ($magnitude === 0) {
7035 return round($size) . $nbsp . $units[$magnitude];
7038 // Convert to specified units.
7039 $sizeinunit = $size / 1024 ** $magnitude;
7041 // Fixed decimal places.
7042 return sprintf('%.' . $decimalplaces . 'f', $sizeinunit) . $nbsp . $units[$magnitude];
7046 * Cleans a given filename by removing suspicious or troublesome characters
7048 * @see clean_param()
7049 * @param string $string file name
7050 * @return string cleaned file name
7052 function clean_filename($string) {
7053 return clean_param($string, PARAM_FILE
);
7056 // STRING TRANSLATION.
7059 * Returns the code for the current language
7064 function current_language() {
7065 global $CFG, $USER, $SESSION, $COURSE;
7067 if (!empty($SESSION->forcelang
)) {
7068 // Allows overriding course-forced language (useful for admins to check
7069 // issues in courses whose language they don't understand).
7070 // Also used by some code to temporarily get language-related information in a
7071 // specific language (see force_current_language()).
7072 $return = $SESSION->forcelang
;
7074 } else if (!empty($COURSE->id
) and $COURSE->id
!= SITEID
and !empty($COURSE->lang
)) {
7075 // Course language can override all other settings for this page.
7076 $return = $COURSE->lang
;
7078 } else if (!empty($SESSION->lang
)) {
7079 // Session language can override other settings.
7080 $return = $SESSION->lang
;
7082 } else if (!empty($USER->lang
)) {
7083 $return = $USER->lang
;
7085 } else if (isset($CFG->lang
)) {
7086 $return = $CFG->lang
;
7092 // Just in case this slipped in from somewhere by accident.
7093 $return = str_replace('_utf8', '', $return);
7099 * Returns parent language of current active language if defined
7102 * @param string $lang null means current language
7105 function get_parent_language($lang=null) {
7107 $parentlang = get_string_manager()->get_string('parentlanguage', 'langconfig', null, $lang);
7109 if ($parentlang === 'en') {
7117 * Force the current language to get strings and dates localised in the given language.
7119 * After calling this function, all strings will be provided in the given language
7120 * until this function is called again, or equivalent code is run.
7122 * @param string $language
7123 * @return string previous $SESSION->forcelang value
7125 function force_current_language($language) {
7127 $sessionforcelang = isset($SESSION->forcelang
) ?
$SESSION->forcelang
: '';
7128 if ($language !== $sessionforcelang) {
7129 // Seting forcelang to null or an empty string disables it's effect.
7130 if (empty($language) ||
get_string_manager()->translation_exists($language, false)) {
7131 $SESSION->forcelang
= $language;
7135 return $sessionforcelang;
7139 * Returns current string_manager instance.
7141 * The param $forcereload is needed for CLI installer only where the string_manager instance
7142 * must be replaced during the install.php script life time.
7145 * @param bool $forcereload shall the singleton be released and new instance created instead?
7146 * @return core_string_manager
7148 function get_string_manager($forcereload=false) {
7151 static $singleton = null;
7156 if ($singleton === null) {
7157 if (empty($CFG->early_install_lang
)) {
7159 $transaliases = array();
7160 if (empty($CFG->langlist
)) {
7161 $translist = array();
7163 $translist = explode(',', $CFG->langlist
);
7164 $translist = array_map('trim', $translist);
7165 // Each language in the $CFG->langlist can has an "alias" that would substitute the default language name.
7166 foreach ($translist as $i => $value) {
7167 $parts = preg_split('/\s*\|\s*/', $value, 2);
7168 if (count($parts) == 2) {
7169 $transaliases[$parts[0]] = $parts[1];
7170 $translist[$i] = $parts[0];
7175 if (!empty($CFG->config_php_settings
['customstringmanager'])) {
7176 $classname = $CFG->config_php_settings
['customstringmanager'];
7178 if (class_exists($classname)) {
7179 $implements = class_implements($classname);
7181 if (isset($implements['core_string_manager'])) {
7182 $singleton = new $classname($CFG->langotherroot
, $CFG->langlocalroot
, $translist, $transaliases);
7186 debugging('Unable to instantiate custom string manager: class '.$classname.
7187 ' does not implement the core_string_manager interface.');
7191 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7195 $singleton = new core_string_manager_standard($CFG->langotherroot
, $CFG->langlocalroot
, $translist, $transaliases);
7198 $singleton = new core_string_manager_install();
7206 * Returns a localized string.
7208 * Returns the translated string specified by $identifier as
7209 * for $module. Uses the same format files as STphp.
7210 * $a is an object, string or number that can be used
7211 * within translation strings
7213 * eg 'hello {$a->firstname} {$a->lastname}'
7216 * If you would like to directly echo the localized string use
7217 * the function {@link print_string()}
7219 * Example usage of this function involves finding the string you would
7220 * like a local equivalent of and using its identifier and module information
7221 * to retrieve it.<br/>
7222 * If you open moodle/lang/en/moodle.php and look near line 278
7223 * you will find a string to prompt a user for their word for 'course'
7225 * $string['course'] = 'Course';
7227 * So if you want to display the string 'Course'
7228 * in any language that supports it on your site
7229 * you just need to use the identifier 'course'
7231 * $mystring = '<strong>'. get_string('course') .'</strong>';
7234 * If the string you want is in another file you'd take a slightly
7235 * different approach. Looking in moodle/lang/en/calendar.php you find
7238 * $string['typecourse'] = 'Course event';
7240 * If you want to display the string "Course event" in any language
7241 * supported you would use the identifier 'typecourse' and the module 'calendar'
7242 * (because it is in the file calendar.php):
7244 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7247 * As a last resort, should the identifier fail to map to a string
7248 * the returned string will be [[ $identifier ]]
7250 * In Moodle 2.3 there is a new argument to this function $lazyload.
7251 * Setting $lazyload to true causes get_string to return a lang_string object
7252 * rather than the string itself. The fetching of the string is then put off until
7253 * the string object is first used. The object can be used by calling it's out
7254 * method or by casting the object to a string, either directly e.g.
7255 * (string)$stringobject
7256 * or indirectly by using the string within another string or echoing it out e.g.
7257 * echo $stringobject
7258 * return "<p>{$stringobject}</p>";
7259 * It is worth noting that using $lazyload and attempting to use the string as an
7260 * array key will cause a fatal error as objects cannot be used as array keys.
7261 * But you should never do that anyway!
7262 * For more information {@link lang_string}
7265 * @param string $identifier The key identifier for the localized string
7266 * @param string $component The module where the key identifier is stored,
7267 * usually expressed as the filename in the language pack without the
7268 * .php on the end but can also be written as mod/forum or grade/export/xls.
7269 * If none is specified then moodle.php is used.
7270 * @param string|object|array $a An object, string or number that can be used
7271 * within translation strings
7272 * @param bool $lazyload If set to true a string object is returned instead of
7273 * the string itself. The string then isn't calculated until it is first used.
7274 * @return string The localized string.
7275 * @throws coding_exception
7277 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7280 // If the lazy load argument has been supplied return a lang_string object
7282 // We need to make sure it is true (and a bool) as you will see below there
7283 // used to be a forth argument at one point.
7284 if ($lazyload === true) {
7285 return new lang_string($identifier, $component, $a);
7288 if ($CFG->debugdeveloper
&& clean_param($identifier, PARAM_STRINGID
) === '') {
7289 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER
);
7292 // There is now a forth argument again, this time it is a boolean however so
7293 // we can still check for the old extralocations parameter.
7294 if (!is_bool($lazyload) && !empty($lazyload)) {
7295 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7298 if (strpos($component, '/') !== false) {
7299 debugging('The module name you passed to get_string is the deprecated format ' .
7300 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER
);
7301 $componentpath = explode('/', $component);
7303 switch ($componentpath[0]) {
7305 $component = $componentpath[1];
7309 $component = 'block_'.$componentpath[1];
7312 $component = 'enrol_'.$componentpath[1];
7315 $component = 'format_'.$componentpath[1];
7318 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7323 $result = get_string_manager()->get_string($identifier, $component, $a);
7325 // Debugging feature lets you display string identifier and component.
7326 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
7327 $result .= ' {' . $identifier . '/' . $component . '}';
7333 * Converts an array of strings to their localized value.
7335 * @param array $array An array of strings
7336 * @param string $component The language module that these strings can be found in.
7337 * @return stdClass translated strings.
7339 function get_strings($array, $component = '') {
7340 $string = new stdClass
;
7341 foreach ($array as $item) {
7342 $string->$item = get_string($item, $component);
7348 * Prints out a translated string.
7350 * Prints out a translated string using the return value from the {@link get_string()} function.
7352 * Example usage of this function when the string is in the moodle.php file:<br/>
7355 * print_string('course');
7359 * Example usage of this function when the string is not in the moodle.php file:<br/>
7362 * print_string('typecourse', 'calendar');
7367 * @param string $identifier The key identifier for the localized string
7368 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7369 * @param string|object|array $a An object, string or number that can be used within translation strings
7371 function print_string($identifier, $component = '', $a = null) {
7372 echo get_string($identifier, $component, $a);
7376 * Returns a list of charset codes
7378 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7379 * (checking that such charset is supported by the texlib library!)
7381 * @return array And associative array with contents in the form of charset => charset
7383 function get_list_of_charsets() {
7386 'EUC-JP' => 'EUC-JP',
7387 'ISO-2022-JP'=> 'ISO-2022-JP',
7388 'ISO-8859-1' => 'ISO-8859-1',
7389 'SHIFT-JIS' => 'SHIFT-JIS',
7390 'GB2312' => 'GB2312',
7391 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7392 'UTF-8' => 'UTF-8');
7400 * Returns a list of valid and compatible themes
7404 function get_list_of_themes() {
7409 if (!empty($CFG->themelist
)) { // Use admin's list of themes.
7410 $themelist = explode(',', $CFG->themelist
);
7412 $themelist = array_keys(core_component
::get_plugin_list("theme"));
7415 foreach ($themelist as $key => $themename) {
7416 $theme = theme_config
::load($themename);
7417 $themes[$themename] = $theme;
7420 core_collator
::asort_objects_by_method($themes, 'get_theme_name');
7426 * Factory function for emoticon_manager
7428 * @return emoticon_manager singleton
7430 function get_emoticon_manager() {
7431 static $singleton = null;
7433 if (is_null($singleton)) {
7434 $singleton = new emoticon_manager();
7441 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7443 * Whenever this manager mentiones 'emoticon object', the following data
7444 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7445 * altidentifier and altcomponent
7447 * @see admin_setting_emoticons
7449 * @copyright 2010 David Mudrak
7450 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7452 class emoticon_manager
{
7455 * Returns the currently enabled emoticons
7457 * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
7458 * @return array of emoticon objects
7460 public function get_emoticons($selectable = false) {
7462 $notselectable = ['martin', 'egg'];
7464 if (empty($CFG->emoticons
)) {
7468 $emoticons = $this->decode_stored_config($CFG->emoticons
);
7470 if (!is_array($emoticons)) {
7471 // Something is wrong with the format of stored setting.
7472 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL
);
7476 foreach ($emoticons as $index => $emote) {
7477 if (in_array($emote->altidentifier
, $notselectable)) {
7479 unset($emoticons[$index]);
7488 * Converts emoticon object into renderable pix_emoticon object
7490 * @param stdClass $emoticon emoticon object
7491 * @param array $attributes explicit HTML attributes to set
7492 * @return pix_emoticon
7494 public function prepare_renderable_emoticon(stdClass
$emoticon, array $attributes = array()) {
7495 $stringmanager = get_string_manager();
7496 if ($stringmanager->string_exists($emoticon->altidentifier
, $emoticon->altcomponent
)) {
7497 $alt = get_string($emoticon->altidentifier
, $emoticon->altcomponent
);
7499 $alt = s($emoticon->text
);
7501 return new pix_emoticon($emoticon->imagename
, $alt, $emoticon->imagecomponent
, $attributes);
7505 * Encodes the array of emoticon objects into a string storable in config table
7507 * @see self::decode_stored_config()
7508 * @param array $emoticons array of emtocion objects
7511 public function encode_stored_config(array $emoticons) {
7512 return json_encode($emoticons);
7516 * Decodes the string into an array of emoticon objects
7518 * @see self::encode_stored_config()
7519 * @param string $encoded
7520 * @return string|null
7522 public function decode_stored_config($encoded) {
7523 $decoded = json_decode($encoded);
7524 if (!is_array($decoded)) {
7531 * Returns default set of emoticons supported by Moodle
7533 * @return array of sdtClasses
7535 public function default_emoticons() {
7537 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7538 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7539 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7540 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7541 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7542 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7543 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7544 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7545 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7546 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7547 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7548 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7549 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7550 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7551 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7552 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7553 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7554 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7555 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7556 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7557 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7558 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7559 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7560 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7561 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7562 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7563 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7564 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7565 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7566 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7571 * Helper method preparing the stdClass with the emoticon properties
7573 * @param string|array $text or array of strings
7574 * @param string $imagename to be used by {@link pix_emoticon}
7575 * @param string $altidentifier alternative string identifier, null for no alt
7576 * @param string $altcomponent where the alternative string is defined
7577 * @param string $imagecomponent to be used by {@link pix_emoticon}
7580 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7581 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7582 return (object)array(
7584 'imagename' => $imagename,
7585 'imagecomponent' => $imagecomponent,
7586 'altidentifier' => $altidentifier,
7587 'altcomponent' => $altcomponent,
7597 * @param string $data Data to encrypt.
7598 * @return string The now encrypted data.
7600 function rc4encrypt($data) {
7601 return endecrypt(get_site_identifier(), $data, '');
7607 * @param string $data Data to decrypt.
7608 * @return string The now decrypted data.
7610 function rc4decrypt($data) {
7611 return endecrypt(get_site_identifier(), $data, 'de');
7615 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7617 * @todo Finish documenting this function
7619 * @param string $pwd The password to use when encrypting or decrypting
7620 * @param string $data The data to be decrypted/encrypted
7621 * @param string $case Either 'de' for decrypt or '' for encrypt
7624 function endecrypt ($pwd, $data, $case) {
7626 if ($case == 'de') {
7627 $data = urldecode($data);
7632 $pwdlength = strlen($pwd);
7634 for ($i = 0; $i <= 255; $i++
) {
7635 $key[$i] = ord(substr($pwd, ($i %
$pwdlength), 1));
7641 for ($i = 0; $i <= 255; $i++
) {
7642 $x = ($x +
$box[$i] +
$key[$i]) %
256;
7643 $tempswap = $box[$i];
7644 $box[$i] = $box[$x];
7645 $box[$x] = $tempswap;
7653 for ($i = 0; $i < strlen($data); $i++
) {
7654 $a = ($a +
1) %
256;
7655 $j = ($j +
$box[$a]) %
256;
7657 $box[$a] = $box[$j];
7659 $k = $box[(($box[$a] +
$box[$j]) %
256)];
7660 $cipherby = ord(substr($data, $i, 1)) ^
$k;
7661 $cipher .= chr($cipherby);
7664 if ($case == 'de') {
7665 $cipher = urldecode(urlencode($cipher));
7667 $cipher = urlencode($cipher);
7673 // ENVIRONMENT CHECKING.
7676 * This method validates a plug name. It is much faster than calling clean_param.
7678 * @param string $name a string that might be a plugin name.
7679 * @return bool if this string is a valid plugin name.
7681 function is_valid_plugin_name($name) {
7682 // This does not work for 'mod', bad luck, use any other type.
7683 return core_component
::is_valid_plugin_name('tool', $name);
7687 * Get a list of all the plugins of a given type that define a certain API function
7688 * in a certain file. The plugin component names and function names are returned.
7690 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7691 * @param string $function the part of the name of the function after the
7692 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7693 * names like report_courselist_hook.
7694 * @param string $file the name of file within the plugin that defines the
7695 * function. Defaults to lib.php.
7696 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7697 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7699 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7702 // We don't include here as all plugin types files would be included.
7703 $plugins = get_plugins_with_function($function, $file, false);
7705 if (empty($plugins[$plugintype])) {
7709 $allplugins = core_component
::get_plugin_list($plugintype);
7711 // Reformat the array and include the files.
7712 $pluginfunctions = array();
7713 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7715 // Check that it has not been removed and the file is still available.
7716 if (!empty($allplugins[$pluginname])) {
7718 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR
. $file;
7719 if (file_exists($filepath)) {
7720 include_once($filepath);
7722 // Now that the file is loaded, we must verify the function still exists.
7723 if (function_exists($functionname)) {
7724 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7726 // Invalidate the cache for next run.
7727 \cache_helper
::invalidate_by_definition('core', 'plugin_functions');
7733 return $pluginfunctions;
7737 * Get a list of all the plugins that define a certain API function in a certain file.
7739 * @param string $function the part of the name of the function after the
7740 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7741 * names like report_courselist_hook.
7742 * @param string $file the name of file within the plugin that defines the
7743 * function. Defaults to lib.php.
7744 * @param bool $include Whether to include the files that contain the functions or not.
7745 * @return array with [plugintype][plugin] = functionname
7747 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7750 if (during_initial_install() ||
isset($CFG->upgraderunning
)) {
7751 // API functions _must not_ be called during an installation or upgrade.
7755 $cache = \cache
::make('core', 'plugin_functions');
7757 // Including both although I doubt that we will find two functions definitions with the same name.
7758 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7759 $key = $function . '_' . clean_param($file, PARAM_ALPHA
);
7760 $pluginfunctions = $cache->get($key);
7763 // Use the plugin manager to check that plugins are currently installed.
7764 $pluginmanager = \core_plugin_manager
::instance();
7766 if ($pluginfunctions !== false) {
7768 // Checking that the files are still available.
7769 foreach ($pluginfunctions as $plugintype => $plugins) {
7771 $allplugins = \core_component
::get_plugin_list($plugintype);
7772 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7773 foreach ($plugins as $plugin => $function) {
7774 if (!isset($installedplugins[$plugin])) {
7775 // Plugin code is still present on disk but it is not installed.
7780 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7781 if (empty($allplugins[$plugin])) {
7786 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR
. $file);
7787 if ($include && $fileexists) {
7788 // Include the files if it was requested.
7789 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR
. $file);
7790 } else if (!$fileexists) {
7791 // If the file is not available any more it should not be returned.
7796 // Check if the function still exists in the file.
7797 if ($include && !function_exists($function)) {
7804 // If the cache is dirty, we should fall through and let it rebuild.
7806 return $pluginfunctions;
7810 $pluginfunctions = array();
7812 // To fill the cached. Also, everything should continue working with cache disabled.
7813 $plugintypes = \core_component
::get_plugin_types();
7814 foreach ($plugintypes as $plugintype => $unused) {
7816 // We need to include files here.
7817 $pluginswithfile = \core_component
::get_plugin_list_with_file($plugintype, $file, true);
7818 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7819 foreach ($pluginswithfile as $plugin => $notused) {
7821 if (!isset($installedplugins[$plugin])) {
7825 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7827 $pluginfunction = false;
7828 if (function_exists($fullfunction)) {
7829 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7830 $pluginfunction = $fullfunction;
7832 } else if ($plugintype === 'mod') {
7833 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7834 $shortfunction = $plugin . '_' . $function;
7835 if (function_exists($shortfunction)) {
7836 $pluginfunction = $shortfunction;
7840 if ($pluginfunction) {
7841 if (empty($pluginfunctions[$plugintype])) {
7842 $pluginfunctions[$plugintype] = array();
7844 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7849 $cache->set($key, $pluginfunctions);
7851 return $pluginfunctions;
7856 * Lists plugin-like directories within specified directory
7858 * This function was originally used for standard Moodle plugins, please use
7859 * new core_component::get_plugin_list() now.
7861 * This function is used for general directory listing and backwards compatility.
7863 * @param string $directory relative directory from root
7864 * @param string $exclude dir name to exclude from the list (defaults to none)
7865 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7866 * @return array Sorted array of directory names found under the requested parameters
7868 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7873 if (empty($basedir)) {
7874 $basedir = $CFG->dirroot
.'/'. $directory;
7877 $basedir = $basedir .'/'. $directory;
7880 if ($CFG->debugdeveloper
and empty($exclude)) {
7881 // Make sure devs do not use this to list normal plugins,
7882 // this is intended for general directories that are not plugins!
7884 $subtypes = core_component
::get_plugin_types();
7885 if (in_array($basedir, $subtypes)) {
7886 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER
);
7891 $ignorelist = array_flip(array_filter([
7903 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7904 if (!$dirhandle = opendir($basedir)) {
7905 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER
);
7908 while (false !== ($dir = readdir($dirhandle))) {
7909 if (strpos($dir, '.') === 0) {
7910 // Ignore directories starting with .
7911 // These are treated as hidden directories.
7914 if (array_key_exists($dir, $ignorelist)) {
7915 // This directory features on the ignore list.
7918 if (filetype($basedir .'/'. $dir) != 'dir') {
7923 closedir($dirhandle);
7932 * Invoke plugin's callback functions
7934 * @param string $type plugin type e.g. 'mod'
7935 * @param string $name plugin name
7936 * @param string $feature feature name
7937 * @param string $action feature's action
7938 * @param array $params parameters of callback function, should be an array
7939 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7942 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7944 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7945 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7949 * Invoke component's callback functions
7951 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7952 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7953 * @param array $params parameters of callback function
7954 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7957 function component_callback($component, $function, array $params = array(), $default = null) {
7959 $functionname = component_callback_exists($component, $function);
7961 if ($params && (array_keys($params) !== range(0, count($params) - 1))) {
7962 // PHP 8 allows to have associative arrays in the call_user_func_array() parameters but
7963 // PHP 7 does not. Using associative arrays can result in different behavior in different PHP versions.
7964 // See https://php.watch/versions/8.0/named-parameters#named-params-call_user_func_array
7965 // This check can be removed when minimum PHP version for Moodle is raised to 8.
7966 debugging('Parameters array can not be an associative array while Moodle supports both PHP 7 and PHP 8.',
7968 $params = array_values($params);
7971 if ($functionname) {
7972 // Function exists, so just return function result.
7973 $ret = call_user_func_array($functionname, $params);
7974 if (is_null($ret)) {
7984 * Determine if a component callback exists and return the function name to call. Note that this
7985 * function will include the required library files so that the functioname returned can be
7988 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7989 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7990 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7991 * @throws coding_exception if invalid component specfied
7993 function component_callback_exists($component, $function) {
7994 global $CFG; // This is needed for the inclusions.
7996 $cleancomponent = clean_param($component, PARAM_COMPONENT
);
7997 if (empty($cleancomponent)) {
7998 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8000 $component = $cleancomponent;
8002 list($type, $name) = core_component
::normalize_component($component);
8003 $component = $type . '_' . $name;
8005 $oldfunction = $name.'_'.$function;
8006 $function = $component.'_'.$function;
8008 $dir = core_component
::get_component_directory($component);
8010 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8013 // Load library and look for function.
8014 if (file_exists($dir.'/lib.php')) {
8015 require_once($dir.'/lib.php');
8018 if (!function_exists($function) and function_exists($oldfunction)) {
8019 if ($type !== 'mod' and $type !== 'core') {
8020 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER
);
8022 $function = $oldfunction;
8025 if (function_exists($function)) {
8032 * Call the specified callback method on the provided class.
8034 * If the callback returns null, then the default value is returned instead.
8035 * If the class does not exist, then the default value is returned.
8037 * @param string $classname The name of the class to call upon.
8038 * @param string $methodname The name of the staticically defined method on the class.
8039 * @param array $params The arguments to pass into the method.
8040 * @param mixed $default The default value.
8041 * @return mixed The return value.
8043 function component_class_callback($classname, $methodname, array $params, $default = null) {
8044 if (!class_exists($classname)) {
8048 if (!method_exists($classname, $methodname)) {
8052 $fullfunction = $classname . '::' . $methodname;
8053 $result = call_user_func_array($fullfunction, $params);
8055 if (null === $result) {
8063 * Checks whether a plugin supports a specified feature.
8065 * @param string $type Plugin type e.g. 'mod'
8066 * @param string $name Plugin name e.g. 'forum'
8067 * @param string $feature Feature code (FEATURE_xx constant)
8068 * @param mixed $default default value if feature support unknown
8069 * @return mixed Feature result (false if not supported, null if feature is unknown,
8070 * otherwise usually true but may have other feature-specific value such as array)
8071 * @throws coding_exception
8073 function plugin_supports($type, $name, $feature, $default = null) {
8076 if ($type === 'mod' and $name === 'NEWMODULE') {
8077 // Somebody forgot to rename the module template.
8081 $component = clean_param($type . '_' . $name, PARAM_COMPONENT
);
8082 if (empty($component)) {
8083 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8088 if ($type === 'mod') {
8089 // We need this special case because we support subplugins in modules,
8090 // otherwise it would end up in infinite loop.
8091 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8092 include_once("$CFG->dirroot/mod/$name/lib.php");
8093 $function = $component.'_supports';
8094 if (!function_exists($function)) {
8095 // Legacy non-frankenstyle function name.
8096 $function = $name.'_supports';
8101 if (!$path = core_component
::get_plugin_directory($type, $name)) {
8102 // Non existent plugin type.
8105 if (file_exists("$path/lib.php")) {
8106 include_once("$path/lib.php");
8107 $function = $component.'_supports';
8111 if ($function and function_exists($function)) {
8112 $supports = $function($feature);
8113 if (is_null($supports)) {
8114 // Plugin does not know - use default.
8121 // Plugin does not care, so use default.
8126 * Returns true if the current version of PHP is greater that the specified one.
8128 * @todo Check PHP version being required here is it too low?
8130 * @param string $version The version of php being tested.
8133 function check_php_version($version='5.2.4') {
8134 return (version_compare(phpversion(), $version) >= 0);
8138 * Determine if moodle installation requires update.
8140 * Checks version numbers of main code and all plugins to see
8141 * if there are any mismatches.
8145 function moodle_needs_upgrading() {
8148 if (empty($CFG->version
)) {
8152 // There is no need to purge plugininfo caches here because
8153 // these caches are not used during upgrade and they are purged after
8156 if (empty($CFG->allversionshash
)) {
8160 $hash = core_component
::get_all_versions_hash();
8162 return ($hash !== $CFG->allversionshash
);
8166 * Returns the major version of this site
8168 * Moodle version numbers consist of three numbers separated by a dot, for
8169 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
8170 * called major version. This function extracts the major version from either
8171 * $CFG->release (default) or eventually from the $release variable defined in
8172 * the main version.php.
8174 * @param bool $fromdisk should the version if source code files be used
8175 * @return string|false the major version like '2.3', false if could not be determined
8177 function moodle_major_version($fromdisk = false) {
8182 require($CFG->dirroot
.'/version.php');
8183 if (empty($release)) {
8188 if (empty($CFG->release
)) {
8191 $release = $CFG->release
;
8194 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8204 * Gets the system locale
8206 * @return string Retuns the current locale.
8208 function moodle_getlocale() {
8211 // Fetch the correct locale based on ostype.
8212 if ($CFG->ostype
== 'WINDOWS') {
8213 $stringtofetch = 'localewin';
8215 $stringtofetch = 'locale';
8218 if (!empty($CFG->locale
)) { // Override locale for all language packs.
8219 return $CFG->locale
;
8222 return get_string($stringtofetch, 'langconfig');
8226 * Sets the system locale
8229 * @param string $locale Can be used to force a locale
8231 function moodle_setlocale($locale='') {
8234 static $currentlocale = ''; // Last locale caching.
8236 $oldlocale = $currentlocale;
8238 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8239 if (!empty($locale)) {
8240 $currentlocale = $locale;
8242 $currentlocale = moodle_getlocale();
8245 // Do nothing if locale already set up.
8246 if ($oldlocale == $currentlocale) {
8250 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8251 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8252 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8254 // Get current values.
8255 $monetary= setlocale (LC_MONETARY
, 0);
8256 $numeric = setlocale (LC_NUMERIC
, 0);
8257 $ctype = setlocale (LC_CTYPE
, 0);
8258 if ($CFG->ostype
!= 'WINDOWS') {
8259 $messages= setlocale (LC_MESSAGES
, 0);
8261 // Set locale to all.
8262 $result = setlocale (LC_ALL
, $currentlocale);
8263 // If setting of locale fails try the other utf8 or utf-8 variant,
8264 // some operating systems support both (Debian), others just one (OSX).
8265 if ($result === false) {
8266 if (stripos($currentlocale, '.UTF-8') !== false) {
8267 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8268 setlocale (LC_ALL
, $newlocale);
8269 } else if (stripos($currentlocale, '.UTF8') !== false) {
8270 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8271 setlocale (LC_ALL
, $newlocale);
8275 setlocale (LC_MONETARY
, $monetary);
8276 setlocale (LC_NUMERIC
, $numeric);
8277 if ($CFG->ostype
!= 'WINDOWS') {
8278 setlocale (LC_MESSAGES
, $messages);
8280 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8281 // To workaround a well-known PHP problem with Turkish letter Ii.
8282 setlocale (LC_CTYPE
, $ctype);
8287 * Count words in a string.
8289 * Words are defined as things between whitespace.
8292 * @param string $string The text to be searched for words. May be HTML.
8293 * @return int The count of words in the specified string
8295 function count_words($string) {
8296 // Before stripping tags, add a space after the close tag of anything that is not obviously inline.
8297 // Also, br is a special case because it definitely delimits a word, but has no close tag.
8298 $string = preg_replace('~
8299 ( # Capture the tag we match.
8300 </ # Start of close tag.
8301 (?! # Do not match any of these specific close tag names.
8302 a> | b> | del> | em> | i> |
8303 ins> | s> | small> |
8304 strong> | sub> | sup> | u>
8306 \w+ # But, apart from those execptions, match any tag name.
8307 > # End of close tag.
8309 <br> | <br\s*/> # Special cases that are not close tags.
8311 ~x', '$1 ', $string); // Add a space after the close tag.
8312 // Now remove HTML tags.
8313 $string = strip_tags($string);
8314 // Decode HTML entities.
8315 $string = html_entity_decode($string);
8317 // Now, the word count is the number of blocks of characters separated
8318 // by any sort of space. That seems to be the definition used by all other systems.
8319 // To be precise about what is considered to separate words:
8320 // * Anything that Unicode considers a 'Separator'
8321 // * Anything that Unicode considers a 'Control character'
8322 // * An em- or en- dash.
8323 return count(preg_split('~[\p{Z}\p{Cc}—–]+~u', $string, -1, PREG_SPLIT_NO_EMPTY
));
8327 * Count letters in a string.
8329 * Letters are defined as chars not in tags and different from whitespace.
8332 * @param string $string The text to be searched for letters. May be HTML.
8333 * @return int The count of letters in the specified text.
8335 function count_letters($string) {
8336 $string = strip_tags($string); // Tags are out now.
8337 $string = html_entity_decode($string);
8338 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8340 return core_text
::strlen($string);
8344 * Generate and return a random string of the specified length.
8346 * @param int $length The length of the string to be created.
8349 function random_string($length=15) {
8350 $randombytes = random_bytes_emulate($length);
8351 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8352 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8353 $pool .= '0123456789';
8354 $poollen = strlen($pool);
8356 for ($i = 0; $i < $length; $i++
) {
8357 $rand = ord($randombytes[$i]);
8358 $string .= substr($pool, ($rand%
($poollen)), 1);
8364 * Generate a complex random string (useful for md5 salts)
8366 * This function is based on the above {@link random_string()} however it uses a
8367 * larger pool of characters and generates a string between 24 and 32 characters
8369 * @param int $length Optional if set generates a string to exactly this length
8372 function complex_random_string($length=null) {
8373 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8374 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8375 $poollen = strlen($pool);
8376 if ($length===null) {
8377 $length = floor(rand(24, 32));
8379 $randombytes = random_bytes_emulate($length);
8381 for ($i = 0; $i < $length; $i++
) {
8382 $rand = ord($randombytes[$i]);
8383 $string .= $pool[($rand%
$poollen)];
8389 * Try to generates cryptographically secure pseudo-random bytes.
8391 * Note this is achieved by fallbacking between:
8392 * - PHP 7 random_bytes().
8393 * - OpenSSL openssl_random_pseudo_bytes().
8394 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8396 * @param int $length requested length in bytes
8397 * @return string binary data
8399 function random_bytes_emulate($length) {
8402 debugging('Invalid random bytes length', DEBUG_DEVELOPER
);
8405 if (function_exists('random_bytes')) {
8406 // Use PHP 7 goodness.
8407 $hash = @random_bytes
($length);
8408 if ($hash !== false) {
8412 if (function_exists('openssl_random_pseudo_bytes')) {
8413 // If you have the openssl extension enabled.
8414 $hash = openssl_random_pseudo_bytes($length);
8415 if ($hash !== false) {
8420 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8421 $staticdata = serialize($CFG) . serialize($_SERVER);
8424 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8425 } while (strlen($hash) < $length);
8427 return substr($hash, 0, $length);
8431 * Given some text (which may contain HTML) and an ideal length,
8432 * this function truncates the text neatly on a word boundary if possible
8435 * @param string $text text to be shortened
8436 * @param int $ideal ideal string length
8437 * @param boolean $exact if false, $text will not be cut mid-word
8438 * @param string $ending The string to append if the passed string is truncated
8439 * @return string $truncate shortened string
8441 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8442 // If the plain text is shorter than the maximum length, return the whole text.
8443 if (core_text
::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8447 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8448 // and only tag in its 'line'.
8449 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER
);
8451 $totallength = core_text
::strlen($ending);
8454 // This array stores information about open and close tags and their position
8455 // in the truncated string. Each item in the array is an object with fields
8456 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8457 // (byte position in truncated text).
8458 $tagdetails = array();
8460 foreach ($lines as $linematchings) {
8461 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8462 if (!empty($linematchings[1])) {
8463 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8464 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8465 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8466 // Record closing tag.
8467 $tagdetails[] = (object) array(
8469 'tag' => core_text
::strtolower($tagmatchings[1]),
8470 'pos' => core_text
::strlen($truncate),
8473 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8474 // Record opening tag.
8475 $tagdetails[] = (object) array(
8477 'tag' => core_text
::strtolower($tagmatchings[1]),
8478 'pos' => core_text
::strlen($truncate),
8480 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8481 $tagdetails[] = (object) array(
8483 'tag' => core_text
::strtolower('if'),
8484 'pos' => core_text
::strlen($truncate),
8486 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8487 $tagdetails[] = (object) array(
8489 'tag' => core_text
::strtolower('if'),
8490 'pos' => core_text
::strlen($truncate),
8494 // Add html-tag to $truncate'd text.
8495 $truncate .= $linematchings[1];
8498 // Calculate the length of the plain text part of the line; handle entities as one character.
8499 $contentlength = core_text
::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8500 if ($totallength +
$contentlength > $ideal) {
8501 // The number of characters which are left.
8502 $left = $ideal - $totallength;
8503 $entitieslength = 0;
8504 // Search for html entities.
8505 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
)) {
8506 // Calculate the real length of all entities in the legal range.
8507 foreach ($entities[0] as $entity) {
8508 if ($entity[1]+
1-$entitieslength <= $left) {
8510 $entitieslength +
= core_text
::strlen($entity[0]);
8512 // No more characters left.
8517 $breakpos = $left +
$entitieslength;
8519 // If the words shouldn't be cut in the middle...
8521 // Search the last occurence of a space.
8522 for (; $breakpos > 0; $breakpos--) {
8523 if ($char = core_text
::substr($linematchings[2], $breakpos, 1)) {
8524 if ($char === '.' or $char === ' ') {
8527 } else if (strlen($char) > 2) {
8528 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8535 if ($breakpos == 0) {
8536 // This deals with the test_shorten_text_no_spaces case.
8537 $breakpos = $left +
$entitieslength;
8538 } else if ($breakpos > $left +
$entitieslength) {
8539 // This deals with the previous for loop breaking on the first char.
8540 $breakpos = $left +
$entitieslength;
8543 $truncate .= core_text
::substr($linematchings[2], 0, $breakpos);
8544 // Maximum length is reached, so get off the loop.
8547 $truncate .= $linematchings[2];
8548 $totallength +
= $contentlength;
8551 // If the maximum length is reached, get off the loop.
8552 if ($totallength >= $ideal) {
8557 // Add the defined ending to the text.
8558 $truncate .= $ending;
8560 // Now calculate the list of open html tags based on the truncate position.
8561 $opentags = array();
8562 foreach ($tagdetails as $taginfo) {
8563 if ($taginfo->open
) {
8564 // Add tag to the beginning of $opentags list.
8565 array_unshift($opentags, $taginfo->tag
);
8567 // Can have multiple exact same open tags, close the last one.
8568 $pos = array_search($taginfo->tag
, array_reverse($opentags, true));
8569 if ($pos !== false) {
8570 unset($opentags[$pos]);
8575 // Close all unclosed html-tags.
8576 foreach ($opentags as $tag) {
8577 if ($tag === 'if') {
8578 $truncate .= '<!--<![endif]-->';
8580 $truncate .= '</' . $tag . '>';
8588 * Shortens a given filename by removing characters positioned after the ideal string length.
8589 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8590 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8592 * @param string $filename file name
8593 * @param int $length ideal string length
8594 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8595 * @return string $shortened shortened file name
8597 function shorten_filename($filename, $length = MAX_FILENAME_SIZE
, $includehash = false) {
8598 $shortened = $filename;
8599 // Extract a part of the filename if it's char size exceeds the ideal string length.
8600 if (core_text
::strlen($filename) > $length) {
8601 // Exclude extension if present in filename.
8602 $mimetypes = get_mimetypes_array();
8603 $extension = pathinfo($filename, PATHINFO_EXTENSION
);
8604 if ($extension && !empty($mimetypes[$extension])) {
8605 $basename = pathinfo($filename, PATHINFO_FILENAME
);
8606 $hash = empty($includehash) ?
'' : ' - ' . substr(sha1($basename), 0, 10);
8607 $shortened = core_text
::substr($basename, 0, $length - strlen($hash)) . $hash;
8608 $shortened .= '.' . $extension;
8610 $hash = empty($includehash) ?
'' : ' - ' . substr(sha1($filename), 0, 10);
8611 $shortened = core_text
::substr($filename, 0, $length - strlen($hash)) . $hash;
8618 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8620 * @param array $path The paths to reduce the length.
8621 * @param int $length Ideal string length
8622 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8623 * @return array $result Shortened paths in array.
8625 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE
, $includehash = false) {
8628 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8629 $carry[] = shorten_filename($singlepath, $length, $includehash);
8637 * Given dates in seconds, how many weeks is the date from startdate
8638 * The first week is 1, the second 2 etc ...
8640 * @param int $startdate Timestamp for the start date
8641 * @param int $thedate Timestamp for the end date
8644 function getweek ($startdate, $thedate) {
8645 if ($thedate < $startdate) {
8649 return floor(($thedate - $startdate) / WEEKSECS
) +
1;
8653 * Returns a randomly generated password of length $maxlen. inspired by
8655 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8656 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8658 * @param int $maxlen The maximum size of the password being generated.
8661 function generate_password($maxlen=10) {
8664 if (empty($CFG->passwordpolicy
)) {
8665 $fillers = PASSWORD_DIGITS
;
8666 $wordlist = file($CFG->wordlist
);
8667 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8668 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8669 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8670 $password = $word1 . $filler1 . $word2;
8672 $minlen = !empty($CFG->minpasswordlength
) ?
$CFG->minpasswordlength
: 0;
8673 $digits = $CFG->minpassworddigits
;
8674 $lower = $CFG->minpasswordlower
;
8675 $upper = $CFG->minpasswordupper
;
8676 $nonalphanum = $CFG->minpasswordnonalphanum
;
8677 $total = $lower +
$upper +
$digits +
$nonalphanum;
8678 // Var minlength should be the greater one of the two ( $minlen and $total ).
8679 $minlen = $minlen < $total ?
$total : $minlen;
8680 // Var maxlen can never be smaller than minlen.
8681 $maxlen = $minlen > $maxlen ?
$minlen : $maxlen;
8682 $additional = $maxlen - $total;
8684 // Make sure we have enough characters to fulfill
8685 // complexity requirements.
8686 $passworddigits = PASSWORD_DIGITS
;
8687 while ($digits > strlen($passworddigits)) {
8688 $passworddigits .= PASSWORD_DIGITS
;
8690 $passwordlower = PASSWORD_LOWER
;
8691 while ($lower > strlen($passwordlower)) {
8692 $passwordlower .= PASSWORD_LOWER
;
8694 $passwordupper = PASSWORD_UPPER
;
8695 while ($upper > strlen($passwordupper)) {
8696 $passwordupper .= PASSWORD_UPPER
;
8698 $passwordnonalphanum = PASSWORD_NONALPHANUM
;
8699 while ($nonalphanum > strlen($passwordnonalphanum)) {
8700 $passwordnonalphanum .= PASSWORD_NONALPHANUM
;
8703 // Now mix and shuffle it all.
8704 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8705 substr(str_shuffle ($passwordupper), 0, $upper) .
8706 substr(str_shuffle ($passworddigits), 0, $digits) .
8707 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8708 substr(str_shuffle ($passwordlower .
8711 $passwordnonalphanum), 0 , $additional));
8714 return substr ($password, 0, $maxlen);
8718 * Given a float, prints it nicely.
8719 * Localized floats must not be used in calculations!
8721 * The stripzeros feature is intended for making numbers look nicer in small
8722 * areas where it is not necessary to indicate the degree of accuracy by showing
8723 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8724 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8726 * @param float $float The float to print
8727 * @param int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision).
8728 * @param bool $localized use localized decimal separator
8729 * @param bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after
8730 * the decimal point are always striped if $decimalpoints is -1.
8731 * @return string locale float
8733 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8734 if (is_null($float)) {
8738 $separator = get_string('decsep', 'langconfig');
8742 if ($decimalpoints == -1) {
8743 // The following counts the number of decimals.
8744 // It is safe as both floatval() and round() functions have same behaviour when non-numeric values are provided.
8745 $floatval = floatval($float);
8746 for ($decimalpoints = 0; $floatval != round($float, $decimalpoints); $decimalpoints++
);
8749 $result = number_format($float, $decimalpoints, $separator, '');
8751 // Remove zeros and final dot if not needed.
8752 $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
8758 * Converts locale specific floating point/comma number back to standard PHP float value
8759 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8761 * @param string $localefloat locale aware float representation
8762 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8763 * @return mixed float|bool - false or the parsed float.
8765 function unformat_float($localefloat, $strict = false) {
8766 $localefloat = trim($localefloat);
8768 if ($localefloat == '') {
8772 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8773 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8775 if ($strict && !is_numeric($localefloat)) {
8779 return (float)$localefloat;
8783 * Given a simple array, this shuffles it up just like shuffle()
8784 * Unlike PHP's shuffle() this function works on any machine.
8786 * @param array $array The array to be rearranged
8789 function swapshuffle($array) {
8791 $last = count($array) - 1;
8792 for ($i = 0; $i <= $last; $i++
) {
8793 $from = rand(0, $last);
8795 $array[$i] = $array[$from];
8796 $array[$from] = $curr;
8802 * Like {@link swapshuffle()}, but works on associative arrays
8804 * @param array $array The associative array to be rearranged
8807 function swapshuffle_assoc($array) {
8809 $newarray = array();
8810 $newkeys = swapshuffle(array_keys($array));
8812 foreach ($newkeys as $newkey) {
8813 $newarray[$newkey] = $array[$newkey];
8819 * Given an arbitrary array, and a number of draws,
8820 * this function returns an array with that amount
8821 * of items. The indexes are retained.
8823 * @todo Finish documenting this function
8825 * @param array $array
8829 function draw_rand_array($array, $draws) {
8833 $last = count($array);
8835 if ($draws > $last) {
8839 while ($draws > 0) {
8842 $keys = array_keys($array);
8843 $rand = rand(0, $last);
8845 $return[$keys[$rand]] = $array[$keys[$rand]];
8846 unset($array[$keys[$rand]]);
8855 * Calculate the difference between two microtimes
8857 * @param string $a The first Microtime
8858 * @param string $b The second Microtime
8861 function microtime_diff($a, $b) {
8862 list($adec, $asec) = explode(' ', $a);
8863 list($bdec, $bsec) = explode(' ', $b);
8864 return $bsec - $asec +
$bdec - $adec;
8868 * Given a list (eg a,b,c,d,e) this function returns
8869 * an array of 1->a, 2->b, 3->c etc
8871 * @param string $list The string to explode into array bits
8872 * @param string $separator The separator used within the list string
8873 * @return array The now assembled array
8875 function make_menu_from_list($list, $separator=',') {
8877 $array = array_reverse(explode($separator, $list), true);
8878 foreach ($array as $key => $item) {
8879 $outarray[$key+
1] = trim($item);
8885 * Creates an array that represents all the current grades that
8886 * can be chosen using the given grading type.
8889 * are scales, zero is no grade, and positive numbers are maximum
8892 * @todo Finish documenting this function or better deprecated this completely!
8894 * @param int $gradingtype
8897 function make_grades_menu($gradingtype) {
8901 if ($gradingtype < 0) {
8902 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8903 return make_menu_from_list($scale->scale
);
8905 } else if ($gradingtype > 0) {
8906 for ($i=$gradingtype; $i>=0; $i--) {
8907 $grades[$i] = $i .' / '. $gradingtype;
8915 * make_unique_id_code
8917 * @todo Finish documenting this function
8920 * @param string $extra Extra string to append to the end of the code
8923 function make_unique_id_code($extra = '') {
8925 $hostname = 'unknownhost';
8926 if (!empty($_SERVER['HTTP_HOST'])) {
8927 $hostname = $_SERVER['HTTP_HOST'];
8928 } else if (!empty($_ENV['HTTP_HOST'])) {
8929 $hostname = $_ENV['HTTP_HOST'];
8930 } else if (!empty($_SERVER['SERVER_NAME'])) {
8931 $hostname = $_SERVER['SERVER_NAME'];
8932 } else if (!empty($_ENV['SERVER_NAME'])) {
8933 $hostname = $_ENV['SERVER_NAME'];
8936 $date = gmdate("ymdHis");
8938 $random = random_string(6);
8941 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8943 return $hostname .'+'. $date .'+'. $random;
8949 * Function to check the passed address is within the passed subnet
8951 * The parameter is a comma separated string of subnet definitions.
8952 * Subnet strings can be in one of three formats:
8953 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8954 * 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)
8955 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8956 * Code for type 1 modified from user posted comments by mediator at
8957 * {@link http://au.php.net/manual/en/function.ip2long.php}
8959 * @param string $addr The address you are checking
8960 * @param string $subnetstr The string of subnet addresses
8963 function address_in_subnet($addr, $subnetstr) {
8965 if ($addr == '0.0.0.0') {
8968 $subnets = explode(',', $subnetstr);
8970 $addr = trim($addr);
8971 $addr = cleanremoteaddr($addr, false); // Normalise.
8972 if ($addr === null) {
8975 $addrparts = explode(':', $addr);
8977 $ipv6 = strpos($addr, ':');
8979 foreach ($subnets as $subnet) {
8980 $subnet = trim($subnet);
8981 if ($subnet === '') {
8985 if (strpos($subnet, '/') !== false) {
8986 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8987 list($ip, $mask) = explode('/', $subnet);
8988 $mask = trim($mask);
8989 if (!is_number($mask)) {
8990 continue; // Incorect mask number, eh?
8992 $ip = cleanremoteaddr($ip, false); // Normalise.
8996 if (strpos($ip, ':') !== false) {
9001 if ($mask > 128 or $mask < 0) {
9002 continue; // Nonsense.
9005 return true; // Any address.
9008 if ($ip === $addr) {
9013 $ipparts = explode(':', $ip);
9014 $modulo = $mask %
16;
9015 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
9016 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
9017 if (implode(':', $ipnet) === implode(':', $addrnet)) {
9021 $pos = ($mask-$modulo)/16;
9022 $ipnet = hexdec($ipparts[$pos]);
9023 $addrnet = hexdec($addrparts[$pos]);
9024 $mask = 0xffff << (16 - $modulo);
9025 if (($addrnet & $mask) == ($ipnet & $mask)) {
9035 if ($mask > 32 or $mask < 0) {
9036 continue; // Nonsense.
9042 if ($ip === $addr) {
9047 $mask = 0xffffffff << (32 - $mask);
9048 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
9053 } else if (strpos($subnet, '-') !== false) {
9054 // 2: xxx.xxx.xxx.xxx-yyy or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy. A range of IP addresses in the last group.
9055 $parts = explode('-', $subnet);
9056 if (count($parts) != 2) {
9060 if (strpos($subnet, ':') !== false) {
9065 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9066 if ($ipstart === null) {
9069 $ipparts = explode(':', $ipstart);
9070 $start = hexdec(array_pop($ipparts));
9071 $ipparts[] = trim($parts[1]);
9072 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
9073 if ($ipend === null) {
9077 $ipnet = implode(':', $ipparts);
9078 if (strpos($addr, $ipnet) !== 0) {
9081 $ipparts = explode(':', $ipend);
9082 $end = hexdec($ipparts[7]);
9084 $addrend = hexdec($addrparts[7]);
9086 if (($addrend >= $start) and ($addrend <= $end)) {
9095 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9096 if ($ipstart === null) {
9099 $ipparts = explode('.', $ipstart);
9100 $ipparts[3] = trim($parts[1]);
9101 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
9102 if ($ipend === null) {
9106 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9112 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9113 if (strpos($subnet, ':') !== false) {
9118 $parts = explode(':', $subnet);
9119 $count = count($parts);
9120 if ($parts[$count-1] === '') {
9121 unset($parts[$count-1]); // Trim trailing :'s.
9123 $subnet = implode('.', $parts);
9125 $isip = cleanremoteaddr($subnet, false); // Normalise.
9126 if ($isip !== null) {
9127 if ($isip === $addr) {
9131 } else if ($count > 8) {
9134 $zeros = array_fill(0, 8-$count, '0');
9135 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9136 if (address_in_subnet($addr, $subnet)) {
9145 $parts = explode('.', $subnet);
9146 $count = count($parts);
9147 if ($parts[$count-1] === '') {
9148 unset($parts[$count-1]); // Trim trailing .
9150 $subnet = implode('.', $parts);
9153 $subnet = cleanremoteaddr($subnet, false); // Normalise.
9154 if ($subnet === $addr) {
9158 } else if ($count > 4) {
9161 $zeros = array_fill(0, 4-$count, '0');
9162 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9163 if (address_in_subnet($addr, $subnet)) {
9174 * For outputting debugging info
9176 * @param string $string The string to write
9177 * @param string $eol The end of line char(s) to use
9178 * @param string $sleep Period to make the application sleep
9179 * This ensures any messages have time to display before redirect
9181 function mtrace($string, $eol="\n", $sleep=0) {
9184 if (isset($CFG->mtrace_wrapper
) && function_exists($CFG->mtrace_wrapper
)) {
9185 $fn = $CFG->mtrace_wrapper
;
9188 } else if (defined('STDOUT') && !PHPUNIT_TEST
&& !defined('BEHAT_TEST')) {
9189 // We must explicitly call the add_line function here.
9190 // Uses of fwrite to STDOUT are not picked up by ob_start.
9191 if ($output = \core\task\logmanager
::add_line("{$string}{$eol}")) {
9192 fwrite(STDOUT
, $output);
9195 echo $string . $eol;
9201 // Delay to keep message on user's screen in case of subsequent redirect.
9208 * Replace 1 or more slashes or backslashes to 1 slash
9210 * @param string $path The path to strip
9211 * @return string the path with double slashes removed
9213 function cleardoubleslashes ($path) {
9214 return preg_replace('/(\/|\\\){1,}/', '/', $path);
9218 * Is the current ip in a given list?
9220 * @param string $list
9223 function remoteip_in_list($list) {
9224 $clientip = getremoteaddr(null);
9227 // Ensure access on cli.
9230 return \core\ip_utils
::is_ip_in_subnet_list($clientip, $list);
9234 * Returns most reliable client address
9236 * @param string $default If an address can't be determined, then return this
9237 * @return string The remote IP address
9239 function getremoteaddr($default='0.0.0.0') {
9242 if (!isset($CFG->getremoteaddrconf
)) {
9243 // This will happen, for example, before just after the upgrade, as the
9244 // user is redirected to the admin screen.
9245 $variablestoskip = GETREMOTEADDR_SKIP_DEFAULT
;
9247 $variablestoskip = $CFG->getremoteaddrconf
;
9249 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP
)) {
9250 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9251 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9252 return $address ?
$address : $default;
9255 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR
)) {
9256 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9257 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9259 $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
9261 return !\core\ip_utils
::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore ??
'', ',');
9264 // Multiple proxies can append values to this header including an
9265 // untrusted original request header so we must only trust the last ip.
9266 $address = end($forwardedaddresses);
9268 if (substr_count($address, ":") > 1) {
9269 // Remove port and brackets from IPv6.
9270 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9271 $address = $matches[1];
9274 // Remove port from IPv4.
9275 if (substr_count($address, ":") == 1) {
9276 $parts = explode(":", $address);
9277 $address = $parts[0];
9281 $address = cleanremoteaddr($address);
9282 return $address ?
$address : $default;
9285 if (!empty($_SERVER['REMOTE_ADDR'])) {
9286 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9287 return $address ?
$address : $default;
9294 * Cleans an ip address. Internal addresses are now allowed.
9295 * (Originally local addresses were not allowed.)
9297 * @param string $addr IPv4 or IPv6 address
9298 * @param bool $compress use IPv6 address compression
9299 * @return string normalised ip address string, null if error
9301 function cleanremoteaddr($addr, $compress=false) {
9302 $addr = trim($addr);
9304 if (strpos($addr, ':') !== false) {
9305 // Can be only IPv6.
9306 $parts = explode(':', $addr);
9307 $count = count($parts);
9309 if (strpos($parts[$count-1], '.') !== false) {
9310 // Legacy ipv4 notation.
9311 $last = array_pop($parts);
9312 $ipv4 = cleanremoteaddr($last, true);
9313 if ($ipv4 === null) {
9316 $bits = explode('.', $ipv4);
9317 $parts[] = dechex($bits[0]).dechex($bits[1]);
9318 $parts[] = dechex($bits[2]).dechex($bits[3]);
9319 $count = count($parts);
9320 $addr = implode(':', $parts);
9323 if ($count < 3 or $count > 8) {
9324 return null; // Severly malformed.
9328 if (strpos($addr, '::') === false) {
9329 return null; // Malformed.
9332 $insertat = array_search('', $parts, true);
9333 $missing = array_fill(0, 1 +
8 - $count, '0');
9334 array_splice($parts, $insertat, 1, $missing);
9335 foreach ($parts as $key => $part) {
9342 $adr = implode(':', $parts);
9343 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9344 return null; // Incorrect format - sorry.
9347 // Normalise 0s and case.
9348 $parts = array_map('hexdec', $parts);
9349 $parts = array_map('dechex', $parts);
9351 $result = implode(':', $parts);
9357 if ($result === '0:0:0:0:0:0:0:0') {
9358 return '::'; // All addresses.
9361 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9362 if ($compressed !== $result) {
9366 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9367 if ($compressed !== $result) {
9371 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9372 if ($compressed !== $result) {
9379 // First get all things that look like IPv4 addresses.
9381 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9386 foreach ($parts as $key => $match) {
9390 $parts[$key] = (int)$match; // Normalise 0s.
9393 return implode('.', $parts);
9398 * Is IP address a public address?
9400 * @param string $ip The ip to check
9401 * @return bool true if the ip is public
9403 function ip_is_public($ip) {
9404 return (bool) filter_var($ip, FILTER_VALIDATE_IP
, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
));
9408 * This function will make a complete copy of anything it's given,
9409 * regardless of whether it's an object or not.
9411 * @param mixed $thing Something you want cloned
9412 * @return mixed What ever it is you passed it
9414 function fullclone($thing) {
9415 return unserialize(serialize($thing));
9419 * Used to make sure that $min <= $value <= $max
9421 * Make sure that value is between min, and max
9423 * @param int $min The minimum value
9424 * @param int $value The value to check
9425 * @param int $max The maximum value
9428 function bounded_number($min, $value, $max) {
9429 if ($value < $min) {
9432 if ($value > $max) {
9439 * Check if there is a nested array within the passed array
9441 * @param array $array
9442 * @return bool true if there is a nested array false otherwise
9444 function array_is_nested($array) {
9445 foreach ($array as $value) {
9446 if (is_array($value)) {
9454 * get_performance_info() pairs up with init_performance_info()
9455 * loaded in setup.php. Returns an array with 'html' and 'txt'
9456 * values ready for use, and each of the individual stats provided
9457 * separately as well.
9461 function get_performance_info() {
9462 global $CFG, $PERF, $DB, $PAGE;
9465 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9468 if (!empty($CFG->themedesignermode
)) {
9469 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9470 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9472 $info['html'] .= '<ul class="list-unstyled row mx-md-0">'; // Holds userfriendly HTML representation.
9474 $info['realtime'] = microtime_diff($PERF->starttime
, microtime());
9476 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9477 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9479 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9480 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ??
"NULL") . ' ';
9482 if (function_exists('memory_get_usage')) {
9483 $info['memory_total'] = memory_get_usage();
9484 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory
;
9485 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9486 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9487 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9490 if (function_exists('memory_get_peak_usage')) {
9491 $info['memory_peak'] = memory_get_peak_usage();
9492 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9493 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9496 $info['html'] .= '</ul><ul class="list-unstyled row mx-md-0">';
9497 $inc = get_included_files();
9498 $info['includecount'] = count($inc);
9499 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9500 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9502 if (!empty($CFG->early_install_lang
) or empty($PAGE)) {
9503 // We can not track more performance before installation or before PAGE init, sorry.
9507 $filtermanager = filter_manager
::instance();
9508 if (method_exists($filtermanager, 'get_performance_summary')) {
9509 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9510 $info = array_merge($filterinfo, $info);
9511 foreach ($filterinfo as $key => $value) {
9512 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9513 $info['txt'] .= "$key: $value ";
9517 $stringmanager = get_string_manager();
9518 if (method_exists($stringmanager, 'get_performance_summary')) {
9519 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9520 $info = array_merge($filterinfo, $info);
9521 foreach ($filterinfo as $key => $value) {
9522 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9523 $info['txt'] .= "$key: $value ";
9527 if (!empty($PERF->logwrites
)) {
9528 $info['logwrites'] = $PERF->logwrites
;
9529 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9530 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9533 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites
);
9534 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9535 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9537 if ($DB->want_read_slave()) {
9538 $info['dbreads_slave'] = $DB->perf_get_reads_slave();
9539 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads from slave: '.$info['dbreads_slave'].'</li> ';
9540 $info['txt'] .= 'db reads from slave: '.$info['dbreads_slave'].' ';
9543 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9544 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9545 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9547 if (function_exists('posix_times')) {
9548 $ptimes = posix_times();
9549 if (is_array($ptimes)) {
9550 foreach ($ptimes as $key => $val) {
9551 $info[$key] = $ptimes[$key] - $PERF->startposixtimes
[$key];
9553 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9554 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9555 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9559 // Grab the load average for the last minute.
9560 // /proc will only work under some linux configurations
9561 // while uptime is there under MacOSX/Darwin and other unices.
9562 if (is_readable('/proc/loadavg') && $loadavg = @file
('/proc/loadavg')) {
9563 list($serverload) = explode(' ', $loadavg[0]);
9565 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `
/usr
/bin
/uptime`
) {
9566 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9567 $serverload = $matches[1];
9569 trigger_error('Could not parse uptime output!');
9572 if (!empty($serverload)) {
9573 $info['serverload'] = $serverload;
9574 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9575 $info['txt'] .= "serverload: {$info['serverload']} ";
9578 // Display size of session if session started.
9579 if ($si = \core\session\manager
::get_performance_info()) {
9580 $info['sessionsize'] = $si['size'];
9581 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9582 $info['txt'] .= $si['txt'];
9585 $info['html'] .= '</ul>';
9587 if ($stats = cache_helper
::get_stats()) {
9589 $table = new html_table();
9590 $table->attributes
['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9591 $table->head
= ['Mode', 'Cache item', 'Static', 'H', 'M', get_string('mappingprimary', 'cache'), 'H', 'M', 'S', 'I/O'];
9593 $table->align
= ['left', 'left', 'left', 'right', 'right', 'left', 'right', 'right', 'right', 'right'];
9595 $text = 'Caches used (hits/misses/sets): ';
9601 // We want to align static caches into their own column.
9603 foreach ($stats as $definition => $details) {
9604 $numstores = count($details['stores']);
9605 $first = key($details['stores']);
9606 if ($first !== cache_store
::STATIC_ACCEL
) {
9607 $numstores++
; // Add a blank space for the missing static store.
9609 $maxstores = max($maxstores, $numstores);
9614 while ($storec++
< ($maxstores - 2)) {
9615 if ($storec == ($maxstores - 2)) {
9616 $table->head
[] = get_string('mappingfinal', 'cache');
9618 $table->head
[] = "Store $storec";
9620 $table->align
[] = 'left';
9621 $table->align
[] = 'right';
9622 $table->align
[] = 'right';
9623 $table->align
[] = 'right';
9624 $table->align
[] = 'right';
9625 $table->head
[] = 'H';
9626 $table->head
[] = 'M';
9627 $table->head
[] = 'S';
9628 $table->head
[] = 'I/O';
9633 foreach ($stats as $definition => $details) {
9634 switch ($details['mode']) {
9635 case cache_store
::MODE_APPLICATION
:
9636 $modeclass = 'application';
9637 $mode = ' <span title="application cache">App</span>';
9639 case cache_store
::MODE_SESSION
:
9640 $modeclass = 'session';
9641 $mode = ' <span title="session cache">Ses</span>';
9643 case cache_store
::MODE_REQUEST
:
9644 $modeclass = 'request';
9645 $mode = ' <span title="request cache">Req</span>';
9648 $row = [$mode, $definition];
9650 $text .= "$definition {";
9653 foreach ($details['stores'] as $store => $data) {
9655 if ($storec == 0 && $store !== cache_store
::STATIC_ACCEL
) {
9662 $hits +
= $data['hits'];
9663 $misses +
= $data['misses'];
9664 $sets +
= $data['sets'];
9665 if ($data['hits'] == 0 and $data['misses'] > 0) {
9666 $cachestoreclass = 'nohits bg-danger';
9667 } else if ($data['hits'] < $data['misses']) {
9668 $cachestoreclass = 'lowhits bg-warning text-dark';
9670 $cachestoreclass = 'hihits';
9672 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9673 $cell = new html_table_cell($store);
9674 $cell->attributes
= ['class' => $cachestoreclass];
9676 $cell = new html_table_cell($data['hits']);
9677 $cell->attributes
= ['class' => $cachestoreclass];
9679 $cell = new html_table_cell($data['misses']);
9680 $cell->attributes
= ['class' => $cachestoreclass];
9683 if ($store !== cache_store
::STATIC_ACCEL
) {
9684 // The static cache is never set.
9685 $cell = new html_table_cell($data['sets']);
9686 $cell->attributes
= ['class' => $cachestoreclass];
9689 if ($data['hits'] ||
$data['sets']) {
9690 if ($data['iobytes'] === cache_store
::IO_BYTES_NOT_SUPPORTED
) {
9693 $size = display_size($data['iobytes'], 1, 'KB');
9694 if ($data['iobytes'] >= 10 * 1024) {
9695 $cachestoreclass = ' bg-warning text-dark';
9701 $cell = new html_table_cell($size);
9702 $cell->attributes
= ['class' => $cachestoreclass];
9707 while ($storec++
< $maxstores) {
9716 $table->data
[] = $row;
9719 $html .= html_writer
::table($table);
9721 // Now lets also show sub totals for each cache store.
9723 $storetotal = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9724 foreach ($stats as $definition => $details) {
9725 foreach ($details['stores'] as $store => $data) {
9726 if (!array_key_exists($store, $storetotals)) {
9727 $storetotals[$store] = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9729 $storetotals[$store]['class'] = $data['class'];
9730 $storetotals[$store]['hits'] +
= $data['hits'];
9731 $storetotals[$store]['misses'] +
= $data['misses'];
9732 $storetotals[$store]['sets'] +
= $data['sets'];
9733 $storetotal['hits'] +
= $data['hits'];
9734 $storetotal['misses'] +
= $data['misses'];
9735 $storetotal['sets'] +
= $data['sets'];
9736 if ($data['iobytes'] !== cache_store
::IO_BYTES_NOT_SUPPORTED
) {
9737 $storetotals[$store]['iobytes'] +
= $data['iobytes'];
9738 $storetotal['iobytes'] +
= $data['iobytes'];
9743 $table = new html_table();
9744 $table->attributes
['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9745 $table->head
= [get_string('storename', 'cache'), get_string('type_cachestore', 'plugin'), 'H', 'M', 'S', 'I/O'];
9747 $table->align
= ['left', 'left', 'right', 'right', 'right', 'right'];
9749 ksort($storetotals);
9751 foreach ($storetotals as $store => $data) {
9753 if ($data['hits'] == 0 and $data['misses'] > 0) {
9754 $cachestoreclass = 'nohits bg-danger';
9755 } else if ($data['hits'] < $data['misses']) {
9756 $cachestoreclass = 'lowhits bg-warning text-dark';
9758 $cachestoreclass = 'hihits';
9760 $cell = new html_table_cell($store);
9761 $cell->attributes
= ['class' => $cachestoreclass];
9763 $cell = new html_table_cell($data['class']);
9764 $cell->attributes
= ['class' => $cachestoreclass];
9766 $cell = new html_table_cell($data['hits']);
9767 $cell->attributes
= ['class' => $cachestoreclass];
9769 $cell = new html_table_cell($data['misses']);
9770 $cell->attributes
= ['class' => $cachestoreclass];
9772 $cell = new html_table_cell($data['sets']);
9773 $cell->attributes
= ['class' => $cachestoreclass];
9775 if ($data['hits'] ||
$data['sets']) {
9776 if ($data['iobytes']) {
9777 $size = display_size($data['iobytes'], 1, 'KB');
9784 $cell = new html_table_cell($size);
9785 $cell->attributes
= ['class' => $cachestoreclass];
9787 $table->data
[] = $row;
9789 if (!empty($storetotal['iobytes'])) {
9790 $size = display_size($storetotal['iobytes'], 1, 'KB');
9791 } else if (!empty($storetotal['hits']) ||
!empty($storetotal['sets'])) {
9797 get_string('total'),
9799 $storetotal['hits'],
9800 $storetotal['misses'],
9801 $storetotal['sets'],
9804 $table->data
[] = $row;
9806 $html .= html_writer
::table($table);
9808 $info['cachesused'] = "$hits / $misses / $sets";
9809 $info['html'] .= $html;
9810 $info['txt'] .= $text.'. ';
9812 $info['cachesused'] = '0 / 0 / 0';
9813 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9814 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9817 $info['html'] = '<div class="performanceinfo siteinfo container-fluid px-md-0 overflow-auto mt-3">'.$info['html'].'</div>';
9822 * Renames a file or directory to a unique name within the same directory.
9824 * This function is designed to avoid any potential race conditions, and select an unused name.
9826 * @param string $filepath Original filepath
9827 * @param string $prefix Prefix to use for the temporary name
9828 * @return string|bool New file path or false if failed
9829 * @since Moodle 3.10
9831 function rename_to_unused_name(string $filepath, string $prefix = '_temp_') {
9832 $dir = dirname($filepath);
9833 $basename = $dir . '/' . $prefix;
9835 while ($limit < 100) {
9836 // Select a new name based on a random number.
9837 $newfilepath = $basename . md5(mt_rand());
9839 // Attempt a rename to that new name.
9840 if (@rename
($filepath, $newfilepath)) {
9841 return $newfilepath;
9844 // The first time, do some sanity checks, maybe it is failing for a good reason and there
9845 // is no point trying 100 times if so.
9846 if ($limit === 0 && (!file_exists($filepath) ||
!is_writable($dir))) {
9855 * Delete directory or only its content
9857 * @param string $dir directory path
9858 * @param bool $contentonly
9859 * @return bool success, true also if dir does not exist
9861 function remove_dir($dir, $contentonly=false) {
9862 if (!is_dir($dir)) {
9867 if (!$contentonly) {
9868 // Start by renaming the directory; this will guarantee that other processes don't write to it
9869 // while it is in the process of being deleted.
9870 $tempdir = rename_to_unused_name($dir);
9872 // If the rename was successful then delete the $tempdir instead.
9875 // If the rename fails, we will continue through and attempt to delete the directory
9876 // without renaming it since that is likely to at least delete most of the files.
9879 if (!$handle = opendir($dir)) {
9883 while (false!==($item = readdir($handle))) {
9884 if ($item != '.' && $item != '..') {
9885 if (is_dir($dir.'/'.$item)) {
9886 $result = remove_dir($dir.'/'.$item) && $result;
9888 $result = unlink($dir.'/'.$item) && $result;
9894 clearstatcache(); // Make sure file stat cache is properly invalidated.
9897 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9898 clearstatcache(); // Make sure file stat cache is properly invalidated.
9903 * Detect if an object or a class contains a given property
9904 * will take an actual object or the name of a class
9906 * @param mix $obj Name of class or real object to test
9907 * @param string $property name of property to find
9908 * @return bool true if property exists
9910 function object_property_exists( $obj, $property ) {
9911 if (is_string( $obj )) {
9912 $properties = get_class_vars( $obj );
9914 $properties = get_object_vars( $obj );
9916 return array_key_exists( $property, $properties );
9920 * Converts an object into an associative array
9922 * This function converts an object into an associative array by iterating
9923 * over its public properties. Because this function uses the foreach
9924 * construct, Iterators are respected. It works recursively on arrays of objects.
9925 * Arrays and simple values are returned as is.
9927 * If class has magic properties, it can implement IteratorAggregate
9928 * and return all available properties in getIterator()
9933 function convert_to_array($var) {
9936 // Loop over elements/properties.
9937 foreach ($var as $key => $value) {
9938 // Recursively convert objects.
9939 if (is_object($value) ||
is_array($value)) {
9940 $result[$key] = convert_to_array($value);
9942 // Simple values are untouched.
9943 $result[$key] = $value;
9950 * Detect a custom script replacement in the data directory that will
9951 * replace an existing moodle script
9953 * @return string|bool full path name if a custom script exists, false if no custom script exists
9955 function custom_script_path() {
9956 global $CFG, $SCRIPT;
9958 if ($SCRIPT === null) {
9959 // Probably some weird external script.
9963 $scriptpath = $CFG->customscripts
. $SCRIPT;
9965 // Check the custom script exists.
9966 if (file_exists($scriptpath) and is_file($scriptpath)) {
9974 * Returns whether or not the user object is a remote MNET user. This function
9975 * is in moodlelib because it does not rely on loading any of the MNET code.
9977 * @param object $user A valid user object
9978 * @return bool True if the user is from a remote Moodle.
9980 function is_mnet_remote_user($user) {
9983 if (!isset($CFG->mnet_localhost_id
)) {
9984 include_once($CFG->dirroot
. '/mnet/lib.php');
9985 $env = new mnet_environment();
9990 return (!empty($user->mnethostid
) && $user->mnethostid
!= $CFG->mnet_localhost_id
);
9994 * This function will search for browser prefereed languages, setting Moodle
9995 * to use the best one available if $SESSION->lang is undefined
9997 function setup_lang_from_browser() {
9998 global $CFG, $SESSION, $USER;
10000 if (!empty($SESSION->lang
) or !empty($USER->lang
) or empty($CFG->autolang
)) {
10001 // Lang is defined in session or user profile, nothing to do.
10005 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
10009 // Extract and clean langs from headers.
10010 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
10011 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
10012 $rawlangs = explode(',', $rawlangs); // Convert to array.
10016 foreach ($rawlangs as $lang) {
10017 if (strpos($lang, ';') === false) {
10018 $langs[(string)$order] = $lang;
10019 $order = $order-0.01;
10021 $parts = explode(';', $lang);
10022 $pos = strpos($parts[1], '=');
10023 $langs[substr($parts[1], $pos+
1)] = $parts[0];
10026 krsort($langs, SORT_NUMERIC
);
10028 // Look for such langs under standard locations.
10029 foreach ($langs as $lang) {
10030 // Clean it properly for include.
10031 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR
));
10032 if (get_string_manager()->translation_exists($lang, false)) {
10033 // Lang exists, set it in session.
10034 $SESSION->lang
= $lang;
10035 // We have finished. Go out.
10043 * Check if $url matches anything in proxybypass list
10045 * Any errors just result in the proxy being used (least bad)
10047 * @param string $url url to check
10048 * @return boolean true if we should bypass the proxy
10050 function is_proxybypass( $url ) {
10054 if (empty($CFG->proxyhost
) or empty($CFG->proxybypass
)) {
10058 // Get the host part out of the url.
10059 if (!$host = parse_url( $url, PHP_URL_HOST
)) {
10063 // Get the possible bypass hosts into an array.
10064 $matches = explode( ',', $CFG->proxybypass
);
10066 // Check for a match.
10067 // (IPs need to match the left hand side and hosts the right of the url,
10068 // but we can recklessly check both as there can't be a false +ve).
10069 foreach ($matches as $match) {
10070 $match = trim($match);
10072 // Try for IP match (Left side).
10073 $lhs = substr($host, 0, strlen($match));
10074 if (strcasecmp($match, $lhs)==0) {
10078 // Try for host match (Right side).
10079 $rhs = substr($host, -strlen($match));
10080 if (strcasecmp($match, $rhs)==0) {
10085 // Nothing matched.
10090 * Check if the passed navigation is of the new style
10092 * @param mixed $navigation
10093 * @return bool true for yes false for no
10095 function is_newnav($navigation) {
10096 if (is_array($navigation) && !empty($navigation['newnav'])) {
10104 * Checks whether the given variable name is defined as a variable within the given object.
10106 * This will NOT work with stdClass objects, which have no class variables.
10108 * @param string $var The variable name
10109 * @param object $object The object to check
10112 function in_object_vars($var, $object) {
10113 $classvars = get_class_vars(get_class($object));
10114 $classvars = array_keys($classvars);
10115 return in_array($var, $classvars);
10119 * Returns an array without repeated objects.
10120 * This function is similar to array_unique, but for arrays that have objects as values
10122 * @param array $array
10123 * @param bool $keepkeyassoc
10126 function object_array_unique($array, $keepkeyassoc = true) {
10127 $duplicatekeys = array();
10130 foreach ($array as $key => $val) {
10131 // Convert objects to arrays, in_array() does not support objects.
10132 if (is_object($val)) {
10133 $val = (array)$val;
10136 if (!in_array($val, $tmp)) {
10139 $duplicatekeys[] = $key;
10143 foreach ($duplicatekeys as $key) {
10144 unset($array[$key]);
10147 return $keepkeyassoc ?
$array : array_values($array);
10151 * Is a userid the primary administrator?
10153 * @param int $userid int id of user to check
10156 function is_primary_admin($userid) {
10157 $primaryadmin = get_admin();
10159 if ($userid == $primaryadmin->id
) {
10167 * Returns the site identifier
10169 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
10171 function get_site_identifier() {
10173 // Check to see if it is missing. If so, initialise it.
10174 if (empty($CFG->siteidentifier
)) {
10175 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
10178 return $CFG->siteidentifier
;
10182 * Check whether the given password has no more than the specified
10183 * number of consecutive identical characters.
10185 * @param string $password password to be checked against the password policy
10186 * @param integer $maxchars maximum number of consecutive identical characters
10189 function check_consecutive_identical_characters($password, $maxchars) {
10191 if ($maxchars < 1) {
10192 return true; // Zero 0 is to disable this check.
10194 if (strlen($password) <= $maxchars) {
10195 return true; // Too short to fail this test.
10198 $previouschar = '';
10199 $consecutivecount = 1;
10200 foreach (str_split($password) as $char) {
10201 if ($char != $previouschar) {
10202 $consecutivecount = 1;
10204 $consecutivecount++
;
10205 if ($consecutivecount > $maxchars) {
10206 return false; // Check failed already.
10210 $previouschar = $char;
10217 * Helper function to do partial function binding.
10218 * so we can use it for preg_replace_callback, for example
10219 * this works with php functions, user functions, static methods and class methods
10220 * it returns you a callback that you can pass on like so:
10222 * $callback = partial('somefunction', $arg1, $arg2);
10224 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
10226 * $obj = new someclass();
10227 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
10229 * and then the arguments that are passed through at calltime are appended to the argument list.
10231 * @param mixed $function a php callback
10232 * @param mixed $arg1,... $argv arguments to partially bind with
10233 * @return array Array callback
10235 function partial() {
10236 if (!class_exists('partial')) {
10238 * Used to manage function binding.
10239 * @copyright 2009 Penny Leach
10240 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10244 public $values = array();
10245 /** @var string The function to call as a callback. */
10249 * @param string $func
10250 * @param array $args
10252 public function __construct($func, $args) {
10253 $this->values
= $args;
10254 $this->func
= $func;
10257 * Calls the callback function.
10260 public function method() {
10261 $args = func_get_args();
10262 return call_user_func_array($this->func
, array_merge($this->values
, $args));
10266 $args = func_get_args();
10267 $func = array_shift($args);
10268 $p = new partial($func, $args);
10269 return array($p, 'method');
10273 * helper function to load up and initialise the mnet environment
10274 * this must be called before you use mnet functions.
10276 * @return mnet_environment the equivalent of old $MNET global
10278 function get_mnet_environment() {
10280 require_once($CFG->dirroot
. '/mnet/lib.php');
10281 static $instance = null;
10282 if (empty($instance)) {
10283 $instance = new mnet_environment();
10290 * during xmlrpc server code execution, any code wishing to access
10291 * information about the remote peer must use this to get it.
10293 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
10295 function get_mnet_remote_client() {
10296 if (!defined('MNET_SERVER')) {
10297 debugging(get_string('notinxmlrpcserver', 'mnet'));
10300 global $MNET_REMOTE_CLIENT;
10301 if (isset($MNET_REMOTE_CLIENT)) {
10302 return $MNET_REMOTE_CLIENT;
10308 * during the xmlrpc server code execution, this will be called
10309 * to setup the object returned by {@link get_mnet_remote_client}
10311 * @param mnet_remote_client $client the client to set up
10312 * @throws moodle_exception
10314 function set_mnet_remote_client($client) {
10315 if (!defined('MNET_SERVER')) {
10316 throw new moodle_exception('notinxmlrpcserver', 'mnet');
10318 global $MNET_REMOTE_CLIENT;
10319 $MNET_REMOTE_CLIENT = $client;
10323 * return the jump url for a given remote user
10324 * this is used for rewriting forum post links in emails, etc
10326 * @param stdclass $user the user to get the idp url for
10328 function mnet_get_idp_jump_url($user) {
10331 static $mnetjumps = array();
10332 if (!array_key_exists($user->mnethostid
, $mnetjumps)) {
10333 $idp = mnet_get_peer_host($user->mnethostid
);
10334 $idpjumppath = mnet_get_app_jumppath($idp->applicationid
);
10335 $mnetjumps[$user->mnethostid
] = $idp->wwwroot
. $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot
. '&wantsurl=';
10337 return $mnetjumps[$user->mnethostid
];
10341 * Gets the homepage to use for the current user
10343 * @return int One of HOMEPAGE_*
10345 function get_home_page() {
10348 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage
)) {
10349 if ($CFG->defaulthomepage
== HOMEPAGE_MY
) {
10350 return HOMEPAGE_MY
;
10352 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY
);
10355 return HOMEPAGE_SITE
;
10359 * Gets the name of a course to be displayed when showing a list of courses.
10360 * By default this is just $course->fullname but user can configure it. The
10361 * result of this function should be passed through print_string.
10362 * @param stdClass|core_course_list_element $course Moodle course object
10363 * @return string Display name of course (either fullname or short + fullname)
10365 function get_course_display_name_for_list($course) {
10367 if (!empty($CFG->courselistshortnames
)) {
10368 if (!($course instanceof stdClass
)) {
10369 $course = (object)convert_to_array($course);
10371 return get_string('courseextendednamedisplay', '', $course);
10373 return $course->fullname
;
10378 * Safe analogue of unserialize() that can only parse arrays
10380 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
10381 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
10382 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
10384 * @param string $expression
10385 * @return array|bool either parsed array or false if parsing was impossible.
10387 function unserialize_array($expression) {
10389 // Find nested arrays, parse them and store in $subs , substitute with special string.
10390 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
10391 $key = '--SUB' . count($subs) . '--';
10392 $subs[$key] = unserialize_array($matches[2]);
10393 if ($subs[$key] === false) {
10396 $expression = str_replace($matches[2], $key . ';', $expression);
10399 // Check the expression is an array.
10400 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
10403 // Get the size and elements of an array (key;value;key;value;....).
10404 $parts = explode(';', $matches1[2]);
10405 $size = intval($matches1[1]);
10406 if (count($parts) < $size * 2 +
1) {
10409 // Analyze each part and make sure it is an integer or string or a substitute.
10411 for ($i = 0; $i < $size * 2; $i++
) {
10412 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
10413 $parts[$i] = (int)$matches2[1];
10414 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
10415 $parts[$i] = $matches3[2];
10416 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
10417 $parts[$i] = $subs[$parts[$i]];
10422 // Combine keys and values.
10423 for ($i = 0; $i < $size * 2; $i +
= 2) {
10424 $value[$parts[$i]] = $parts[$i+
1];
10430 * Safe method for unserializing given input that is expected to contain only a serialized instance of an stdClass object
10432 * If any class type other than stdClass is included in the input string, it will not be instantiated and will be cast to an
10433 * stdClass object. The initial cast to array, then back to object is to ensure we are always returning the correct type,
10434 * otherwise we would return an instances of {@see __PHP_Incomplete_class} for malformed strings
10436 * @param string $input
10439 function unserialize_object(string $input): stdClass
{
10440 $instance = (array) unserialize($input, ['allowed_classes' => [stdClass
::class]]);
10441 return (object) $instance;
10445 * The lang_string class
10447 * This special class is used to create an object representation of a string request.
10448 * It is special because processing doesn't occur until the object is first used.
10449 * The class was created especially to aid performance in areas where strings were
10450 * required to be generated but were not necessarily used.
10451 * As an example the admin tree when generated uses over 1500 strings, of which
10452 * normally only 1/3 are ever actually printed at any time.
10453 * The performance advantage is achieved by not actually processing strings that
10454 * arn't being used, as such reducing the processing required for the page.
10456 * How to use the lang_string class?
10457 * There are two methods of using the lang_string class, first through the
10458 * forth argument of the get_string function, and secondly directly.
10459 * The following are examples of both.
10460 * 1. Through get_string calls e.g.
10461 * $string = get_string($identifier, $component, $a, true);
10462 * $string = get_string('yes', 'moodle', null, true);
10463 * 2. Direct instantiation
10464 * $string = new lang_string($identifier, $component, $a, $lang);
10465 * $string = new lang_string('yes');
10467 * How do I use a lang_string object?
10468 * The lang_string object makes use of a magic __toString method so that you
10469 * are able to use the object exactly as you would use a string in most cases.
10470 * This means you are able to collect it into a variable and then directly
10471 * echo it, or concatenate it into another string, or similar.
10472 * The other thing you can do is manually get the string by calling the
10473 * lang_strings out method e.g.
10474 * $string = new lang_string('yes');
10476 * Also worth noting is that the out method can take one argument, $lang which
10477 * allows the developer to change the language on the fly.
10479 * When should I use a lang_string object?
10480 * The lang_string object is designed to be used in any situation where a
10481 * string may not be needed, but needs to be generated.
10482 * The admin tree is a good example of where lang_string objects should be
10484 * A more practical example would be any class that requries strings that may
10485 * not be printed (after all classes get renderer by renderers and who knows
10486 * what they will do ;))
10488 * When should I not use a lang_string object?
10489 * Don't use lang_strings when you are going to use a string immediately.
10490 * There is no need as it will be processed immediately and there will be no
10491 * advantage, and in fact perhaps a negative hit as a class has to be
10492 * instantiated for a lang_string object, however get_string won't require
10496 * 1. You cannot use a lang_string object as an array offset. Doing so will
10497 * result in PHP throwing an error. (You can use it as an object property!)
10501 * @copyright 2011 Sam Hemelryk
10502 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10504 class lang_string
{
10506 /** @var string The strings identifier */
10507 protected $identifier;
10508 /** @var string The strings component. Default '' */
10509 protected $component = '';
10510 /** @var array|stdClass Any arguments required for the string. Default null */
10511 protected $a = null;
10512 /** @var string The language to use when processing the string. Default null */
10513 protected $lang = null;
10515 /** @var string The processed string (once processed) */
10516 protected $string = null;
10519 * A special boolean. If set to true then the object has been woken up and
10520 * cannot be regenerated. If this is set then $this->string MUST be used.
10523 protected $forcedstring = false;
10526 * Constructs a lang_string object
10528 * This function should do as little processing as possible to ensure the best
10529 * performance for strings that won't be used.
10531 * @param string $identifier The strings identifier
10532 * @param string $component The strings component
10533 * @param stdClass|array $a Any arguments the string requires
10534 * @param string $lang The language to use when processing the string.
10535 * @throws coding_exception
10537 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10538 if (empty($component)) {
10539 $component = 'moodle';
10542 $this->identifier
= $identifier;
10543 $this->component
= $component;
10544 $this->lang
= $lang;
10546 // We MUST duplicate $a to ensure that it if it changes by reference those
10547 // changes are not carried across.
10548 // To do this we always ensure $a or its properties/values are strings
10549 // and that any properties/values that arn't convertable are forgotten.
10551 if (is_scalar($a)) {
10553 } else if ($a instanceof lang_string
) {
10554 $this->a
= $a->out();
10555 } else if (is_object($a) or is_array($a)) {
10557 $this->a
= array();
10558 foreach ($a as $key => $value) {
10559 // Make sure conversion errors don't get displayed (results in '').
10560 if (is_array($value)) {
10561 $this->a
[$key] = '';
10562 } else if (is_object($value)) {
10563 if (method_exists($value, '__toString')) {
10564 $this->a
[$key] = $value->__toString();
10566 $this->a
[$key] = '';
10569 $this->a
[$key] = (string)$value;
10575 if (debugging(false, DEBUG_DEVELOPER
)) {
10576 if (clean_param($this->identifier
, PARAM_STRINGID
) == '') {
10577 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10579 if (!empty($this->component
) && clean_param($this->component
, PARAM_COMPONENT
) == '') {
10580 throw new coding_exception('Invalid string compontent. Please check your string definition');
10582 if (!get_string_manager()->string_exists($this->identifier
, $this->component
)) {
10583 debugging('String does not exist. Please check your string definition for '.$this->identifier
.'/'.$this->component
, DEBUG_DEVELOPER
);
10589 * Processes the string.
10591 * This function actually processes the string, stores it in the string property
10592 * and then returns it.
10593 * You will notice that this function is VERY similar to the get_string method.
10594 * That is because it is pretty much doing the same thing.
10595 * However as this function is an upgrade it isn't as tolerant to backwards
10599 * @throws coding_exception
10601 protected function get_string() {
10604 // Check if we need to process the string.
10605 if ($this->string === null) {
10606 // Check the quality of the identifier.
10607 if ($CFG->debugdeveloper
&& clean_param($this->identifier
, PARAM_STRINGID
) === '') {
10608 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
);
10611 // Process the string.
10612 $this->string = get_string_manager()->get_string($this->identifier
, $this->component
, $this->a
, $this->lang
);
10613 // Debugging feature lets you display string identifier and component.
10614 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
10615 $this->string .= ' {' . $this->identifier
. '/' . $this->component
. '}';
10618 // Return the string.
10619 return $this->string;
10623 * Returns the string
10625 * @param string $lang The langauge to use when processing the string
10628 public function out($lang = null) {
10629 if ($lang !== null && $lang != $this->lang
&& ($this->lang
== null && $lang != current_language())) {
10630 if ($this->forcedstring
) {
10631 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang
.' used)', DEBUG_DEVELOPER
);
10632 return $this->get_string();
10634 $translatedstring = new lang_string($this->identifier
, $this->component
, $this->a
, $lang);
10635 return $translatedstring->out();
10637 return $this->get_string();
10641 * Magic __toString method for printing a string
10645 public function __toString() {
10646 return $this->get_string();
10650 * Magic __set_state method used for var_export
10652 * @param array $array
10655 public static function __set_state(array $array): self
{
10656 $tmp = new lang_string($array['identifier'], $array['component'], $array['a'], $array['lang']);
10657 $tmp->string = $array['string'];
10658 $tmp->forcedstring
= $array['forcedstring'];
10663 * Prepares the lang_string for sleep and stores only the forcedstring and
10664 * string properties... the string cannot be regenerated so we need to ensure
10665 * it is generated for this.
10669 public function __sleep() {
10670 $this->get_string();
10671 $this->forcedstring
= true;
10672 return array('forcedstring', 'string', 'lang');
10676 * Returns the identifier.
10680 public function get_identifier() {
10681 return $this->identifier
;
10685 * Returns the component.
10689 public function get_component() {
10690 return $this->component
;
10695 * Get human readable name describing the given callable.
10697 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10698 * It does not check if the callable actually exists.
10700 * @param callable|string|array $callable
10701 * @return string|bool Human readable name of callable, or false if not a valid callable.
10703 function get_callable_name($callable) {
10705 if (!is_callable($callable, true, $name)) {
10714 * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10715 * Never put your faith on this function and rely on its accuracy as there might be false positives.
10716 * It just performs some simple checks, and mainly is used for places where we want to hide some options
10717 * such as site registration when $CFG->wwwroot is not publicly accessible.
10718 * Good thing is there is no false negative.
10719 * Note that it's possible to force the result of this check by specifying $CFG->site_is_public in config.php
10723 function site_is_public() {
10726 // Return early if site admin has forced this setting.
10727 if (isset($CFG->site_is_public
)) {
10728 return (bool)$CFG->site_is_public
;
10731 $host = parse_url($CFG->wwwroot
, PHP_URL_HOST
);
10733 if ($host === 'localhost' ||
preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10735 } else if (\core\ip_utils
::is_ip_address($host) && !ip_is_public($host)) {
10737 } else if (($address = \core\ip_utils
::get_ip_address($host)) && !ip_is_public($address)) {