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 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1461 * that we need only fetch it once per request.
1462 * @param string $plugin full component name
1463 * @param string $name default null
1464 * @return mixed hash-like object or single value, return false no config found
1465 * @throws dml_exception
1467 function get_config($plugin, $name = null) {
1470 static $siteidentifier = null;
1472 if ($plugin === 'moodle' ||
$plugin === 'core' ||
empty($plugin)) {
1473 $forced =& $CFG->config_php_settings
;
1477 if (array_key_exists($plugin, $CFG->forced_plugin_settings
)) {
1478 $forced =& $CFG->forced_plugin_settings
[$plugin];
1485 if ($siteidentifier === null) {
1487 // This may fail during installation.
1488 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1489 // install the database.
1490 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1491 } catch (dml_exception
$ex) {
1492 // Set siteidentifier to false. We don't want to trip this continually.
1493 $siteidentifier = false;
1498 if (!empty($name)) {
1499 if (array_key_exists($name, $forced)) {
1500 return (string)$forced[$name];
1501 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1502 return $siteidentifier;
1506 $cache = cache
::make('core', 'config');
1507 $result = $cache->get($plugin);
1508 if ($result === false) {
1509 // The user is after a recordset.
1511 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1513 // This part is not really used any more, but anyway...
1514 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1516 $cache->set($plugin, $result);
1519 if (!empty($name)) {
1520 if (array_key_exists($name, $result)) {
1521 return $result[$name];
1526 if ($plugin === 'core') {
1527 $result['siteidentifier'] = $siteidentifier;
1530 foreach ($forced as $key => $value) {
1531 if (is_null($value) or is_array($value) or is_object($value)) {
1532 // We do not want any extra mess here, just real settings that could be saved in db.
1533 unset($result[$key]);
1535 // Convert to string as if it went through the DB.
1536 $result[$key] = (string)$value;
1540 return (object)$result;
1544 * Removes a key from global configuration.
1546 * NOTE: this function is called from lib/db/upgrade.php
1548 * @param string $name the key to set
1549 * @param string $plugin (optional) the plugin scope
1550 * @return boolean whether the operation succeeded.
1552 function unset_config($name, $plugin=null) {
1555 if (empty($plugin)) {
1557 $DB->delete_records('config', array('name' => $name));
1558 cache_helper
::invalidate_by_definition('core', 'config', array(), 'core');
1560 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1561 cache_helper
::invalidate_by_definition('core', 'config', array(), $plugin);
1568 * Remove all the config variables for a given plugin.
1570 * NOTE: this function is called from lib/db/upgrade.php
1572 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1573 * @return boolean whether the operation succeeded.
1575 function unset_all_config_for_plugin($plugin) {
1577 // Delete from the obvious config_plugins first.
1578 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1579 // Next delete any suspect settings from config.
1580 $like = $DB->sql_like('name', '?', true, true, false, '|');
1581 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1582 $DB->delete_records_select('config', $like, $params);
1583 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1584 cache_helper
::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1590 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1592 * All users are verified if they still have the necessary capability.
1594 * @param string $value the value of the config setting.
1595 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1596 * @param bool $includeadmins include administrators.
1597 * @return array of user objects.
1599 function get_users_from_config($value, $capability, $includeadmins = true) {
1600 if (empty($value) or $value === '$@NONE@$') {
1604 // We have to make sure that users still have the necessary capability,
1605 // it should be faster to fetch them all first and then test if they are present
1606 // instead of validating them one-by-one.
1607 $users = get_users_by_capability(context_system
::instance(), $capability);
1608 if ($includeadmins) {
1609 $admins = get_admins();
1610 foreach ($admins as $admin) {
1611 $users[$admin->id
] = $admin;
1615 if ($value === '$@ALL@$') {
1619 $result = array(); // Result in correct order.
1620 $allowed = explode(',', $value);
1621 foreach ($allowed as $uid) {
1622 if (isset($users[$uid])) {
1623 $user = $users[$uid];
1624 $result[$user->id
] = $user;
1633 * Invalidates browser caches and cached data in temp.
1637 function purge_all_caches() {
1642 * Selectively invalidate different types of cache.
1644 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1645 * areas alone or in combination.
1647 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1648 * 'muc' Purge MUC caches?
1649 * 'theme' Purge theme cache?
1650 * 'lang' Purge language string cache?
1651 * 'js' Purge javascript cache?
1652 * 'filter' Purge text filter cache?
1653 * 'other' Purge all other caches?
1655 function purge_caches($options = []) {
1656 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1657 if (empty(array_filter($options))) {
1658 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1660 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1662 if ($options['muc']) {
1663 cache_helper
::purge_all();
1665 if ($options['theme']) {
1666 theme_reset_all_caches();
1668 if ($options['lang']) {
1669 get_string_manager()->reset_caches();
1671 if ($options['js']) {
1672 js_reset_all_caches();
1674 if ($options['template']) {
1675 template_reset_all_caches();
1677 if ($options['filter']) {
1678 reset_text_filters_cache();
1680 if ($options['other']) {
1681 purge_other_caches();
1686 * Purge all non-MUC caches not otherwise purged in purge_caches.
1688 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1689 * {@link phpunit_util::reset_dataroot()}
1691 function purge_other_caches() {
1693 core_text
::reset_caches();
1694 if (class_exists('core_plugin_manager')) {
1695 core_plugin_manager
::reset_caches();
1698 // Bump up cacherev field for all courses.
1700 increment_revision_number('course', 'cacherev', '');
1701 } catch (moodle_exception
$e) {
1702 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1705 $DB->reset_caches();
1707 // Purge all other caches: rss, simplepie, etc.
1709 remove_dir($CFG->cachedir
.'', true);
1711 // Make sure cache dir is writable, throws exception if not.
1712 make_cache_directory('');
1714 // This is the only place where we purge local caches, we are only adding files there.
1715 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1716 remove_dir($CFG->localcachedir
, true);
1717 set_config('localcachedirpurged', time());
1718 make_localcache_directory('', true);
1719 \core\task\manager
::clear_static_caches();
1723 * Get volatile flags
1725 * @param string $type
1726 * @param int $changedsince default null
1727 * @return array records array
1729 function get_cache_flags($type, $changedsince = null) {
1732 $params = array('type' => $type, 'expiry' => time());
1733 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1734 if ($changedsince !== null) {
1735 $params['changedsince'] = $changedsince;
1736 $sqlwhere .= " AND timemodified > :changedsince";
1739 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1740 foreach ($flags as $flag) {
1741 $cf[$flag->name
] = $flag->value
;
1748 * Get volatile flags
1750 * @param string $type
1751 * @param string $name
1752 * @param int $changedsince default null
1753 * @return string|false The cache flag value or false
1755 function get_cache_flag($type, $name, $changedsince=null) {
1758 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1760 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1761 if ($changedsince !== null) {
1762 $params['changedsince'] = $changedsince;
1763 $sqlwhere .= " AND timemodified > :changedsince";
1766 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1770 * Set a volatile flag
1772 * @param string $type the "type" namespace for the key
1773 * @param string $name the key to set
1774 * @param string $value the value to set (without magic quotes) - null will remove the flag
1775 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1776 * @return bool Always returns true
1778 function set_cache_flag($type, $name, $value, $expiry = null) {
1781 $timemodified = time();
1782 if ($expiry === null ||
$expiry < $timemodified) {
1783 $expiry = $timemodified +
24 * 60 * 60;
1785 $expiry = (int)$expiry;
1788 if ($value === null) {
1789 unset_cache_flag($type, $name);
1793 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE
)) {
1794 // This is a potential problem in DEBUG_DEVELOPER.
1795 if ($f->value
== $value and $f->expiry
== $expiry and $f->timemodified
== $timemodified) {
1796 return true; // No need to update.
1799 $f->expiry
= $expiry;
1800 $f->timemodified
= $timemodified;
1801 $DB->update_record('cache_flags', $f);
1803 $f = new stdClass();
1804 $f->flagtype
= $type;
1807 $f->expiry
= $expiry;
1808 $f->timemodified
= $timemodified;
1809 $DB->insert_record('cache_flags', $f);
1815 * Removes a single volatile flag
1817 * @param string $type the "type" namespace for the key
1818 * @param string $name the key to set
1821 function unset_cache_flag($type, $name) {
1823 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1828 * Garbage-collect volatile flags
1830 * @return bool Always returns true
1832 function gc_cache_flags() {
1834 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1838 // USER PREFERENCE API.
1841 * Refresh user preference cache. This is used most often for $USER
1842 * object that is stored in session, but it also helps with performance in cron script.
1844 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1847 * @category preference
1849 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1850 * @param int $cachelifetime Cache life time on the current page (in seconds)
1851 * @throws coding_exception
1854 function check_user_preferences_loaded(stdClass
$user, $cachelifetime = 120) {
1856 // Static cache, we need to check on each page load, not only every 2 minutes.
1857 static $loadedusers = array();
1859 if (!isset($user->id
)) {
1860 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1863 if (empty($user->id
) or isguestuser($user->id
)) {
1864 // No permanent storage for not-logged-in users and guest.
1865 if (!isset($user->preference
)) {
1866 $user->preference
= array();
1873 if (isset($loadedusers[$user->id
]) and isset($user->preference
) and isset($user->preference
['_lastloaded'])) {
1874 // Already loaded at least once on this page. Are we up to date?
1875 if ($user->preference
['_lastloaded'] +
$cachelifetime > $timenow) {
1876 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1879 } else if (!get_cache_flag('userpreferenceschanged', $user->id
, $user->preference
['_lastloaded'])) {
1880 // No change since the lastcheck on this page.
1881 $user->preference
['_lastloaded'] = $timenow;
1886 // OK, so we have to reload all preferences.
1887 $loadedusers[$user->id
] = true;
1888 $user->preference
= $DB->get_records_menu('user_preferences', array('userid' => $user->id
), '', 'name,value'); // All values.
1889 $user->preference
['_lastloaded'] = $timenow;
1893 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1895 * NOTE: internal function, do not call from other code.
1899 * @param integer $userid the user whose prefs were changed.
1901 function mark_user_preferences_changed($userid) {
1904 if (empty($userid) or isguestuser($userid)) {
1905 // No cache flags for guest and not-logged-in users.
1909 set_cache_flag('userpreferenceschanged', $userid, 1, time() +
$CFG->sessiontimeout
);
1913 * Sets a preference for the specified user.
1915 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1917 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1920 * @category preference
1922 * @param string $name The key to set as preference for the specified user
1923 * @param string $value The value to set for the $name key in the specified user's
1924 * record, null means delete current value.
1925 * @param stdClass|int|null $user A moodle user object or id, null means current user
1926 * @throws coding_exception
1927 * @return bool Always true or exception
1929 function set_user_preference($name, $value, $user = null) {
1932 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1933 throw new coding_exception('Invalid preference name in set_user_preference() call');
1936 if (is_null($value)) {
1937 // Null means delete current.
1938 return unset_user_preference($name, $user);
1939 } else if (is_object($value)) {
1940 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1941 } else if (is_array($value)) {
1942 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1944 // Value column maximum length is 1333 characters.
1945 $value = (string)$value;
1946 if (core_text
::strlen($value) > 1333) {
1947 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1950 if (is_null($user)) {
1952 } else if (isset($user->id
)) {
1953 // It is a valid object.
1954 } else if (is_numeric($user)) {
1955 $user = (object)array('id' => (int)$user);
1957 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1960 check_user_preferences_loaded($user);
1962 if (empty($user->id
) or isguestuser($user->id
)) {
1963 // No permanent storage for not-logged-in users and guest.
1964 $user->preference
[$name] = $value;
1968 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => $name))) {
1969 if ($preference->value
=== $value and isset($user->preference
[$name]) and $user->preference
[$name] === $value) {
1970 // Preference already set to this value.
1973 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id
));
1976 $preference = new stdClass();
1977 $preference->userid
= $user->id
;
1978 $preference->name
= $name;
1979 $preference->value
= $value;
1980 $DB->insert_record('user_preferences', $preference);
1983 // Update value in cache.
1984 $user->preference
[$name] = $value;
1985 // Update the $USER in case where we've not a direct reference to $USER.
1986 if ($user !== $USER && $user->id
== $USER->id
) {
1987 $USER->preference
[$name] = $value;
1990 // Set reload flag for other sessions.
1991 mark_user_preferences_changed($user->id
);
1997 * Sets a whole array of preferences for the current user
1999 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2002 * @category preference
2004 * @param array $prefarray An array of key/value pairs to be set
2005 * @param stdClass|int|null $user A moodle user object or id, null means current user
2006 * @return bool Always true or exception
2008 function set_user_preferences(array $prefarray, $user = null) {
2009 foreach ($prefarray as $name => $value) {
2010 set_user_preference($name, $value, $user);
2016 * Unsets a preference completely by deleting it from the database
2018 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2021 * @category preference
2023 * @param string $name The key to unset as preference for the specified user
2024 * @param stdClass|int|null $user A moodle user object or id, null means current user
2025 * @throws coding_exception
2026 * @return bool Always true or exception
2028 function unset_user_preference($name, $user = null) {
2031 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2032 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2035 if (is_null($user)) {
2037 } else if (isset($user->id
)) {
2038 // It is a valid object.
2039 } else if (is_numeric($user)) {
2040 $user = (object)array('id' => (int)$user);
2042 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2045 check_user_preferences_loaded($user);
2047 if (empty($user->id
) or isguestuser($user->id
)) {
2048 // No permanent storage for not-logged-in user and guest.
2049 unset($user->preference
[$name]);
2054 $DB->delete_records('user_preferences', array('userid' => $user->id
, 'name' => $name));
2056 // Delete the preference from cache.
2057 unset($user->preference
[$name]);
2058 // Update the $USER in case where we've not a direct reference to $USER.
2059 if ($user !== $USER && $user->id
== $USER->id
) {
2060 unset($USER->preference
[$name]);
2063 // Set reload flag for other sessions.
2064 mark_user_preferences_changed($user->id
);
2070 * Used to fetch user preference(s)
2072 * If no arguments are supplied this function will return
2073 * all of the current user preferences as an array.
2075 * If a name is specified then this function
2076 * attempts to return that particular preference value. If
2077 * none is found, then the optional value $default is returned,
2080 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2083 * @category preference
2085 * @param string $name Name of the key to use in finding a preference value
2086 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2087 * @param stdClass|int|null $user A moodle user object or id, null means current user
2088 * @throws coding_exception
2089 * @return string|mixed|null A string containing the value of a single preference. An
2090 * array with all of the preferences or null
2092 function get_user_preferences($name = null, $default = null, $user = null) {
2095 if (is_null($name)) {
2097 } else if (is_numeric($name) or $name === '_lastloaded') {
2098 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2101 if (is_null($user)) {
2103 } else if (isset($user->id
)) {
2104 // Is a valid object.
2105 } else if (is_numeric($user)) {
2106 if ($USER->id
== $user) {
2109 $user = (object)array('id' => (int)$user);
2112 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2115 check_user_preferences_loaded($user);
2119 return $user->preference
;
2120 } else if (isset($user->preference
[$name])) {
2121 // The single string value.
2122 return $user->preference
[$name];
2124 // Default value (null if not specified).
2129 // FUNCTIONS FOR HANDLING TIME.
2132 * Given Gregorian date parts in user time produce a GMT timestamp.
2136 * @param int $year The year part to create timestamp of
2137 * @param int $month The month part to create timestamp of
2138 * @param int $day The day part to create timestamp of
2139 * @param int $hour The hour part to create timestamp of
2140 * @param int $minute The minute part to create timestamp of
2141 * @param int $second The second part to create timestamp of
2142 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2143 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2144 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2145 * applied only if timezone is 99 or string.
2146 * @return int GMT timestamp
2148 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2149 $date = new DateTime('now', core_date
::get_user_timezone_object($timezone));
2150 $date->setDate((int)$year, (int)$month, (int)$day);
2151 $date->setTime((int)$hour, (int)$minute, (int)$second);
2153 $time = $date->getTimestamp();
2155 if ($time === false) {
2156 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2157 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2160 // Moodle BC DST stuff.
2162 $time +
= dst_offset_on($time, $timezone);
2170 * Format a date/time (seconds) as weeks, days, hours etc as needed
2172 * Given an amount of time in seconds, returns string
2173 * formatted nicely as years, days, hours etc as needed
2181 * @param int $totalsecs Time in seconds
2182 * @param stdClass $str Should be a time object
2183 * @return string A nicely formatted date/time string
2185 function format_time($totalsecs, $str = null) {
2187 $totalsecs = abs($totalsecs);
2190 // Create the str structure the slow way.
2191 $str = new stdClass();
2192 $str->day
= get_string('day');
2193 $str->days
= get_string('days');
2194 $str->hour
= get_string('hour');
2195 $str->hours
= get_string('hours');
2196 $str->min
= get_string('min');
2197 $str->mins
= get_string('mins');
2198 $str->sec
= get_string('sec');
2199 $str->secs
= get_string('secs');
2200 $str->year
= get_string('year');
2201 $str->years
= get_string('years');
2204 $years = floor($totalsecs/YEARSECS
);
2205 $remainder = $totalsecs - ($years*YEARSECS
);
2206 $days = floor($remainder/DAYSECS
);
2207 $remainder = $totalsecs - ($days*DAYSECS
);
2208 $hours = floor($remainder/HOURSECS
);
2209 $remainder = $remainder - ($hours*HOURSECS
);
2210 $mins = floor($remainder/MINSECS
);
2211 $secs = $remainder - ($mins*MINSECS
);
2213 $ss = ($secs == 1) ?
$str->sec
: $str->secs
;
2214 $sm = ($mins == 1) ?
$str->min
: $str->mins
;
2215 $sh = ($hours == 1) ?
$str->hour
: $str->hours
;
2216 $sd = ($days == 1) ?
$str->day
: $str->days
;
2217 $sy = ($years == 1) ?
$str->year
: $str->years
;
2226 $oyears = $years .' '. $sy;
2229 $odays = $days .' '. $sd;
2232 $ohours = $hours .' '. $sh;
2235 $omins = $mins .' '. $sm;
2238 $osecs = $secs .' '. $ss;
2242 return trim($oyears .' '. $odays);
2245 return trim($odays .' '. $ohours);
2248 return trim($ohours .' '. $omins);
2251 return trim($omins .' '. $osecs);
2256 return get_string('now');
2260 * Returns a formatted string that represents a date in user time.
2264 * @param int $date the timestamp in UTC, as obtained from the database.
2265 * @param string $format strftime format. You should probably get this using
2266 * get_string('strftime...', 'langconfig');
2267 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2268 * not 99 then daylight saving will not be added.
2269 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2270 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2271 * If false then the leading zero is maintained.
2272 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2273 * @return string the formatted date/time.
2275 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2276 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2277 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2281 * Returns a html "time" tag with both the exact user date with timezone information
2282 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2286 * @param int $date the timestamp in UTC, as obtained from the database.
2287 * @param string $format strftime format. You should probably get this using
2288 * get_string('strftime...', 'langconfig');
2289 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2290 * not 99 then daylight saving will not be added.
2291 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2292 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2293 * If false then the leading zero is maintained.
2294 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2295 * @return string the formatted date/time.
2297 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2298 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2299 if (CLI_SCRIPT
&& !PHPUNIT_TEST
) {
2300 return $userdatestr;
2302 $machinedate = new DateTime();
2303 $machinedate->setTimestamp(intval($date));
2304 $machinedate->setTimezone(core_date
::get_user_timezone_object());
2306 return html_writer
::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime
::W3C
)]);
2310 * Returns a formatted date ensuring it is UTF-8.
2312 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2313 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2315 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2316 * @param string $format strftime format.
2317 * @param int|float|string $tz the user timezone
2318 * @return string the formatted date/time.
2319 * @since Moodle 2.3.3
2321 function date_format_string($date, $format, $tz = 99) {
2324 $localewincharset = null;
2325 // Get the calendar type user is using.
2326 if ($CFG->ostype
== 'WINDOWS') {
2327 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2328 $localewincharset = $calendartype->locale_win_charset();
2331 if ($localewincharset) {
2332 $format = core_text
::convert($format, 'utf-8', $localewincharset);
2335 date_default_timezone_set(core_date
::get_user_timezone($tz));
2336 $datestring = strftime($format, $date);
2337 core_date
::set_default_server_timezone();
2339 if ($localewincharset) {
2340 $datestring = core_text
::convert($datestring, $localewincharset, 'utf-8');
2347 * Given a $time timestamp in GMT (seconds since epoch),
2348 * returns an array that represents the Gregorian date in user time
2352 * @param int $time Timestamp in GMT
2353 * @param float|int|string $timezone user timezone
2354 * @return array An array that represents the date in user time
2356 function usergetdate($time, $timezone=99) {
2357 if ($time === null) {
2358 // PHP8 and PHP7 return different results when getdate(null) is called.
2359 // Display warning and cast to 0 to make sure the usergetdate() behaves consistently on all versions of PHP.
2360 // In the future versions of Moodle we may consider adding a strict typehint.
2361 debugging('usergetdate() expects parameter $time to be int, null given', DEBUG_DEVELOPER
);
2365 date_default_timezone_set(core_date
::get_user_timezone($timezone));
2366 $result = getdate($time);
2367 core_date
::set_default_server_timezone();
2373 * Given a GMT timestamp (seconds since epoch), offsets it by
2374 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2376 * NOTE: this function does not include DST properly,
2377 * you should use the PHP date stuff instead!
2381 * @param int $date Timestamp in GMT
2382 * @param float|int|string $timezone user timezone
2385 function usertime($date, $timezone=99) {
2386 $userdate = new DateTime('@' . $date);
2387 $userdate->setTimezone(core_date
::get_user_timezone_object($timezone));
2388 $dst = dst_offset_on($date, $timezone);
2390 return $date - $userdate->getOffset() +
$dst;
2394 * Get a formatted string representation of an interval between two unix timestamps.
2397 * $intervalstring = get_time_interval_string(12345600, 12345660);
2398 * Will produce the string:
2401 * @param int $time1 unix timestamp
2402 * @param int $time2 unix timestamp
2403 * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2404 * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2406 function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
2407 $dtdate = new DateTime();
2408 $dtdate->setTimeStamp($time1);
2409 $dtdate2 = new DateTime();
2410 $dtdate2->setTimeStamp($time2);
2411 $interval = $dtdate2->diff($dtdate);
2412 $format = empty($format) ?
get_string('dateintervaldayshoursmins', 'langconfig') : $format;
2413 return $interval->format($format);
2417 * Given a time, return the GMT timestamp of the most recent midnight
2418 * for the current user.
2422 * @param int $date Timestamp in GMT
2423 * @param float|int|string $timezone user timezone
2424 * @return int Returns a GMT timestamp
2426 function usergetmidnight($date, $timezone=99) {
2428 $userdate = usergetdate($date, $timezone);
2430 // Time of midnight of this user's day, in GMT.
2431 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2436 * Returns a string that prints the user's timezone
2440 * @param float|int|string $timezone user timezone
2443 function usertimezone($timezone=99) {
2444 $tz = core_date
::get_user_timezone($timezone);
2445 return core_date
::get_localised_timezone($tz);
2449 * Returns a float or a string which denotes the user's timezone
2450 * 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)
2451 * means that for this timezone there are also DST rules to be taken into account
2452 * Checks various settings and picks the most dominant of those which have a value
2456 * @param float|int|string $tz timezone to calculate GMT time offset before
2457 * calculating user timezone, 99 is default user timezone
2458 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2459 * @return float|string
2461 function get_user_timezone($tz = 99) {
2466 isset($CFG->forcetimezone
) ?
$CFG->forcetimezone
: 99,
2467 isset($USER->timezone
) ?
$USER->timezone
: 99,
2468 isset($CFG->timezone
) ?
$CFG->timezone
: 99,
2473 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2474 foreach ($timezones as $nextvalue) {
2475 if ((empty($tz) && !is_numeric($tz)) ||
$tz == 99) {
2479 return is_numeric($tz) ?
(float) $tz : $tz;
2483 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2484 * - Note: Daylight saving only works for string timezones and not for float.
2488 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2489 * @param int|float|string $strtimezone user timezone
2492 function dst_offset_on($time, $strtimezone = null) {
2493 $tz = core_date
::get_user_timezone($strtimezone);
2494 $date = new DateTime('@' . $time);
2495 $date->setTimezone(new DateTimeZone($tz));
2496 if ($date->format('I') == '1') {
2497 if ($tz === 'Australia/Lord_Howe') {
2506 * Calculates when the day appears in specific month
2510 * @param int $startday starting day of the month
2511 * @param int $weekday The day when week starts (normally taken from user preferences)
2512 * @param int $month The month whose day is sought
2513 * @param int $year The year of the month whose day is sought
2516 function find_day_in_month($startday, $weekday, $month, $year) {
2517 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2519 $daysinmonth = days_in_month($month, $year);
2520 $daysinweek = count($calendartype->get_weekdays());
2522 if ($weekday == -1) {
2523 // Don't care about weekday, so return:
2524 // abs($startday) if $startday != -1
2525 // $daysinmonth otherwise.
2526 return ($startday == -1) ?
$daysinmonth : abs($startday);
2529 // From now on we 're looking for a specific weekday.
2530 // Give "end of month" its actual value, since we know it.
2531 if ($startday == -1) {
2532 $startday = -1 * $daysinmonth;
2535 // Starting from day $startday, the sign is the direction.
2536 if ($startday < 1) {
2537 $startday = abs($startday);
2538 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2540 // This is the last such weekday of the month.
2541 $lastinmonth = $daysinmonth +
$weekday - $lastmonthweekday;
2542 if ($lastinmonth > $daysinmonth) {
2543 $lastinmonth -= $daysinweek;
2546 // Find the first such weekday <= $startday.
2547 while ($lastinmonth > $startday) {
2548 $lastinmonth -= $daysinweek;
2551 return $lastinmonth;
2553 $indexweekday = dayofweek($startday, $month, $year);
2555 $diff = $weekday - $indexweekday;
2557 $diff +
= $daysinweek;
2560 // This is the first such weekday of the month equal to or after $startday.
2561 $firstfromindex = $startday +
$diff;
2563 return $firstfromindex;
2568 * Calculate the number of days in a given month
2572 * @param int $month The month whose day count is sought
2573 * @param int $year The year of the month whose day count is sought
2576 function days_in_month($month, $year) {
2577 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2578 return $calendartype->get_num_days_in_month($year, $month);
2582 * Calculate the position in the week of a specific calendar day
2586 * @param int $day The day of the date whose position in the week is sought
2587 * @param int $month The month of the date whose position in the week is sought
2588 * @param int $year The year of the date whose position in the week is sought
2591 function dayofweek($day, $month, $year) {
2592 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2593 return $calendartype->get_weekday($year, $month, $day);
2596 // USER AUTHENTICATION AND LOGIN.
2599 * Returns full login url.
2601 * Any form submissions for authentication to this URL must include username,
2602 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2604 * @return string login url
2606 function get_login_url() {
2609 return "$CFG->wwwroot/login/index.php";
2613 * This function checks that the current user is logged in and has the
2614 * required privileges
2616 * This function checks that the current user is logged in, and optionally
2617 * whether they are allowed to be in a particular course and view a particular
2619 * If they are not logged in, then it redirects them to the site login unless
2620 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2621 * case they are automatically logged in as guests.
2622 * If $courseid is given and the user is not enrolled in that course then the
2623 * user is redirected to the course enrolment page.
2624 * If $cm is given and the course module is hidden and the user is not a teacher
2625 * in the course then the user is redirected to the course home page.
2627 * When $cm parameter specified, this function sets page layout to 'module'.
2628 * You need to change it manually later if some other layout needed.
2630 * @package core_access
2633 * @param mixed $courseorid id of the course or course object
2634 * @param bool $autologinguest default true
2635 * @param object $cm course module object
2636 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2637 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2638 * in order to keep redirects working properly. MDL-14495
2639 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2640 * @return mixed Void, exit, and die depending on path
2641 * @throws coding_exception
2642 * @throws require_login_exception
2643 * @throws moodle_exception
2645 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2646 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2648 // Must not redirect when byteserving already started.
2649 if (!empty($_SERVER['HTTP_RANGE'])) {
2650 $preventredirect = true;
2654 // We cannot redirect for AJAX scripts either.
2655 $preventredirect = true;
2658 // Setup global $COURSE, themes, language and locale.
2659 if (!empty($courseorid)) {
2660 if (is_object($courseorid)) {
2661 $course = $courseorid;
2662 } else if ($courseorid == SITEID
) {
2663 $course = clone($SITE);
2665 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST
);
2668 if ($cm->course
!= $course->id
) {
2669 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2671 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2672 if (!($cm instanceof cm_info
)) {
2673 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2674 // db queries so this is not really a performance concern, however it is obviously
2675 // better if you use get_fast_modinfo to get the cm before calling this.
2676 $modinfo = get_fast_modinfo($course);
2677 $cm = $modinfo->get_cm($cm->id
);
2681 // Do not touch global $COURSE via $PAGE->set_course(),
2682 // the reasons is we need to be able to call require_login() at any time!!
2685 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2689 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2690 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2691 // risk leading the user back to the AJAX request URL.
2692 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT
) {
2693 $setwantsurltome = false;
2696 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2697 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out
) && !empty($CFG->dbsessions
)) {
2698 if ($preventredirect) {
2699 throw new require_login_session_timeout_exception();
2701 if ($setwantsurltome) {
2702 $SESSION->wantsurl
= qualified_me();
2704 redirect(get_login_url());
2708 // If the user is not even logged in yet then make sure they are.
2709 if (!isloggedin()) {
2710 if ($autologinguest and !empty($CFG->guestloginbutton
) and !empty($CFG->autologinguests
)) {
2711 if (!$guest = get_complete_user_data('id', $CFG->siteguest
)) {
2712 // Misconfigured site guest, just redirect to login page.
2713 redirect(get_login_url());
2714 exit; // Never reached.
2716 $lang = isset($SESSION->lang
) ?
$SESSION->lang
: $CFG->lang
;
2717 complete_user_login($guest);
2718 $USER->autologinguest
= true;
2719 $SESSION->lang
= $lang;
2721 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2722 if ($preventredirect) {
2723 throw new require_login_exception('You are not logged in');
2726 if ($setwantsurltome) {
2727 $SESSION->wantsurl
= qualified_me();
2730 $referer = get_local_referer(false);
2731 if (!empty($referer)) {
2732 $SESSION->fromurl
= $referer;
2735 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2736 $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
2737 foreach($authsequence as $authname) {
2738 $authplugin = get_auth_plugin($authname);
2739 $authplugin->pre_loginpage_hook();
2742 $modinfo = get_fast_modinfo($course);
2743 $cm = $modinfo->get_cm($cm->id
);
2745 set_access_log_user();
2750 // If we're still not logged in then go to the login page
2751 if (!isloggedin()) {
2752 redirect(get_login_url());
2753 exit; // Never reached.
2758 // Loginas as redirection if needed.
2759 if ($course->id
!= SITEID
and \core\session\manager
::is_loggedinas()) {
2760 if ($USER->loginascontext
->contextlevel
== CONTEXT_COURSE
) {
2761 if ($USER->loginascontext
->instanceid
!= $course->id
) {
2762 print_error('loginasonecourse', '', $CFG->wwwroot
.'/course/view.php?id='.$USER->loginascontext
->instanceid
);
2767 // Check whether the user should be changing password (but only if it is REALLY them).
2768 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager
::is_loggedinas()) {
2769 $userauth = get_auth_plugin($USER->auth
);
2770 if ($userauth->can_change_password() and !$preventredirect) {
2771 if ($setwantsurltome) {
2772 $SESSION->wantsurl
= qualified_me();
2774 if ($changeurl = $userauth->change_password_url()) {
2775 // Use plugin custom url.
2776 redirect($changeurl);
2778 // Use moodle internal method.
2779 redirect($CFG->wwwroot
.'/login/change_password.php');
2781 } else if ($userauth->can_change_password()) {
2782 throw new moodle_exception('forcepasswordchangenotice');
2784 throw new moodle_exception('nopasswordchangeforced', 'auth');
2788 // Check that the user account is properly set up. If we can't redirect to
2789 // edit their profile and this is not a WS request, perform just the lax check.
2790 // It will allow them to use filepicker on the profile edit page.
2792 if ($preventredirect && !WS_SERVER
) {
2793 $usernotfullysetup = user_not_fully_set_up($USER, false);
2795 $usernotfullysetup = user_not_fully_set_up($USER, true);
2798 if ($usernotfullysetup) {
2799 if ($preventredirect) {
2800 throw new moodle_exception('usernotfullysetup');
2802 if ($setwantsurltome) {
2803 $SESSION->wantsurl
= qualified_me();
2805 redirect($CFG->wwwroot
.'/user/edit.php?id='. $USER->id
.'&course='. SITEID
);
2808 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2811 if (\core\session\manager
::is_loggedinas()) {
2812 // During a "logged in as" session we should force all content to be cleaned because the
2813 // logged in user will be viewing potentially malicious user generated content.
2814 // See MDL-63786 for more details.
2815 $CFG->forceclean
= true;
2818 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2820 // Do not bother admins with any formalities, except for activities pending deletion.
2821 if (is_siteadmin() && !($cm && $cm->deletioninprogress
)) {
2822 // Set the global $COURSE.
2824 $PAGE->set_cm($cm, $course);
2825 $PAGE->set_pagelayout('incourse');
2826 } else if (!empty($courseorid)) {
2827 $PAGE->set_course($course);
2829 // Set accesstime or the user will appear offline which messes up messaging.
2830 // Do not update access time for webservice or ajax requests.
2831 if (!WS_SERVER
&& !AJAX_SCRIPT
) {
2832 user_accesstime_log($course->id
);
2835 foreach ($afterlogins as $plugintype => $plugins) {
2836 foreach ($plugins as $pluginfunction) {
2837 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2843 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2844 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2845 if (!defined('NO_SITEPOLICY_CHECK')) {
2846 define('NO_SITEPOLICY_CHECK', false);
2849 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2850 // Do not test if the script explicitly asked for skipping the site policies check.
2851 if (!$USER->policyagreed
&& !is_siteadmin() && !NO_SITEPOLICY_CHECK
) {
2852 $manager = new \core_privacy\local\sitepolicy\
manager();
2853 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2854 if ($preventredirect) {
2855 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2857 if ($setwantsurltome) {
2858 $SESSION->wantsurl
= qualified_me();
2860 redirect($policyurl);
2864 // Fetch the system context, the course context, and prefetch its child contexts.
2865 $sysctx = context_system
::instance();
2866 $coursecontext = context_course
::instance($course->id
, MUST_EXIST
);
2868 $cmcontext = context_module
::instance($cm->id
, MUST_EXIST
);
2873 // If the site is currently under maintenance, then print a message.
2874 if (!empty($CFG->maintenance_enabled
) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2875 if ($preventredirect) {
2876 throw new require_login_exception('Maintenance in progress');
2878 $PAGE->set_context(null);
2879 print_maintenance_message();
2882 // Make sure the course itself is not hidden.
2883 if ($course->id
== SITEID
) {
2884 // Frontpage can not be hidden.
2886 if (is_role_switched($course->id
)) {
2887 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2889 if (!$course->visible
and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2890 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2891 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2892 if ($preventredirect) {
2893 throw new require_login_exception('Course is hidden');
2895 $PAGE->set_context(null);
2896 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2897 // the navigation will mess up when trying to find it.
2898 navigation_node
::override_active_url(new moodle_url('/'));
2899 notice(get_string('coursehidden'), $CFG->wwwroot
.'/');
2904 // Is the user enrolled?
2905 if ($course->id
== SITEID
) {
2906 // Everybody is enrolled on the frontpage.
2908 if (\core\session\manager
::is_loggedinas()) {
2909 // Make sure the REAL person can access this course first.
2910 $realuser = \core\session\manager
::get_realuser();
2911 if (!is_enrolled($coursecontext, $realuser->id
, '', true) and
2912 !is_viewing($coursecontext, $realuser->id
) and !is_siteadmin($realuser->id
)) {
2913 if ($preventredirect) {
2914 throw new require_login_exception('Invalid course login-as access');
2916 $PAGE->set_context(null);
2917 echo $OUTPUT->header();
2918 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot
.'/');
2924 if (is_role_switched($course->id
)) {
2925 // Ok, user had to be inside this course before the switch.
2928 } else if (is_viewing($coursecontext, $USER)) {
2929 // Ok, no need to mess with enrol.
2933 if (isset($USER->enrol
['enrolled'][$course->id
])) {
2934 if ($USER->enrol
['enrolled'][$course->id
] > time()) {
2936 if (isset($USER->enrol
['tempguest'][$course->id
])) {
2937 unset($USER->enrol
['tempguest'][$course->id
]);
2938 remove_temp_course_roles($coursecontext);
2942 unset($USER->enrol
['enrolled'][$course->id
]);
2945 if (isset($USER->enrol
['tempguest'][$course->id
])) {
2946 if ($USER->enrol
['tempguest'][$course->id
] == 0) {
2948 } else if ($USER->enrol
['tempguest'][$course->id
] > time()) {
2952 unset($USER->enrol
['tempguest'][$course->id
]);
2953 remove_temp_course_roles($coursecontext);
2959 $until = enrol_get_enrolment_end($coursecontext->instanceid
, $USER->id
);
2960 if ($until !== false) {
2961 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2963 $until = ENROL_MAX_TIMESTAMP
;
2965 $USER->enrol
['enrolled'][$course->id
] = $until;
2968 } else if (core_course_category
::can_view_course_info($course)) {
2969 $params = array('courseid' => $course->id
, 'status' => ENROL_INSTANCE_ENABLED
);
2970 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2971 $enrols = enrol_get_plugins(true);
2972 // First ask all enabled enrol instances in course if they want to auto enrol user.
2973 foreach ($instances as $instance) {
2974 if (!isset($enrols[$instance->enrol
])) {
2977 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2978 $until = $enrols[$instance->enrol
]->try_autoenrol($instance);
2979 if ($until !== false) {
2981 $until = ENROL_MAX_TIMESTAMP
;
2983 $USER->enrol
['enrolled'][$course->id
] = $until;
2988 // If not enrolled yet try to gain temporary guest access.
2990 foreach ($instances as $instance) {
2991 if (!isset($enrols[$instance->enrol
])) {
2994 // Get a duration for the guest access, a timestamp in the future or false.
2995 $until = $enrols[$instance->enrol
]->try_guestaccess($instance);
2996 if ($until !== false and $until > time()) {
2997 $USER->enrol
['tempguest'][$course->id
] = $until;
3004 // User is not enrolled and is not allowed to browse courses here.
3005 if ($preventredirect) {
3006 throw new require_login_exception('Course is not available');
3008 $PAGE->set_context(null);
3009 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3010 // the navigation will mess up when trying to find it.
3011 navigation_node
::override_active_url(new moodle_url('/'));
3012 notice(get_string('coursehidden'), $CFG->wwwroot
.'/');
3018 if ($preventredirect) {
3019 throw new require_login_exception('Not enrolled');
3021 if ($setwantsurltome) {
3022 $SESSION->wantsurl
= qualified_me();
3024 redirect($CFG->wwwroot
.'/enrol/index.php?id='. $course->id
);
3028 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3029 if ($cm && $cm->deletioninprogress
) {
3030 if ($preventredirect) {
3031 throw new moodle_exception('activityisscheduledfordeletion');
3033 require_once($CFG->dirroot
. '/course/lib.php');
3034 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3037 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3038 if ($cm && !$cm->uservisible
) {
3039 if ($preventredirect) {
3040 throw new require_login_exception('Activity is hidden');
3042 // Get the error message that activity is not available and why (if explanation can be shown to the user).
3043 $PAGE->set_course($course);
3044 $renderer = $PAGE->get_renderer('course');
3045 $message = $renderer->course_section_cm_unavailable_error_message($cm);
3046 redirect(course_get_url($course), $message, null, \core\output\notification
::NOTIFY_ERROR
);
3049 // Set the global $COURSE.
3051 $PAGE->set_cm($cm, $course);
3052 $PAGE->set_pagelayout('incourse');
3053 } else if (!empty($courseorid)) {
3054 $PAGE->set_course($course);
3057 foreach ($afterlogins as $plugintype => $plugins) {
3058 foreach ($plugins as $pluginfunction) {
3059 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3063 // Finally access granted, update lastaccess times.
3064 // Do not update access time for webservice or ajax requests.
3065 if (!WS_SERVER
&& !AJAX_SCRIPT
) {
3066 user_accesstime_log($course->id
);
3071 * A convenience function for where we must be logged in as admin
3074 function require_admin() {
3075 require_login(null, false);
3076 require_capability('moodle/site:config', context_system
::instance());
3080 * This function just makes sure a user is logged out.
3082 * @package core_access
3085 function require_logout() {
3088 if (!isloggedin()) {
3089 // This should not happen often, no need for hooks or events here.
3090 \core\session\manager
::terminate_current();
3094 // Execute hooks before action.
3095 $authplugins = array();
3096 $authsequence = get_enabled_auth_plugins();
3097 foreach ($authsequence as $authname) {
3098 $authplugins[$authname] = get_auth_plugin($authname);
3099 $authplugins[$authname]->prelogout_hook();
3102 // Store info that gets removed during logout.
3103 $sid = session_id();
3104 $event = \core\event\user_loggedout
::create(
3106 'userid' => $USER->id
,
3107 'objectid' => $USER->id
,
3108 'other' => array('sessionid' => $sid),
3111 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3112 $event->add_record_snapshot('sessions', $session);
3115 // Clone of $USER object to be used by auth plugins.
3116 $user = fullclone($USER);
3118 // Delete session record and drop $_SESSION content.
3119 \core\session\manager
::terminate_current();
3121 // Trigger event AFTER action.
3124 // Hook to execute auth plugins redirection after event trigger.
3125 foreach ($authplugins as $authplugin) {
3126 $authplugin->postlogout_hook($user);
3131 * Weaker version of require_login()
3133 * This is a weaker version of {@link require_login()} which only requires login
3134 * when called from within a course rather than the site page, unless
3135 * the forcelogin option is turned on.
3136 * @see require_login()
3138 * @package core_access
3141 * @param mixed $courseorid The course object or id in question
3142 * @param bool $autologinguest Allow autologin guests if that is wanted
3143 * @param object $cm Course activity module if known
3144 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3145 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3146 * in order to keep redirects working properly. MDL-14495
3147 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3149 * @throws coding_exception
3151 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3152 global $CFG, $PAGE, $SITE;
3153 $issite = ((is_object($courseorid) and $courseorid->id
== SITEID
)
3154 or (!is_object($courseorid) and $courseorid == SITEID
));
3155 if ($issite && !empty($cm) && !($cm instanceof cm_info
)) {
3156 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3157 // db queries so this is not really a performance concern, however it is obviously
3158 // better if you use get_fast_modinfo to get the cm before calling this.
3159 if (is_object($courseorid)) {
3160 $course = $courseorid;
3162 $course = clone($SITE);
3164 $modinfo = get_fast_modinfo($course);
3165 $cm = $modinfo->get_cm($cm->id
);
3167 if (!empty($CFG->forcelogin
)) {
3168 // Login required for both SITE and courses.
3169 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3171 } else if ($issite && !empty($cm) and !$cm->uservisible
) {
3172 // Always login for hidden activities.
3173 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3175 } else if (isloggedin() && !isguestuser()) {
3176 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3177 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3179 } else if ($issite) {
3180 // Login for SITE not required.
3181 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3182 if (!empty($courseorid)) {
3183 if (is_object($courseorid)) {
3184 $course = $courseorid;
3186 $course = clone $SITE;
3189 if ($cm->course
!= $course->id
) {
3190 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3192 $PAGE->set_cm($cm, $course);
3193 $PAGE->set_pagelayout('incourse');
3195 $PAGE->set_course($course);
3198 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3199 $PAGE->set_course($PAGE->course
);
3201 // Do not update access time for webservice or ajax requests.
3202 if (!WS_SERVER
&& !AJAX_SCRIPT
) {
3203 user_accesstime_log(SITEID
);
3208 // Course login always required.
3209 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3214 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3216 * @param string $keyvalue the key value
3217 * @param string $script unique script identifier
3218 * @param int $instance instance id
3219 * @return stdClass the key entry in the user_private_key table
3221 * @throws moodle_exception
3223 function validate_user_key($keyvalue, $script, $instance) {
3226 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3227 print_error('invalidkey');
3230 if (!empty($key->validuntil
) and $key->validuntil
< time()) {
3231 print_error('expiredkey');
3234 if ($key->iprestriction
) {
3235 $remoteaddr = getremoteaddr(null);
3236 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction
)) {
3237 print_error('ipmismatch');
3244 * Require key login. Function terminates with error if key not found or incorrect.
3246 * @uses NO_MOODLE_COOKIES
3247 * @uses PARAM_ALPHANUM
3248 * @param string $script unique script identifier
3249 * @param int $instance optional instance id
3250 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3251 * @return int Instance ID
3253 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3256 if (!NO_MOODLE_COOKIES
) {
3257 print_error('sessioncookiesdisable');
3261 \core\session\manager
::write_close();
3263 if (null === $keyvalue) {
3264 $keyvalue = required_param('key', PARAM_ALPHANUM
);
3267 $key = validate_user_key($keyvalue, $script, $instance);
3269 if (!$user = $DB->get_record('user', array('id' => $key->userid
))) {
3270 print_error('invaliduserid');
3273 core_user
::require_active_user($user, true, true);
3275 // Emulate normal session.
3276 enrol_check_plugins($user);
3277 \core\session\manager
::set_user($user);
3279 // Note we are not using normal login.
3280 if (!defined('USER_KEY_LOGIN')) {
3281 define('USER_KEY_LOGIN', true);
3284 // Return instance id - it might be empty.
3285 return $key->instance
;
3289 * Creates a new private user access key.
3291 * @param string $script unique target identifier
3292 * @param int $userid
3293 * @param int $instance optional instance id
3294 * @param string $iprestriction optional ip restricted access
3295 * @param int $validuntil key valid only until given data
3296 * @return string access key value
3298 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3301 $key = new stdClass();
3302 $key->script
= $script;
3303 $key->userid
= $userid;
3304 $key->instance
= $instance;
3305 $key->iprestriction
= $iprestriction;
3306 $key->validuntil
= $validuntil;
3307 $key->timecreated
= time();
3309 // Something long and unique.
3310 $key->value
= md5($userid.'_'.time().random_string(40));
3311 while ($DB->record_exists('user_private_key', array('value' => $key->value
))) {
3313 $key->value
= md5($userid.'_'.time().random_string(40));
3315 $DB->insert_record('user_private_key', $key);
3320 * Delete the user's new private user access keys for a particular script.
3322 * @param string $script unique target identifier
3323 * @param int $userid
3326 function delete_user_key($script, $userid) {
3328 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3332 * Gets a private user access key (and creates one if one doesn't exist).
3334 * @param string $script unique target identifier
3335 * @param int $userid
3336 * @param int $instance optional instance id
3337 * @param string $iprestriction optional ip restricted access
3338 * @param int $validuntil key valid only until given date
3339 * @return string access key value
3341 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3344 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3345 'instance' => $instance, 'iprestriction' => $iprestriction,
3346 'validuntil' => $validuntil))) {
3349 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3355 * Modify the user table by setting the currently logged in user's last login to now.
3357 * @return bool Always returns true
3359 function update_user_login_times() {
3362 if (isguestuser()) {
3363 // Do not update guest access times/ips for performance.
3369 $user = new stdClass();
3370 $user->id
= $USER->id
;
3372 // Make sure all users that logged in have some firstaccess.
3373 if ($USER->firstaccess
== 0) {
3374 $USER->firstaccess
= $user->firstaccess
= $now;
3377 // Store the previous current as lastlogin.
3378 $USER->lastlogin
= $user->lastlogin
= $USER->currentlogin
;
3380 $USER->currentlogin
= $user->currentlogin
= $now;
3382 // Function user_accesstime_log() may not update immediately, better do it here.
3383 $USER->lastaccess
= $user->lastaccess
= $now;
3384 $USER->lastip
= $user->lastip
= getremoteaddr();
3386 // Note: do not call user_update_user() here because this is part of the login process,
3387 // the login event means that these fields were updated.
3388 $DB->update_record('user', $user);
3393 * Determines if a user has completed setting up their account.
3395 * The lax mode (with $strict = false) has been introduced for special cases
3396 * only where we want to skip certain checks intentionally. This is valid in
3397 * certain mnet or ajax scenarios when the user cannot / should not be
3398 * redirected to edit their profile. In most cases, you should perform the
3401 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3402 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3405 function user_not_fully_set_up($user, $strict = true) {
3407 require_once($CFG->dirroot
.'/user/profile/lib.php');
3409 if (isguestuser($user)) {
3413 if (empty($user->firstname
) or empty($user->lastname
) or empty($user->email
) or over_bounce_threshold($user)) {
3418 if (empty($user->id
)) {
3419 // Strict mode can be used with existing accounts only.
3422 if (!profile_has_required_custom_fields_set($user->id
)) {
3431 * Check whether the user has exceeded the bounce threshold
3433 * @param stdClass $user A {@link $USER} object
3434 * @return bool true => User has exceeded bounce threshold
3436 function over_bounce_threshold($user) {
3439 if (empty($CFG->handlebounces
)) {
3443 if (empty($user->id
)) {
3444 // No real (DB) user, nothing to do here.
3448 // Set sensible defaults.
3449 if (empty($CFG->minbounces
)) {
3450 $CFG->minbounces
= 10;
3452 if (empty($CFG->bounceratio
)) {
3453 $CFG->bounceratio
= .20;
3457 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id
, 'name' => 'email_bounce_count'))) {
3458 $bouncecount = $bounce->value
;
3460 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_send_count'))) {
3461 $sendcount = $send->value
;
3463 return ($bouncecount >= $CFG->minbounces
&& $bouncecount/$sendcount >= $CFG->bounceratio
);
3467 * Used to increment or reset email sent count
3469 * @param stdClass $user object containing an id
3470 * @param bool $reset will reset the count to 0
3473 function set_send_count($user, $reset=false) {
3476 if (empty($user->id
)) {
3477 // No real (DB) user, nothing to do here.
3481 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_send_count'))) {
3482 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3483 $DB->update_record('user_preferences', $pref);
3484 } else if (!empty($reset)) {
3485 // If it's not there and we're resetting, don't bother. Make a new one.
3486 $pref = new stdClass();
3487 $pref->name
= 'email_send_count';
3489 $pref->userid
= $user->id
;
3490 $DB->insert_record('user_preferences', $pref, false);
3495 * Increment or reset user's email bounce count
3497 * @param stdClass $user object containing an id
3498 * @param bool $reset will reset the count to 0
3500 function set_bounce_count($user, $reset=false) {
3503 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_bounce_count'))) {
3504 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3505 $DB->update_record('user_preferences', $pref);
3506 } else if (!empty($reset)) {
3507 // If it's not there and we're resetting, don't bother. Make a new one.
3508 $pref = new stdClass();
3509 $pref->name
= 'email_bounce_count';
3511 $pref->userid
= $user->id
;
3512 $DB->insert_record('user_preferences', $pref, false);
3517 * Determines if the logged in user is currently moving an activity
3519 * @param int $courseid The id of the course being tested
3522 function ismoving($courseid) {
3525 if (!empty($USER->activitycopy
)) {
3526 return ($USER->activitycopycourse
== $courseid);
3532 * Returns a persons full name
3534 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3535 * The result may depend on system settings or language. 'override' will force the alternativefullnameformat to be used. In
3536 * English, fullname as well as alternativefullnameformat is set to 'firstname lastname' by default. But you could have
3537 * fullname set to 'firstname lastname' and alternativefullnameformat set to 'firstname middlename alternatename lastname'.
3539 * @param stdClass $user A {@link $USER} object to get full name of.
3540 * @param bool $override If true then the alternativefullnameformat format rather than fullnamedisplay format will be used.
3543 function fullname($user, $override=false) {
3544 global $CFG, $SESSION;
3546 if (!isset($user->firstname
) and !isset($user->lastname
)) {
3550 // Get all of the name fields.
3551 $allnames = \core_user\fields
::get_name_fields();
3552 if ($CFG->debugdeveloper
) {
3553 foreach ($allnames as $allname) {
3554 if (!property_exists($user, $allname)) {
3555 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3556 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER
);
3557 // Message has been sent, no point in sending the message multiple times.
3564 if (!empty($CFG->forcefirstname
)) {
3565 $user->firstname
= $CFG->forcefirstname
;
3567 if (!empty($CFG->forcelastname
)) {
3568 $user->lastname
= $CFG->forcelastname
;
3572 if (!empty($SESSION->fullnamedisplay
)) {
3573 $CFG->fullnamedisplay
= $SESSION->fullnamedisplay
;
3577 // If the fullnamedisplay setting is available, set the template to that.
3578 if (isset($CFG->fullnamedisplay
)) {
3579 $template = $CFG->fullnamedisplay
;
3581 // If the template is empty, or set to language, return the language string.
3582 if ((empty($template) ||
$template == 'language') && !$override) {
3583 return get_string('fullnamedisplay', null, $user);
3586 // Check to see if we are displaying according to the alternative full name format.
3588 if (empty($CFG->alternativefullnameformat
) ||
$CFG->alternativefullnameformat
== 'language') {
3589 // Default to show just the user names according to the fullnamedisplay string.
3590 return get_string('fullnamedisplay', null, $user);
3592 // If the override is true, then change the template to use the complete name.
3593 $template = $CFG->alternativefullnameformat
;
3597 $requirednames = array();
3598 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3599 foreach ($allnames as $allname) {
3600 if (strpos($template, $allname) !== false) {
3601 $requirednames[] = $allname;
3605 $displayname = $template;
3606 // Switch in the actual data into the template.
3607 foreach ($requirednames as $altname) {
3608 if (isset($user->$altname)) {
3609 // Using empty() on the below if statement causes breakages.
3610 if ((string)$user->$altname == '') {
3611 $displayname = str_replace($altname, 'EMPTY', $displayname);
3613 $displayname = str_replace($altname, $user->$altname, $displayname);
3616 $displayname = str_replace($altname, 'EMPTY', $displayname);
3619 // Tidy up any misc. characters (Not perfect, but gets most characters).
3620 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3621 // katakana and parenthesis.
3622 $patterns = array();
3623 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3624 // filled in by a user.
3625 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3626 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3627 // This regular expression is to remove any double spaces in the display name.
3628 $patterns[] = '/\s{2,}/u';
3629 foreach ($patterns as $pattern) {
3630 $displayname = preg_replace($pattern, ' ', $displayname);
3633 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3634 $displayname = trim($displayname);
3635 if (empty($displayname)) {
3636 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3637 // people in general feel is a good setting to fall back on.
3638 $displayname = $user->firstname
;
3640 return $displayname;
3644 * Reduces lines of duplicated code for getting user name fields.
3646 * See also {@link user_picture::unalias()}
3648 * @param object $addtoobject Object to add user name fields to.
3649 * @param object $secondobject Object that contains user name field information.
3650 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3651 * @param array $additionalfields Additional fields to be matched with data in the second object.
3652 * The key can be set to the user table field name.
3653 * @return object User name fields.
3655 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3657 foreach (\core_user\fields
::get_name_fields() as $field) {
3658 $fields[$field] = $prefix . $field;
3660 if ($additionalfields) {
3661 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3662 // the key is a number and then sets the key to the array value.
3663 foreach ($additionalfields as $key => $value) {
3664 if (is_numeric($key)) {
3665 $additionalfields[$value] = $prefix . $value;
3666 unset($additionalfields[$key]);
3668 $additionalfields[$key] = $prefix . $value;
3671 $fields = array_merge($fields, $additionalfields);
3673 foreach ($fields as $key => $field) {
3674 // Important that we have all of the user name fields present in the object that we are sending back.
3675 $addtoobject->$key = '';
3676 if (isset($secondobject->$field)) {
3677 $addtoobject->$key = $secondobject->$field;
3680 return $addtoobject;
3684 * Returns an array of values in order of occurance in a provided string.
3685 * The key in the result is the character postion in the string.
3687 * @param array $values Values to be found in the string format
3688 * @param string $stringformat The string which may contain values being searched for.
3689 * @return array An array of values in order according to placement in the string format.
3691 function order_in_string($values, $stringformat) {
3692 $valuearray = array();
3693 foreach ($values as $value) {
3694 $pattern = "/$value\b/";
3695 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3696 if (preg_match($pattern, $stringformat)) {
3697 $replacement = "thing";
3698 // Replace the value with something more unique to ensure we get the right position when using strpos().
3699 $newformat = preg_replace($pattern, $replacement, $stringformat);
3700 $position = strpos($newformat, $replacement);
3701 $valuearray[$position] = $value;
3709 * Returns whether a given authentication plugin exists.
3711 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3712 * @return boolean Whether the plugin is available.
3714 function exists_auth_plugin($auth) {
3717 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3718 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3724 * Checks if a given plugin is in the list of enabled authentication plugins.
3726 * @param string $auth Authentication plugin.
3727 * @return boolean Whether the plugin is enabled.
3729 function is_enabled_auth($auth) {
3734 $enabled = get_enabled_auth_plugins();
3736 return in_array($auth, $enabled);
3740 * Returns an authentication plugin instance.
3742 * @param string $auth name of authentication plugin
3743 * @return auth_plugin_base An instance of the required authentication plugin.
3745 function get_auth_plugin($auth) {
3748 // Check the plugin exists first.
3749 if (! exists_auth_plugin($auth)) {
3750 print_error('authpluginnotfound', 'debug', '', $auth);
3753 // Return auth plugin instance.
3754 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3755 $class = "auth_plugin_$auth";
3760 * Returns array of active auth plugins.
3762 * @param bool $fix fix $CFG->auth if needed. Only set if logged in as admin.
3765 function get_enabled_auth_plugins($fix=false) {
3768 $default = array('manual', 'nologin');
3770 if (empty($CFG->auth
)) {
3773 $auths = explode(',', $CFG->auth
);
3776 $auths = array_unique($auths);
3777 $oldauthconfig = implode(',', $auths);
3778 foreach ($auths as $k => $authname) {
3779 if (in_array($authname, $default)) {
3780 // The manual and nologin plugin never need to be stored.
3782 } else if (!exists_auth_plugin($authname)) {
3783 debugging(get_string('authpluginnotfound', 'debug', $authname));
3788 // Ideally only explicit interaction from a human admin should trigger a
3789 // change in auth config, see MDL-70424 for details.
3791 $newconfig = implode(',', $auths);
3792 if (!isset($CFG->auth
) or $newconfig != $CFG->auth
) {
3793 add_to_config_log('auth', $oldauthconfig, $newconfig, 'core');
3794 set_config('auth', $newconfig);
3798 return (array_merge($default, $auths));
3802 * Returns true if an internal authentication method is being used.
3803 * if method not specified then, global default is assumed
3805 * @param string $auth Form of authentication required
3808 function is_internal_auth($auth) {
3809 // Throws error if bad $auth.
3810 $authplugin = get_auth_plugin($auth);
3811 return $authplugin->is_internal();
3815 * Returns true if the user is a 'restored' one.
3817 * Used in the login process to inform the user and allow him/her to reset the password
3819 * @param string $username username to be checked
3822 function is_restored_user($username) {
3825 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'password' => 'restored'));
3829 * Returns an array of user fields
3831 * @return array User field/column names
3833 function get_user_fieldnames() {
3836 $fieldarray = $DB->get_columns('user');
3837 unset($fieldarray['id']);
3838 $fieldarray = array_keys($fieldarray);
3844 * Returns the string of the language for the new user.
3846 * @return string language for the new user
3848 function get_newuser_language() {
3849 global $CFG, $SESSION;
3850 return (!empty($CFG->autolangusercreation
) && !empty($SESSION->lang
)) ?
$SESSION->lang
: $CFG->lang
;
3854 * Creates a bare-bones user record
3856 * @todo Outline auth types and provide code example
3858 * @param string $username New user's username to add to record
3859 * @param string $password New user's password to add to record
3860 * @param string $auth Form of authentication required
3861 * @return stdClass A complete user object
3863 function create_user_record($username, $password, $auth = 'manual') {
3864 global $CFG, $DB, $SESSION;
3865 require_once($CFG->dirroot
.'/user/profile/lib.php');
3866 require_once($CFG->dirroot
.'/user/lib.php');
3868 // Just in case check text case.
3869 $username = trim(core_text
::strtolower($username));
3871 $authplugin = get_auth_plugin($auth);
3872 $customfields = $authplugin->get_custom_user_profile_fields();
3873 $newuser = new stdClass();
3874 if ($newinfo = $authplugin->get_userinfo($username)) {
3875 $newinfo = truncate_userinfo($newinfo);
3876 foreach ($newinfo as $key => $value) {
3877 if (in_array($key, $authplugin->userfields
) ||
(in_array($key, $customfields))) {
3878 $newuser->$key = $value;
3883 if (!empty($newuser->email
)) {
3884 if (email_is_not_allowed($newuser->email
)) {
3885 unset($newuser->email
);
3889 if (!isset($newuser->city
)) {
3890 $newuser->city
= '';
3893 $newuser->auth
= $auth;
3894 $newuser->username
= $username;
3897 // user CFG lang for user if $newuser->lang is empty
3898 // or $user->lang is not an installed language.
3899 if (empty($newuser->lang
) ||
!get_string_manager()->translation_exists($newuser->lang
)) {
3900 $newuser->lang
= get_newuser_language();
3902 $newuser->confirmed
= 1;
3903 $newuser->lastip
= getremoteaddr();
3904 $newuser->timecreated
= time();
3905 $newuser->timemodified
= $newuser->timecreated
;
3906 $newuser->mnethostid
= $CFG->mnet_localhost_id
;
3908 $newuser->id
= user_create_user($newuser, false, false);
3910 // Save user profile data.
3911 profile_save_data($newuser);
3913 $user = get_complete_user_data('id', $newuser->id
);
3914 if (!empty($CFG->{'auth_'.$newuser->auth
.'_forcechangepassword'})) {
3915 set_user_preference('auth_forcepasswordchange', 1, $user);
3917 // Set the password.
3918 update_internal_user_password($user, $password);
3921 \core\event\user_created
::create_from_userid($newuser->id
)->trigger();
3927 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3929 * @param string $username user's username to update the record
3930 * @return stdClass A complete user object
3932 function update_user_record($username) {
3934 // Just in case check text case.
3935 $username = trim(core_text
::strtolower($username));
3937 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
), '*', MUST_EXIST
);
3938 return update_user_record_by_id($oldinfo->id
);
3942 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3944 * @param int $id user id
3945 * @return stdClass A complete user object
3947 function update_user_record_by_id($id) {
3949 require_once($CFG->dirroot
."/user/profile/lib.php");
3950 require_once($CFG->dirroot
.'/user/lib.php');
3952 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'id' => $id, 'deleted' => 0);
3953 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST
);
3956 $userauth = get_auth_plugin($oldinfo->auth
);
3958 if ($newinfo = $userauth->get_userinfo($oldinfo->username
)) {
3959 $newinfo = truncate_userinfo($newinfo);
3960 $customfields = $userauth->get_custom_user_profile_fields();
3962 foreach ($newinfo as $key => $value) {
3963 $iscustom = in_array($key, $customfields);
3965 $key = strtolower($key);
3967 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3968 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3969 // Unknown or must not be changed.
3972 if (empty($userauth->config
->{'field_updatelocal_' . $key}) ||
empty($userauth->config
->{'field_lock_' . $key})) {
3975 $confval = $userauth->config
->{'field_updatelocal_' . $key};
3976 $lockval = $userauth->config
->{'field_lock_' . $key};
3977 if ($confval === 'onlogin') {
3978 // MDL-4207 Don't overwrite modified user profile values with
3979 // empty LDAP values when 'unlocked if empty' is set. The purpose
3980 // of the setting 'unlocked if empty' is to allow the user to fill
3981 // in a value for the selected field _if LDAP is giving
3982 // nothing_ for this field. Thus it makes sense to let this value
3983 // stand in until LDAP is giving a value for this field.
3984 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3985 if ($iscustom ||
(in_array($key, $userauth->userfields
) &&
3986 ((string)$oldinfo->$key !== (string)$value))) {
3987 $newuser[$key] = (string)$value;
3993 $newuser['id'] = $oldinfo->id
;
3994 $newuser['timemodified'] = time();
3995 user_update_user((object) $newuser, false, false);
3997 // Save user profile data.
3998 profile_save_data((object) $newuser);
4001 \core\event\user_updated
::create_from_userid($newuser['id'])->trigger();
4005 return get_complete_user_data('id', $oldinfo->id
);
4009 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4011 * @param array $info Array of user properties to truncate if needed
4012 * @return array The now truncated information that was passed in
4014 function truncate_userinfo(array $info) {
4015 // Define the limits.
4024 'institution' => 255,
4025 'department' => 255,
4031 // Apply where needed.
4032 foreach (array_keys($info) as $key) {
4033 if (!empty($limit[$key])) {
4034 $info[$key] = trim(core_text
::substr($info[$key], 0, $limit[$key]));
4042 * Marks user deleted in internal user database and notifies the auth plugin.
4043 * Also unenrols user from all roles and does other cleanup.
4045 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4047 * @param stdClass $user full user object before delete
4048 * @return boolean success
4049 * @throws coding_exception if invalid $user parameter detected
4051 function delete_user(stdClass
$user) {
4052 global $CFG, $DB, $SESSION;
4053 require_once($CFG->libdir
.'/grouplib.php');
4054 require_once($CFG->libdir
.'/gradelib.php');
4055 require_once($CFG->dirroot
.'/message/lib.php');
4056 require_once($CFG->dirroot
.'/user/lib.php');
4058 // Make sure nobody sends bogus record type as parameter.
4059 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4060 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4063 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4064 if (!$user = $DB->get_record('user', array('id' => $user->id
))) {
4065 debugging('Attempt to delete unknown user account.');
4069 // There must be always exactly one guest record, originally the guest account was identified by username only,
4070 // now we use $CFG->siteguest for performance reasons.
4071 if ($user->username
=== 'guest' or isguestuser($user)) {
4072 debugging('Guest user account can not be deleted.');
4076 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4077 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4078 if ($user->auth
=== 'manual' and is_siteadmin($user)) {
4079 debugging('Local administrator accounts can not be deleted.');
4083 // Allow plugins to use this user object before we completely delete it.
4084 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4085 foreach ($pluginsfunction as $plugintype => $plugins) {
4086 foreach ($plugins as $pluginfunction) {
4087 $pluginfunction($user);
4092 // Keep user record before updating it, as we have to pass this to user_deleted event.
4093 $olduser = clone $user;
4095 // Keep a copy of user context, we need it for event.
4096 $usercontext = context_user
::instance($user->id
);
4098 // Delete all grades - backup is kept in grade_grades_history table.
4099 grade_user_delete($user->id
);
4101 // TODO: remove from cohorts using standard API here.
4103 // Remove user tags.
4104 core_tag_tag
::remove_all_item_tags('core', 'user', $user->id
);
4106 // Unconditionally unenrol from all courses.
4107 enrol_user_delete($user);
4109 // Unenrol from all roles in all contexts.
4110 // This might be slow but it is really needed - modules might do some extra cleanup!
4111 role_unassign_all(array('userid' => $user->id
));
4113 // Notify the competency subsystem.
4114 \core_competency\api
::hook_user_deleted($user->id
);
4116 // Now do a brute force cleanup.
4118 // Delete all user events and subscription events.
4119 $DB->delete_records_select('event', 'userid = :userid AND subscriptionid IS NOT NULL', ['userid' => $user->id
]);
4121 // Now, delete all calendar subscription from the user.
4122 $DB->delete_records('event_subscriptions', ['userid' => $user->id
]);
4124 // Remove from all cohorts.
4125 $DB->delete_records('cohort_members', array('userid' => $user->id
));
4127 // Remove from all groups.
4128 $DB->delete_records('groups_members', array('userid' => $user->id
));
4130 // Brute force unenrol from all courses.
4131 $DB->delete_records('user_enrolments', array('userid' => $user->id
));
4133 // Purge user preferences.
4134 $DB->delete_records('user_preferences', array('userid' => $user->id
));
4136 // Purge user extra profile info.
4137 $DB->delete_records('user_info_data', array('userid' => $user->id
));
4139 // Purge log of previous password hashes.
4140 $DB->delete_records('user_password_history', array('userid' => $user->id
));
4142 // Last course access not necessary either.
4143 $DB->delete_records('user_lastaccess', array('userid' => $user->id
));
4144 // Remove all user tokens.
4145 $DB->delete_records('external_tokens', array('userid' => $user->id
));
4147 // Unauthorise the user for all services.
4148 $DB->delete_records('external_services_users', array('userid' => $user->id
));
4150 // Remove users private keys.
4151 $DB->delete_records('user_private_key', array('userid' => $user->id
));
4153 // Remove users customised pages.
4154 $DB->delete_records('my_pages', array('userid' => $user->id
, 'private' => 1));
4156 // Remove user's oauth2 refresh tokens, if present.
4157 $DB->delete_records('oauth2_refresh_token', array('userid' => $user->id
));
4159 // Delete user from $SESSION->bulk_users.
4160 if (isset($SESSION->bulk_users
[$user->id
])) {
4161 unset($SESSION->bulk_users
[$user->id
]);
4164 // Force logout - may fail if file based sessions used, sorry.
4165 \core\session\manager
::kill_user_sessions($user->id
);
4167 // Generate username from email address, or a fake email.
4168 $delemail = !empty($user->email
) ?
$user->email
: $user->username
. '.' . $user->id
. '@unknownemail.invalid';
4171 $deltimelength = core_text
::strlen((string) $deltime);
4173 // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
4174 $delname = clean_param($delemail, PARAM_USERNAME
);
4175 $delname = core_text
::substr($delname, 0, 100 - ($deltimelength +
1)) . ".{$deltime}";
4177 // Workaround for bulk deletes of users with the same email address.
4178 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4182 // Mark internal user record as "deleted".
4183 $updateuser = new stdClass();
4184 $updateuser->id
= $user->id
;
4185 $updateuser->deleted
= 1;
4186 $updateuser->username
= $delname; // Remember it just in case.
4187 $updateuser->email
= md5($user->username
);// Store hash of username, useful importing/restoring users.
4188 $updateuser->idnumber
= ''; // Clear this field to free it up.
4189 $updateuser->picture
= 0;
4190 $updateuser->timemodified
= $deltime;
4192 // Don't trigger update event, as user is being deleted.
4193 user_update_user($updateuser, false, false);
4195 // Delete all content associated with the user context, but not the context itself.
4196 $usercontext->delete_content();
4198 // Delete any search data.
4199 \core_search\manager
::context_deleted($usercontext);
4201 // Any plugin that needs to cleanup should register this event.
4203 $event = \core\event\user_deleted
::create(
4205 'objectid' => $user->id
,
4206 'relateduserid' => $user->id
,
4207 'context' => $usercontext,
4209 'username' => $user->username
,
4210 'email' => $user->email
,
4211 'idnumber' => $user->idnumber
,
4212 'picture' => $user->picture
,
4213 'mnethostid' => $user->mnethostid
4217 $event->add_record_snapshot('user', $olduser);
4220 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4221 // should know about this updated property persisted to the user's table.
4222 $user->timemodified
= $updateuser->timemodified
;
4224 // Notify auth plugin - do not block the delete even when plugin fails.
4225 $authplugin = get_auth_plugin($user->auth
);
4226 $authplugin->user_delete($user);
4232 * Retrieve the guest user object.
4234 * @return stdClass A {@link $USER} object
4236 function guest_user() {
4239 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest
))) {
4240 $newuser->confirmed
= 1;
4241 $newuser->lang
= get_newuser_language();
4242 $newuser->lastip
= getremoteaddr();
4249 * Authenticates a user against the chosen authentication mechanism
4251 * Given a username and password, this function looks them
4252 * up using the currently selected authentication mechanism,
4253 * and if the authentication is successful, it returns a
4254 * valid $user object from the 'user' table.
4256 * Uses auth_ functions from the currently active auth module
4258 * After authenticate_user_login() returns success, you will need to
4259 * log that the user has logged in, and call complete_user_login() to set
4262 * Note: this function works only with non-mnet accounts!
4264 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4265 * @param string $password User's password
4266 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4267 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4268 * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4269 * @return stdClass|false A {@link $USER} object or false if error
4271 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4272 global $CFG, $DB, $PAGE;
4273 require_once("$CFG->libdir/authlib.php");
4275 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id
)) {
4276 // we have found the user
4278 } else if (!empty($CFG->authloginviaemail
)) {
4279 if ($email = clean_param($username, PARAM_EMAIL
)) {
4280 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4281 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'email' => $email);
4282 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4283 if (count($users) === 1) {
4284 // Use email for login only if unique.
4285 $user = reset($users);
4286 $user = get_complete_user_data('id', $user->id
);
4287 $username = $user->username
;
4293 // Make sure this request came from the login form.
4294 if (!\core\session\manager
::validate_login_token($logintoken)) {
4295 $failurereason = AUTH_LOGIN_FAILED
;
4297 // Trigger login failed event (specifying the ID of the found user, if available).
4298 \core\event\user_login_failed
::create([
4299 'userid' => ($user->id ??
0),
4301 'username' => $username,
4302 'reason' => $failurereason,
4306 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4310 $authsenabled = get_enabled_auth_plugins();
4313 // Use manual if auth not set.
4314 $auth = empty($user->auth
) ?
'manual' : $user->auth
;
4316 if (in_array($user->auth
, $authsenabled)) {
4317 $authplugin = get_auth_plugin($user->auth
);
4318 $authplugin->pre_user_login_hook($user);
4321 if (!empty($user->suspended
)) {
4322 $failurereason = AUTH_LOGIN_SUSPENDED
;
4324 // Trigger login failed event.
4325 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4326 'other' => array('username' => $username, 'reason' => $failurereason)));
4328 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4331 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4332 // Legacy way to suspend user.
4333 $failurereason = AUTH_LOGIN_SUSPENDED
;
4335 // Trigger login failed event.
4336 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4337 'other' => array('username' => $username, 'reason' => $failurereason)));
4339 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4342 $auths = array($auth);
4345 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4346 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'deleted' => 1))) {
4347 $failurereason = AUTH_LOGIN_NOUSER
;
4349 // Trigger login failed event.
4350 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4351 'reason' => $failurereason)));
4353 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4357 // User does not exist.
4358 $auths = $authsenabled;
4359 $user = new stdClass();
4363 if ($ignorelockout) {
4364 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4365 // or this function is called from a SSO script.
4366 } else if ($user->id
) {
4367 // Verify login lockout after other ways that may prevent user login.
4368 if (login_is_lockedout($user)) {
4369 $failurereason = AUTH_LOGIN_LOCKOUT
;
4371 // Trigger login failed event.
4372 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4373 'other' => array('username' => $username, 'reason' => $failurereason)));
4376 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4380 // We can not lockout non-existing accounts.
4383 foreach ($auths as $auth) {
4384 $authplugin = get_auth_plugin($auth);
4386 // On auth fail fall through to the next plugin.
4387 if (!$authplugin->user_login($username, $password)) {
4391 // Before performing login actions, check if user still passes password policy, if admin setting is enabled.
4392 if (!empty($CFG->passwordpolicycheckonlogin
)) {
4394 $passed = check_password_policy($password, $errmsg, $user);
4396 // First trigger event for failure.
4397 $failedevent = \core\event\user_password_policy_failed
::create_from_user($user);
4398 $failedevent->trigger();
4400 // If able to change password, set flag and move on.
4401 if ($authplugin->can_change_password()) {
4402 // Check if we are on internal change password page, or service is external, don't show notification.
4403 $internalchangeurl = new moodle_url('/login/change_password.php');
4404 if (!($PAGE->has_set_url() && $internalchangeurl->compare($PAGE->url
)) && $authplugin->is_internal()) {
4405 \core\notification
::error(get_string('passwordpolicynomatch', '', $errmsg));
4407 set_user_preference('auth_forcepasswordchange', 1, $user);
4408 } else if ($authplugin->can_reset_password()) {
4409 // Else force a reset if possible.
4410 \core\notification
::error(get_string('forcepasswordresetnotice', '', $errmsg));
4411 redirect(new moodle_url('/login/forgot_password.php'));
4413 $notifymsg = get_string('forcepasswordresetfailurenotice', '', $errmsg);
4414 // If support page is set, add link for help.
4415 if (!empty($CFG->supportpage
)) {
4416 $link = \html_writer
::link($CFG->supportpage
, $CFG->supportpage
);
4417 $link = \html_writer
::tag('p', $link);
4418 $notifymsg .= $link;
4421 // If no change or reset is possible, add a notification for user.
4422 \core\notification
::error($notifymsg);
4427 // Successful authentication.
4429 // User already exists in database.
4430 if (empty($user->auth
)) {
4431 // For some reason auth isn't set yet.
4432 $DB->set_field('user', 'auth', $auth, array('id' => $user->id
));
4433 $user->auth
= $auth;
4436 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4437 // the current hash algorithm while we have access to the user's password.
4438 update_internal_user_password($user, $password);
4440 if ($authplugin->is_synchronised_with_external()) {
4441 // Update user record from external DB.
4442 $user = update_user_record_by_id($user->id
);
4445 // The user is authenticated but user creation may be disabled.
4446 if (!empty($CFG->authpreventaccountcreation
)) {
4447 $failurereason = AUTH_LOGIN_UNAUTHORISED
;
4449 // Trigger login failed event.
4450 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4451 'reason' => $failurereason)));
4454 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4455 $_SERVER['HTTP_USER_AGENT']);
4458 $user = create_user_record($username, $password, $auth);
4462 $authplugin->sync_roles($user);
4464 foreach ($authsenabled as $hau) {
4465 $hauth = get_auth_plugin($hau);
4466 $hauth->user_authenticated_hook($user, $username, $password);
4469 if (empty($user->id
)) {
4470 $failurereason = AUTH_LOGIN_NOUSER
;
4471 // Trigger login failed event.
4472 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4473 'reason' => $failurereason)));
4478 if (!empty($user->suspended
)) {
4479 // Just in case some auth plugin suspended account.
4480 $failurereason = AUTH_LOGIN_SUSPENDED
;
4481 // Trigger login failed event.
4482 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4483 'other' => array('username' => $username, 'reason' => $failurereason)));
4485 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4489 login_attempt_valid($user);
4490 $failurereason = AUTH_LOGIN_OK
;
4494 // Failed if all the plugins have failed.
4495 if (debugging('', DEBUG_ALL
)) {
4496 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4500 login_attempt_failed($user);
4501 $failurereason = AUTH_LOGIN_FAILED
;
4502 // Trigger login failed event.
4503 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4504 'other' => array('username' => $username, 'reason' => $failurereason)));
4507 $failurereason = AUTH_LOGIN_NOUSER
;
4508 // Trigger login failed event.
4509 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4510 'reason' => $failurereason)));
4518 * Call to complete the user login process after authenticate_user_login()
4519 * has succeeded. It will setup the $USER variable and other required bits
4523 * - It will NOT log anything -- up to the caller to decide what to log.
4524 * - this function does not set any cookies any more!
4526 * @param stdClass $user
4527 * @return stdClass A {@link $USER} object - BC only, do not use
4529 function complete_user_login($user) {
4530 global $CFG, $DB, $USER, $SESSION;
4532 \core\session\manager
::login_user($user);
4534 // Reload preferences from DB.
4535 unset($USER->preference
);
4536 check_user_preferences_loaded($USER);
4538 // Update login times.
4539 update_user_login_times();
4541 // Extra session prefs init.
4542 set_login_session_preferences();
4544 // Trigger login event.
4545 $event = \core\event\user_loggedin
::create(
4547 'userid' => $USER->id
,
4548 'objectid' => $USER->id
,
4549 'other' => array('username' => $USER->username
),
4554 // Queue migrating the messaging data, if we need to.
4555 if (!get_user_preferences('core_message_migrate_data', false, $USER->id
)) {
4556 // Check if there are any legacy messages to migrate.
4557 if (\core_message\helper
::legacy_messages_exist($USER->id
)) {
4558 \core_message\task\migrate_message_data
::queue_task($USER->id
);
4560 set_user_preference('core_message_migrate_data', true, $USER->id
);
4564 if (isguestuser()) {
4565 // No need to continue when user is THE guest.
4570 // We can redirect to password change URL only in browser.
4574 // Select password change url.
4575 $userauth = get_auth_plugin($USER->auth
);
4577 // Check whether the user should be changing password.
4578 if (get_user_preferences('auth_forcepasswordchange', false)) {
4579 if ($userauth->can_change_password()) {
4580 if ($changeurl = $userauth->change_password_url()) {
4581 redirect($changeurl);
4583 require_once($CFG->dirroot
. '/login/lib.php');
4584 $SESSION->wantsurl
= core_login_get_return_url();
4585 redirect($CFG->wwwroot
.'/login/change_password.php');
4588 print_error('nopasswordchangeforced', 'auth');
4595 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4597 * @param string $password String to check.
4598 * @return boolean True if the $password matches the format of an md5 sum.
4600 function password_is_legacy_hash($password) {
4601 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4605 * Compare password against hash stored in user object to determine if it is valid.
4607 * If necessary it also updates the stored hash to the current format.
4609 * @param stdClass $user (Password property may be updated).
4610 * @param string $password Plain text password.
4611 * @return bool True if password is valid.
4613 function validate_internal_user_password($user, $password) {
4616 if ($user->password
=== AUTH_PASSWORD_NOT_CACHED
) {
4617 // Internal password is not used at all, it can not validate.
4621 // If hash isn't a legacy (md5) hash, validate using the library function.
4622 if (!password_is_legacy_hash($user->password
)) {
4623 return password_verify($password, $user->password
);
4626 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4627 // is valid we can then update it to the new algorithm.
4629 $sitesalt = isset($CFG->passwordsaltmain
) ?
$CFG->passwordsaltmain
: '';
4632 if ($user->password
=== md5($password.$sitesalt)
4633 or $user->password
=== md5($password)
4634 or $user->password
=== md5(addslashes($password).$sitesalt)
4635 or $user->password
=== md5(addslashes($password))) {
4636 // Note: we are intentionally using the addslashes() here because we
4637 // need to accept old password hashes of passwords with magic quotes.
4641 for ($i=1; $i<=20; $i++
) { // 20 alternative salts should be enough, right?
4642 $alt = 'passwordsaltalt'.$i;
4643 if (!empty($CFG->$alt)) {
4644 if ($user->password
=== md5($password.$CFG->$alt) or $user->password
=== md5(addslashes($password).$CFG->$alt)) {
4653 // If the password matches the existing md5 hash, update to the
4654 // current hash algorithm while we have access to the user's password.
4655 update_internal_user_password($user, $password);
4662 * Calculate hash for a plain text password.
4664 * @param string $password Plain text password to be hashed.
4665 * @param bool $fasthash If true, use a low cost factor when generating the hash
4666 * This is much faster to generate but makes the hash
4667 * less secure. It is used when lots of hashes need to
4668 * be generated quickly.
4669 * @return string The hashed password.
4671 * @throws moodle_exception If a problem occurs while generating the hash.
4673 function hash_internal_user_password($password, $fasthash = false) {
4676 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4677 $options = ($fasthash) ?
array('cost' => 4) : array();
4679 $generatedhash = password_hash($password, PASSWORD_DEFAULT
, $options);
4681 if ($generatedhash === false ||
$generatedhash === null) {
4682 throw new moodle_exception('Failed to generate password hash.');
4685 return $generatedhash;
4689 * Update password hash in user object (if necessary).
4691 * The password is updated if:
4692 * 1. The password has changed (the hash of $user->password is different
4693 * to the hash of $password).
4694 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4697 * Updating the password will modify the $user object and the database
4698 * record to use the current hashing algorithm.
4699 * It will remove Web Services user tokens too.
4701 * @param stdClass $user User object (password property may be updated).
4702 * @param string $password Plain text password.
4703 * @param bool $fasthash If true, use a low cost factor when generating the hash
4704 * This is much faster to generate but makes the hash
4705 * less secure. It is used when lots of hashes need to
4706 * be generated quickly.
4707 * @return bool Always returns true.
4709 function update_internal_user_password($user, $password, $fasthash = false) {
4712 // Figure out what the hashed password should be.
4713 if (!isset($user->auth
)) {
4714 debugging('User record in update_internal_user_password() must include field auth',
4716 $user->auth
= $DB->get_field('user', 'auth', array('id' => $user->id
));
4718 $authplugin = get_auth_plugin($user->auth
);
4719 if ($authplugin->prevent_local_passwords()) {
4720 $hashedpassword = AUTH_PASSWORD_NOT_CACHED
;
4722 $hashedpassword = hash_internal_user_password($password, $fasthash);
4725 $algorithmchanged = false;
4727 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED
) {
4728 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4729 $passwordchanged = ($user->password
!== $hashedpassword);
4731 } else if (isset($user->password
)) {
4732 // If verification fails then it means the password has changed.
4733 $passwordchanged = !password_verify($password, $user->password
);
4734 $algorithmchanged = password_needs_rehash($user->password
, PASSWORD_DEFAULT
);
4736 // While creating new user, password in unset in $user object, to avoid
4737 // saving it with user_create()
4738 $passwordchanged = true;
4741 if ($passwordchanged ||
$algorithmchanged) {
4742 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id
));
4743 $user->password
= $hashedpassword;
4746 $user = $DB->get_record('user', array('id' => $user->id
));
4747 \core\event\user_password_updated
::create_from_user($user)->trigger();
4749 // Remove WS user tokens.
4750 if (!empty($CFG->passwordchangetokendeletion
)) {
4751 require_once($CFG->dirroot
.'/webservice/lib.php');
4752 webservice
::delete_user_ws_tokens($user->id
);
4760 * Get a complete user record, which includes all the info in the user record.
4762 * Intended for setting as $USER session variable
4764 * @param string $field The user field to be checked for a given value.
4765 * @param string $value The value to match for $field.
4766 * @param int $mnethostid
4767 * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4768 * found. Otherwise, it will just return false.
4769 * @return mixed False, or A {@link $USER} object.
4771 function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4774 if (!$field ||
!$value) {
4778 // Change the field to lowercase.
4779 $field = core_text
::strtolower($field);
4781 // List of case insensitive fields.
4782 $caseinsensitivefields = ['email'];
4784 // Username input is forced to lowercase and should be case sensitive.
4785 if ($field == 'username') {
4786 $value = core_text
::strtolower($value);
4789 // Build the WHERE clause for an SQL query.
4790 $params = array('fieldval' => $value);
4792 // Do a case-insensitive query, if necessary. These are generally very expensive. The performance can be improved on some DBs
4793 // such as MySQL by pre-filtering users with accent-insensitive subselect.
4794 if (in_array($field, $caseinsensitivefields)) {
4795 $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4796 $idsubselect = $DB->sql_equal($field, ':fieldval2', false, false);
4797 $params['fieldval2'] = $value;
4799 $fieldselect = "$field = :fieldval";
4802 $constraints = "$fieldselect AND deleted <> 1";
4804 // If we are loading user data based on anything other than id,
4805 // we must also restrict our search based on mnet host.
4806 if ($field != 'id') {
4807 if (empty($mnethostid)) {
4808 // If empty, we restrict to local users.
4809 $mnethostid = $CFG->mnet_localhost_id
;
4812 if (!empty($mnethostid)) {
4813 $params['mnethostid'] = $mnethostid;
4814 $constraints .= " AND mnethostid = :mnethostid";
4818 $constraints .= " AND id IN (SELECT id FROM {user} WHERE {$idsubselect})";
4821 // Get all the basic user data.
4823 // Make sure that there's only a single record that matches our query.
4824 // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4825 // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4826 $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST
);
4827 } catch (dml_exception
$exception) {
4828 if ($throwexception) {
4831 // Return false when no records or multiple records were found.
4836 // Get various settings and preferences.
4838 // Preload preference cache.
4839 check_user_preferences_loaded($user);
4841 // Load course enrolment related stuff.
4842 $user->lastcourseaccess
= array(); // During last session.
4843 $user->currentcourseaccess
= array(); // During current session.
4844 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id
))) {
4845 foreach ($lastaccesses as $lastaccess) {
4846 $user->lastcourseaccess
[$lastaccess->courseid
] = $lastaccess->timeaccess
;
4850 $sql = "SELECT g.id, g.courseid
4851 FROM {groups} g, {groups_members} gm
4852 WHERE gm.groupid=g.id AND gm.userid=?";
4854 // This is a special hack to speedup calendar display.
4855 $user->groupmember
= array();
4856 if (!isguestuser($user)) {
4857 if ($groups = $DB->get_records_sql($sql, array($user->id
))) {
4858 foreach ($groups as $group) {
4859 if (!array_key_exists($group->courseid
, $user->groupmember
)) {
4860 $user->groupmember
[$group->courseid
] = array();
4862 $user->groupmember
[$group->courseid
][$group->id
] = $group->id
;
4867 // Add cohort theme.
4868 if (!empty($CFG->allowcohortthemes
)) {
4869 require_once($CFG->dirroot
. '/cohort/lib.php');
4870 if ($cohorttheme = cohort_get_user_cohort_theme($user->id
)) {
4871 $user->cohorttheme
= $cohorttheme;
4875 // Add the custom profile fields to the user record.
4876 $user->profile
= array();
4877 if (!isguestuser($user)) {
4878 require_once($CFG->dirroot
.'/user/profile/lib.php');
4879 profile_load_custom_fields($user);
4882 // Rewrite some variables if necessary.
4883 if (!empty($user->description
)) {
4884 // No need to cart all of it around.
4885 $user->description
= true;
4887 if (isguestuser($user)) {
4888 // Guest language always same as site.
4889 $user->lang
= get_newuser_language();
4890 // Name always in current language.
4891 $user->firstname
= get_string('guestuser');
4892 $user->lastname
= ' ';
4899 * Validate a password against the configured password policy
4901 * @param string $password the password to be checked against the password policy
4902 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4903 * @param stdClass $user the user object to perform password validation against. Defaults to null if not provided.
4905 * @return bool true if the password is valid according to the policy. false otherwise.
4907 function check_password_policy($password, &$errmsg, $user = null) {
4910 if (!empty($CFG->passwordpolicy
)) {
4912 if (core_text
::strlen($password) < $CFG->minpasswordlength
) {
4913 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength
) .'</div>';
4915 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits
) {
4916 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits
) .'</div>';
4918 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower
) {
4919 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower
) .'</div>';
4921 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper
) {
4922 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper
) .'</div>';
4924 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum
) {
4925 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
) .'</div>';
4927 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars
)) {
4928 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars
) .'</div>';
4931 // Fire any additional password policy functions from plugins.
4932 // Plugin functions should output an error message string or empty string for success.
4933 $pluginsfunction = get_plugins_with_function('check_password_policy');
4934 foreach ($pluginsfunction as $plugintype => $plugins) {
4935 foreach ($plugins as $pluginfunction) {
4936 $pluginerr = $pluginfunction($password, $user);
4938 $errmsg .= '<div>'. $pluginerr .'</div>';
4944 if ($errmsg == '') {
4953 * When logging in, this function is run to set certain preferences for the current SESSION.
4955 function set_login_session_preferences() {
4958 $SESSION->justloggedin
= true;
4960 unset($SESSION->lang
);
4961 unset($SESSION->forcelang
);
4962 unset($SESSION->load_navigation_admin
);
4967 * Delete a course, including all related data from the database, and any associated files.
4969 * @param mixed $courseorid The id of the course or course object to delete.
4970 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4971 * @return bool true if all the removals succeeded. false if there were any failures. If this
4972 * method returns false, some of the removals will probably have succeeded, and others
4973 * failed, but you have no way of knowing which.
4975 function delete_course($courseorid, $showfeedback = true) {
4978 if (is_object($courseorid)) {
4979 $courseid = $courseorid->id
;
4980 $course = $courseorid;
4982 $courseid = $courseorid;
4983 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4987 $context = context_course
::instance($courseid);
4989 // Frontpage course can not be deleted!!
4990 if ($courseid == SITEID
) {
4994 // Allow plugins to use this course before we completely delete it.
4995 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
4996 foreach ($pluginsfunction as $plugintype => $plugins) {
4997 foreach ($plugins as $pluginfunction) {
4998 $pluginfunction($course);
5003 // Tell the search manager we are about to delete a course. This prevents us sending updates
5004 // for each individual context being deleted.
5005 \core_search\manager
::course_deleting_start($courseid);
5007 $handler = core_course\customfield\course_handler
::create();
5008 $handler->delete_instance($courseid);
5010 // Make the course completely empty.
5011 remove_course_contents($courseid, $showfeedback);
5013 // Delete the course and related context instance.
5014 context_helper
::delete_instance(CONTEXT_COURSE
, $courseid);
5016 $DB->delete_records("course", array("id" => $courseid));
5017 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5019 // Reset all course related caches here.
5020 if (class_exists('format_base', false)) {
5021 format_base
::reset_course_cache($courseid);
5024 // Tell search that we have deleted the course so it can delete course data from the index.
5025 \core_search\manager
::course_deleting_finish($courseid);
5027 // Trigger a course deleted event.
5028 $event = \core\event\course_deleted
::create(array(
5029 'objectid' => $course->id
,
5030 'context' => $context,
5032 'shortname' => $course->shortname
,
5033 'fullname' => $course->fullname
,
5034 'idnumber' => $course->idnumber
5037 $event->add_record_snapshot('course', $course);
5044 * Clear a course out completely, deleting all content but don't delete the course itself.
5046 * This function does not verify any permissions.
5048 * Please note this function also deletes all user enrolments,
5049 * enrolment instances and role assignments by default.
5052 * - 'keep_roles_and_enrolments' - false by default
5053 * - 'keep_groups_and_groupings' - false by default
5055 * @param int $courseid The id of the course that is being deleted
5056 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5057 * @param array $options extra options
5058 * @return bool true if all the removals succeeded. false if there were any failures. If this
5059 * method returns false, some of the removals will probably have succeeded, and others
5060 * failed, but you have no way of knowing which.
5062 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5063 global $CFG, $DB, $OUTPUT;
5065 require_once($CFG->libdir
.'/badgeslib.php');
5066 require_once($CFG->libdir
.'/completionlib.php');
5067 require_once($CFG->libdir
.'/questionlib.php');
5068 require_once($CFG->libdir
.'/gradelib.php');
5069 require_once($CFG->dirroot
.'/group/lib.php');
5070 require_once($CFG->dirroot
.'/comment/lib.php');
5071 require_once($CFG->dirroot
.'/rating/lib.php');
5072 require_once($CFG->dirroot
.'/notes/lib.php');
5074 // Handle course badges.
5075 badges_handle_course_deletion($courseid);
5077 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5078 $strdeleted = get_string('deleted').' - ';
5080 // Some crazy wishlist of stuff we should skip during purging of course content.
5081 $options = (array)$options;
5083 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST
);
5084 $coursecontext = context_course
::instance($courseid);
5085 $fs = get_file_storage();
5087 // Delete course completion information, this has to be done before grades and enrols.
5088 $cc = new completion_info($course);
5089 $cc->clear_criteria();
5090 if ($showfeedback) {
5091 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5094 // Remove all data from gradebook - this needs to be done before course modules
5095 // because while deleting this information, the system may need to reference
5096 // the course modules that own the grades.
5097 remove_course_grades($courseid, $showfeedback);
5098 remove_grade_letters($coursecontext, $showfeedback);
5100 // Delete course blocks in any all child contexts,
5101 // they may depend on modules so delete them first.
5102 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5103 foreach ($childcontexts as $childcontext) {
5104 blocks_delete_all_for_context($childcontext->id
);
5106 unset($childcontexts);
5107 blocks_delete_all_for_context($coursecontext->id
);
5108 if ($showfeedback) {
5109 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5112 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $courseid]);
5113 rebuild_course_cache($courseid, true);
5115 // Get the list of all modules that are properly installed.
5116 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5118 // Delete every instance of every module,
5119 // this has to be done before deleting of course level stuff.
5120 $locations = core_component
::get_plugin_list('mod');
5121 foreach ($locations as $modname => $moddir) {
5122 if ($modname === 'NEWMODULE') {
5125 if (array_key_exists($modname, $allmodules)) {
5126 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5127 FROM {".$modname."} m
5128 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5129 WHERE m.course = :courseid";
5130 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id
,
5131 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5133 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5134 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5137 foreach ($instances as $cm) {
5139 // Delete activity context questions and question categories.
5140 question_delete_activity($cm);
5141 // Notify the competency subsystem.
5142 \core_competency\api
::hook_course_module_deleted($cm);
5144 if (function_exists($moddelete)) {
5145 // This purges all module data in related tables, extra user prefs, settings, etc.
5146 $moddelete($cm->modinstance
);
5148 // NOTE: we should not allow installation of modules with missing delete support!
5149 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5150 $DB->delete_records($modname, array('id' => $cm->modinstance
));
5154 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5155 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
5156 $DB->delete_records('course_modules_completion', ['coursemoduleid' => $cm->id
]);
5157 $DB->delete_records('course_modules', array('id' => $cm->id
));
5158 rebuild_course_cache($cm->course
, true);
5162 if ($instances and $showfeedback) {
5163 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5166 // Ooops, this module is not properly installed, force-delete it in the next block.
5170 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5172 // Delete completion defaults.
5173 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5175 // Remove all data from availability and completion tables that is associated
5176 // with course-modules belonging to this course. Note this is done even if the
5177 // features are not enabled now, in case they were enabled previously.
5178 $DB->delete_records_subquery('course_modules_completion', 'coursemoduleid', 'id',
5179 'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
5181 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5182 $cms = $DB->get_records('course_modules', array('course' => $course->id
));
5183 $allmodulesbyid = array_flip($allmodules);
5184 foreach ($cms as $cm) {
5185 if (array_key_exists($cm->module
, $allmodulesbyid)) {
5187 $DB->delete_records($allmodulesbyid[$cm->module
], array('id' => $cm->instance
));
5188 } catch (Exception
$e) {
5189 // Ignore weird or missing table problems.
5192 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
5193 $DB->delete_records('course_modules', array('id' => $cm->id
));
5194 rebuild_course_cache($cm->course
, true);
5197 if ($showfeedback) {
5198 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5201 // Delete questions and question categories.
5202 question_delete_course($course);
5203 if ($showfeedback) {
5204 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5207 // Delete content bank contents.
5208 $cb = new \core_contentbank\
contentbank();
5209 $cbdeleted = $cb->delete_contents($coursecontext);
5210 if ($showfeedback && $cbdeleted) {
5211 echo $OUTPUT->notification($strdeleted.get_string('contentbank', 'contentbank'), 'notifysuccess');
5214 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5215 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5216 foreach ($childcontexts as $childcontext) {
5217 $childcontext->delete();
5219 unset($childcontexts);
5221 // Remove roles and enrolments by default.
5222 if (empty($options['keep_roles_and_enrolments'])) {
5223 // This hack is used in restore when deleting contents of existing course.
5224 // During restore, we should remove only enrolment related data that the user performing the restore has a
5225 // permission to remove.
5226 $userid = $options['userid'] ??
null;
5227 enrol_course_delete($course, $userid);
5228 role_unassign_all(array('contextid' => $coursecontext->id
, 'component' => ''), true);
5229 if ($showfeedback) {
5230 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5234 // Delete any groups, removing members and grouping/course links first.
5235 if (empty($options['keep_groups_and_groupings'])) {
5236 groups_delete_groupings($course->id
, $showfeedback);
5237 groups_delete_groups($course->id
, $showfeedback);
5241 filter_delete_all_for_context($coursecontext->id
);
5243 // Notes, you shall not pass!
5244 note_delete_all($course->id
);
5247 comment
::delete_comments($coursecontext->id
);
5249 // Ratings are history too.
5250 $delopt = new stdclass();
5251 $delopt->contextid
= $coursecontext->id
;
5252 $rm = new rating_manager();
5253 $rm->delete_ratings($delopt);
5255 // Delete course tags.
5256 core_tag_tag
::remove_all_item_tags('core', 'course', $course->id
);
5258 // Notify the competency subsystem.
5259 \core_competency\api
::hook_course_deleted($course);
5261 // Delete calendar events.
5262 $DB->delete_records('event', array('courseid' => $course->id
));
5263 $fs->delete_area_files($coursecontext->id
, 'calendar');
5265 // Delete all related records in other core tables that may have a courseid
5266 // This array stores the tables that need to be cleared, as
5267 // table_name => column_name that contains the course id.
5268 $tablestoclear = array(
5269 'backup_courses' => 'courseid', // Scheduled backup stuff.
5270 'user_lastaccess' => 'courseid', // User access info.
5272 foreach ($tablestoclear as $table => $col) {
5273 $DB->delete_records($table, array($col => $course->id
));
5276 // Delete all course backup files.
5277 $fs->delete_area_files($coursecontext->id
, 'backup');
5279 // Cleanup course record - remove links to deleted stuff.
5280 $oldcourse = new stdClass();
5281 $oldcourse->id
= $course->id
;
5282 $oldcourse->summary
= '';
5283 $oldcourse->cacherev
= 0;
5284 $oldcourse->legacyfiles
= 0;
5285 if (!empty($options['keep_groups_and_groupings'])) {
5286 $oldcourse->defaultgroupingid
= 0;
5288 $DB->update_record('course', $oldcourse);
5290 // Delete course sections.
5291 $DB->delete_records('course_sections', array('course' => $course->id
));
5293 // Delete legacy, section and any other course files.
5294 $fs->delete_area_files($coursecontext->id
, 'course'); // Files from summary and section.
5296 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5297 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5298 // Easy, do not delete the context itself...
5299 $coursecontext->delete_content();
5302 // We can not drop all context stuff because it would bork enrolments and roles,
5303 // there might be also files used by enrol plugins...
5306 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5307 // also some non-standard unsupported plugins may try to store something there.
5308 fulldelete($CFG->dataroot
.'/'.$course->id
);
5310 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5311 $cachemodinfo = cache
::make('core', 'coursemodinfo');
5312 $cachemodinfo->delete($courseid);
5314 // Trigger a course content deleted event.
5315 $event = \core\event\course_content_deleted
::create(array(
5316 'objectid' => $course->id
,
5317 'context' => $coursecontext,
5318 'other' => array('shortname' => $course->shortname
,
5319 'fullname' => $course->fullname
,
5320 'options' => $options) // Passing this for legacy reasons.
5322 $event->add_record_snapshot('course', $course);
5329 * Change dates in module - used from course reset.
5331 * @param string $modname forum, assignment, etc
5332 * @param array $fields array of date fields from mod table
5333 * @param int $timeshift time difference
5334 * @param int $courseid
5335 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5336 * @return bool success
5338 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5340 include_once($CFG->dirroot
.'/mod/'.$modname.'/lib.php');
5343 $params = array($timeshift, $courseid);
5344 foreach ($fields as $field) {
5345 $updatesql = "UPDATE {".$modname."}
5346 SET $field = $field + ?
5347 WHERE course=? AND $field<>0";
5349 $updatesql .= ' AND id=?';
5352 $return = $DB->execute($updatesql, $params) && $return;
5359 * This function will empty a course of user data.
5360 * It will retain the activities and the structure of the course.
5362 * @param object $data an object containing all the settings including courseid (without magic quotes)
5363 * @return array status array of array component, item, error
5365 function reset_course_userdata($data) {
5367 require_once($CFG->libdir
.'/gradelib.php');
5368 require_once($CFG->libdir
.'/completionlib.php');
5369 require_once($CFG->dirroot
.'/completion/criteria/completion_criteria_date.php');
5370 require_once($CFG->dirroot
.'/group/lib.php');
5372 $data->courseid
= $data->id
;
5373 $context = context_course
::instance($data->courseid
);
5375 $eventparams = array(
5376 'context' => $context,
5377 'courseid' => $data->id
,
5379 'reset_options' => (array) $data
5382 $event = \core\event\course_reset_started
::create($eventparams);
5385 // Calculate the time shift of dates.
5386 if (!empty($data->reset_start_date
)) {
5387 // Time part of course startdate should be zero.
5388 $data->timeshift
= $data->reset_start_date
- usergetmidnight($data->reset_start_date_old
);
5390 $data->timeshift
= 0;
5393 // Result array: component, item, error.
5396 // Start the resetting.
5397 $componentstr = get_string('general');
5399 // Move the course start time.
5400 if (!empty($data->reset_start_date
) and $data->timeshift
) {
5401 // Change course start data.
5402 $DB->set_field('course', 'startdate', $data->reset_start_date
, array('id' => $data->courseid
));
5403 // Update all course and group events - do not move activity events.
5404 $updatesql = "UPDATE {event}
5405 SET timestart = timestart + ?
5406 WHERE courseid=? AND instance=0";
5407 $DB->execute($updatesql, array($data->timeshift
, $data->courseid
));
5409 // Update any date activity restrictions.
5410 if ($CFG->enableavailability
) {
5411 \availability_date\condition
::update_all_dates($data->courseid
, $data->timeshift
);
5414 // Update completion expected dates.
5415 if ($CFG->enablecompletion
) {
5416 $modinfo = get_fast_modinfo($data->courseid
);
5418 foreach ($modinfo->get_cms() as $cm) {
5419 if ($cm->completion
&& !empty($cm->completionexpected
)) {
5420 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected +
$data->timeshift
,
5421 array('id' => $cm->id
));
5426 // Clear course cache if changes made.
5428 rebuild_course_cache($data->courseid
, true);
5431 // Update course date completion criteria.
5432 \completion_criteria_date
::update_date($data->courseid
, $data->timeshift
);
5435 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5438 if (!empty($data->reset_end_date
)) {
5439 // If the user set a end date value respect it.
5440 $DB->set_field('course', 'enddate', $data->reset_end_date
, array('id' => $data->courseid
));
5441 } else if ($data->timeshift
> 0 && $data->reset_end_date_old
) {
5442 // If there is a time shift apply it to the end date as well.
5443 $enddate = $data->reset_end_date_old +
$data->timeshift
;
5444 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid
));
5447 if (!empty($data->reset_events
)) {
5448 $DB->delete_records('event', array('courseid' => $data->courseid
));
5449 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5452 if (!empty($data->reset_notes
)) {
5453 require_once($CFG->dirroot
.'/notes/lib.php');
5454 note_delete_all($data->courseid
);
5455 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5458 if (!empty($data->delete_blog_associations
)) {
5459 require_once($CFG->dirroot
.'/blog/lib.php');
5460 blog_remove_associations_for_course($data->courseid
);
5461 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5464 if (!empty($data->reset_completion
)) {
5465 // Delete course and activity completion information.
5466 $course = $DB->get_record('course', array('id' => $data->courseid
));
5467 $cc = new completion_info($course);
5468 $cc->delete_all_completion_data();
5469 $status[] = array('component' => $componentstr,
5470 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5473 if (!empty($data->reset_competency_ratings
)) {
5474 \core_competency\api
::hook_course_reset_competency_ratings($data->courseid
);
5475 $status[] = array('component' => $componentstr,
5476 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5479 $componentstr = get_string('roles');
5481 if (!empty($data->reset_roles_overrides
)) {
5482 $children = $context->get_child_contexts();
5483 foreach ($children as $child) {
5484 $child->delete_capabilities();
5486 $context->delete_capabilities();
5487 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5490 if (!empty($data->reset_roles_local
)) {
5491 $children = $context->get_child_contexts();
5492 foreach ($children as $child) {
5493 role_unassign_all(array('contextid' => $child->id
));
5495 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5498 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5499 $data->unenrolled
= array();
5500 if (!empty($data->unenrol_users
)) {
5501 $plugins = enrol_get_plugins(true);
5502 $instances = enrol_get_instances($data->courseid
, true);
5503 foreach ($instances as $key => $instance) {
5504 if (!isset($plugins[$instance->enrol
])) {
5505 unset($instances[$key]);
5510 $usersroles = enrol_get_course_users_roles($data->courseid
);
5511 foreach ($data->unenrol_users
as $withroleid) {
5514 FROM {user_enrolments} ue
5515 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5516 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5517 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5518 $params = array('courseid' => $data->courseid
, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE
);
5521 // Without any role assigned at course context.
5523 FROM {user_enrolments} ue
5524 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5525 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5526 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5527 WHERE ra.id IS null";
5528 $params = array('courseid' => $data->courseid
, 'courselevel' => CONTEXT_COURSE
);
5531 $rs = $DB->get_recordset_sql($sql, $params);
5532 foreach ($rs as $ue) {
5533 if (!isset($instances[$ue->enrolid
])) {
5536 $instance = $instances[$ue->enrolid
];
5537 $plugin = $plugins[$instance->enrol
];
5538 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5542 if ($withroleid && count($usersroles[$ue->userid
]) > 1) {
5543 // If we don't remove all roles and user has more than one role, just remove this role.
5544 role_unassign($withroleid, $ue->userid
, $context->id
);
5546 unset($usersroles[$ue->userid
][$withroleid]);
5548 // If we remove all roles or user has only one role, unenrol user from course.
5549 $plugin->unenrol_user($instance, $ue->userid
);
5551 $data->unenrolled
[$ue->userid
] = $ue->userid
;
5556 if (!empty($data->unenrolled
)) {
5558 'component' => $componentstr,
5559 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled
).')',
5564 $componentstr = get_string('groups');
5566 // Remove all group members.
5567 if (!empty($data->reset_groups_members
)) {
5568 groups_delete_group_members($data->courseid
);
5569 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5572 // Remove all groups.
5573 if (!empty($data->reset_groups_remove
)) {
5574 groups_delete_groups($data->courseid
, false);
5575 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5578 // Remove all grouping members.
5579 if (!empty($data->reset_groupings_members
)) {
5580 groups_delete_groupings_groups($data->courseid
, false);
5581 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5584 // Remove all groupings.
5585 if (!empty($data->reset_groupings_remove
)) {
5586 groups_delete_groupings($data->courseid
, false);
5587 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5590 // Look in every instance of every module for data to delete.
5591 $unsupportedmods = array();
5592 if ($allmods = $DB->get_records('modules') ) {
5593 foreach ($allmods as $mod) {
5594 $modname = $mod->name
;
5595 $modfile = $CFG->dirroot
.'/mod/'. $modname.'/lib.php';
5596 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5597 if (file_exists($modfile)) {
5598 if (!$DB->count_records($modname, array('course' => $data->courseid
))) {
5599 continue; // Skip mods with no instances.
5601 include_once($modfile);
5602 if (function_exists($moddeleteuserdata)) {
5603 $modstatus = $moddeleteuserdata($data);
5604 if (is_array($modstatus)) {
5605 $status = array_merge($status, $modstatus);
5607 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5610 $unsupportedmods[] = $mod;
5613 debugging('Missing lib.php in '.$modname.' module!');
5615 // Update calendar events for all modules.
5616 course_module_bulk_update_calendar_events($modname, $data->courseid
);
5620 // Mention unsupported mods.
5621 if (!empty($unsupportedmods)) {
5622 foreach ($unsupportedmods as $mod) {
5624 'component' => get_string('modulenameplural', $mod->name
),
5626 'error' => get_string('resetnotimplemented')
5631 $componentstr = get_string('gradebook', 'grades');
5632 // Reset gradebook,.
5633 if (!empty($data->reset_gradebook_items
)) {
5634 remove_course_grades($data->courseid
, false);
5635 grade_grab_course_grades($data->courseid
);
5636 grade_regrade_final_grades($data->courseid
);
5637 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5639 } else if (!empty($data->reset_gradebook_grades
)) {
5640 grade_course_reset($data->courseid
);
5641 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5644 if (!empty($data->reset_comments
)) {
5645 require_once($CFG->dirroot
.'/comment/lib.php');
5646 comment
::reset_course_page_comments($context);
5649 $event = \core\event\course_reset_ended
::create($eventparams);
5656 * Generate an email processing address.
5659 * @param string $modargs
5660 * @return string Returns email processing address
5662 function generate_email_processing_address($modid, $modargs) {
5665 $header = $CFG->mailprefix
. substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5666 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain
;
5672 * @todo Finish documenting this function
5674 * @param string $modargs
5675 * @param string $body Currently unused
5677 function moodle_process_email($modargs, $body) {
5680 // The first char should be an unencoded letter. We'll take this as an action.
5681 switch ($modargs[0]) {
5682 case 'B': { // Bounce.
5683 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5684 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5685 // Check the half md5 of their email.
5686 $md5check = substr(md5($user->email
), 0, 16);
5687 if ($md5check == substr($modargs, -16)) {
5688 set_bounce_count($user);
5690 // Else maybe they've already changed it?
5694 // Maybe more later?
5701 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5703 * @param string $action 'get', 'buffer', 'close' or 'flush'
5704 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5706 function get_mailer($action='get') {
5709 /** @var moodle_phpmailer $mailer */
5710 static $mailer = null;
5711 static $counter = 0;
5713 if (!isset($CFG->smtpmaxbulk
)) {
5714 $CFG->smtpmaxbulk
= 1;
5717 if ($action == 'get') {
5718 $prevkeepalive = false;
5720 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5721 if ($counter < $CFG->smtpmaxbulk
and !$mailer->isError()) {
5723 // Reset the mailer.
5724 $mailer->Priority
= 3;
5725 $mailer->CharSet
= 'UTF-8'; // Our default.
5726 $mailer->ContentType
= "text/plain";
5727 $mailer->Encoding
= "8bit";
5728 $mailer->From
= "root@localhost";
5729 $mailer->FromName
= "Root User";
5730 $mailer->Sender
= "";
5731 $mailer->Subject
= "";
5733 $mailer->AltBody
= "";
5734 $mailer->ConfirmReadingTo
= "";
5736 $mailer->clearAllRecipients();
5737 $mailer->clearReplyTos();
5738 $mailer->clearAttachments();
5739 $mailer->clearCustomHeaders();
5743 $prevkeepalive = $mailer->SMTPKeepAlive
;
5744 get_mailer('flush');
5747 require_once($CFG->libdir
.'/phpmailer/moodle_phpmailer.php');
5748 $mailer = new moodle_phpmailer();
5752 if ($CFG->smtphosts
== 'qmail') {
5753 // Use Qmail system.
5756 } else if (empty($CFG->smtphosts
)) {
5757 // Use PHP mail() = sendmail.
5761 // Use SMTP directly.
5763 if (!empty($CFG->debugsmtp
) && (!empty($CFG->debugdeveloper
))) {
5764 $mailer->SMTPDebug
= 3;
5766 // Specify main and backup servers.
5767 $mailer->Host
= $CFG->smtphosts
;
5768 // Specify secure connection protocol.
5769 $mailer->SMTPSecure
= $CFG->smtpsecure
;
5770 // Use previous keepalive.
5771 $mailer->SMTPKeepAlive
= $prevkeepalive;
5773 if ($CFG->smtpuser
) {
5774 // Use SMTP authentication.
5775 $mailer->SMTPAuth
= true;
5776 $mailer->Username
= $CFG->smtpuser
;
5777 $mailer->Password
= $CFG->smtppass
;
5786 // Keep smtp session open after sending.
5787 if ($action == 'buffer') {
5788 if (!empty($CFG->smtpmaxbulk
)) {
5789 get_mailer('flush');
5791 if ($m->Mailer
== 'smtp') {
5792 $m->SMTPKeepAlive
= true;
5798 // Close smtp session, but continue buffering.
5799 if ($action == 'flush') {
5800 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5801 if (!empty($mailer->SMTPDebug
)) {
5804 $mailer->SmtpClose();
5805 if (!empty($mailer->SMTPDebug
)) {
5812 // Close smtp session, do not buffer anymore.
5813 if ($action == 'close') {
5814 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5815 get_mailer('flush');
5816 $mailer->SMTPKeepAlive
= false;
5818 $mailer = null; // Better force new instance.
5824 * A helper function to test for email diversion
5826 * @param string $email
5827 * @return bool Returns true if the email should be diverted
5829 function email_should_be_diverted($email) {
5832 if (empty($CFG->divertallemailsto
)) {
5836 if (empty($CFG->divertallemailsexcept
)) {
5840 $patterns = array_map('trim', preg_split("/[\s,]+/", $CFG->divertallemailsexcept
));
5841 foreach ($patterns as $pattern) {
5842 if (preg_match("/$pattern/", $email)) {
5851 * Generate a unique email Message-ID using the moodle domain and install path
5853 * @param string $localpart An optional unique message id prefix.
5854 * @return string The formatted ID ready for appending to the email headers.
5856 function generate_email_messageid($localpart = null) {
5859 $urlinfo = parse_url($CFG->wwwroot
);
5860 $base = '@' . $urlinfo['host'];
5862 // If multiple moodles are on the same domain we want to tell them
5863 // apart so we add the install path to the local part. This means
5864 // that the id local part should never contain a / character so
5865 // we can correctly parse the id to reassemble the wwwroot.
5866 if (isset($urlinfo['path'])) {
5867 $base = $urlinfo['path'] . $base;
5870 if (empty($localpart)) {
5871 $localpart = uniqid('', true);
5874 // Because we may have an option /installpath suffix to the local part
5875 // of the id we need to escape any / chars which are in the $localpart.
5876 $localpart = str_replace('/', '%2F', $localpart);
5878 return '<' . $localpart . $base . '>';
5882 * Send an email to a specified user
5884 * @param stdClass $user A {@link $USER} object
5885 * @param stdClass $from A {@link $USER} object
5886 * @param string $subject plain text subject line of the email
5887 * @param string $messagetext plain text version of the message
5888 * @param string $messagehtml complete html version of the message (optional)
5889 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in one of
5890 * the following directories: $CFG->cachedir, $CFG->dataroot, $CFG->dirroot, $CFG->localcachedir, $CFG->tempdir
5891 * @param string $attachname the name of the file (extension indicates MIME)
5892 * @param bool $usetrueaddress determines whether $from email address should
5893 * be sent out. Will be overruled by user profile setting for maildisplay
5894 * @param string $replyto Email address to reply to
5895 * @param string $replytoname Name of reply to recipient
5896 * @param int $wordwrapwidth custom word wrap width, default 79
5897 * @return bool Returns true if mail was sent OK and false if there was an error.
5899 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5900 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5902 global $CFG, $PAGE, $SITE;
5904 if (empty($user) or empty($user->id
)) {
5905 debugging('Can not send email to null user', DEBUG_DEVELOPER
);
5909 if (empty($user->email
)) {
5910 debugging('Can not send email to user without email: '.$user->id
, DEBUG_DEVELOPER
);
5914 if (!empty($user->deleted
)) {
5915 debugging('Can not send email to deleted user: '.$user->id
, DEBUG_DEVELOPER
);
5919 if (defined('BEHAT_SITE_RUNNING')) {
5920 // Fake email sending in behat.
5924 if (!empty($CFG->noemailever
)) {
5925 // Hidden setting for development sites, set in config.php if needed.
5926 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL
);
5930 if (email_should_be_diverted($user->email
)) {
5931 $subject = "[DIVERTED {$user->email}] $subject";
5932 $user = clone($user);
5933 $user->email
= $CFG->divertallemailsto
;
5936 // Skip mail to suspended users.
5937 if ((isset($user->auth
) && $user->auth
=='nologin') or (isset($user->suspended
) && $user->suspended
)) {
5941 if (!validate_email($user->email
)) {
5942 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5943 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5947 if (over_bounce_threshold($user)) {
5948 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5952 // TLD .invalid is specifically reserved for invalid domain names.
5953 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5954 if (substr($user->email
, -8) == '.invalid') {
5955 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5956 return true; // This is not an error.
5959 // If the user is a remote mnet user, parse the email text for URL to the
5960 // wwwroot and modify the url to direct the user's browser to login at their
5961 // home site (identity provider - idp) before hitting the link itself.
5962 if (is_mnet_remote_user($user)) {
5963 require_once($CFG->dirroot
.'/mnet/lib.php');
5965 $jumpurl = mnet_get_idp_jump_url($user);
5966 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5968 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5971 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5975 $mail = get_mailer();
5977 if (!empty($mail->SMTPDebug
)) {
5978 echo '<pre>' . "\n";
5981 $temprecipients = array();
5982 $tempreplyto = array();
5984 // Make sure that we fall back onto some reasonable no-reply address.
5985 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot
);
5986 $noreplyaddress = empty($CFG->noreplyaddress
) ?
$noreplyaddressdefault : $CFG->noreplyaddress
;
5988 if (!validate_email($noreplyaddress)) {
5989 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
5990 $noreplyaddress = $noreplyaddressdefault;
5993 // Make up an email address for handling bounces.
5994 if (!empty($CFG->handlebounces
)) {
5995 $modargs = 'B'.base64_encode(pack('V', $user->id
)).substr(md5($user->email
), 0, 16);
5996 $mail->Sender
= generate_email_processing_address(0, $modargs);
5998 $mail->Sender
= $noreplyaddress;
6001 // Make sure that the explicit replyto is valid, fall back to the implicit one.
6002 if (!empty($replyto) && !validate_email($replyto)) {
6003 debugging('email_to_user: Invalid replyto-email '.s($replyto));
6004 $replyto = $noreplyaddress;
6007 if (is_string($from)) { // So we can pass whatever we want if there is need.
6008 $mail->From
= $noreplyaddress;
6009 $mail->FromName
= $from;
6010 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
6011 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6012 // in a course with the sender.
6013 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
6014 if (!validate_email($from->email
)) {
6015 debugging('email_to_user: Invalid from-email '.s($from->email
).' - not sending');
6016 // Better not to use $noreplyaddress in this case.
6019 $mail->From
= $from->email
;
6020 $fromdetails = new stdClass();
6021 $fromdetails->name
= fullname($from);
6022 $fromdetails->url
= preg_replace('#^https?://#', '', $CFG->wwwroot
);
6023 $fromdetails->siteshortname
= format_string($SITE->shortname
);
6024 $fromstring = $fromdetails->name
;
6025 if ($CFG->emailfromvia
== EMAIL_VIA_ALWAYS
) {
6026 $fromstring = get_string('emailvia', 'core', $fromdetails);
6028 $mail->FromName
= $fromstring;
6029 if (empty($replyto)) {
6030 $tempreplyto[] = array($from->email
, fullname($from));
6033 $mail->From
= $noreplyaddress;
6034 $fromdetails = new stdClass();
6035 $fromdetails->name
= fullname($from);
6036 $fromdetails->url
= preg_replace('#^https?://#', '', $CFG->wwwroot
);
6037 $fromdetails->siteshortname
= format_string($SITE->shortname
);
6038 $fromstring = $fromdetails->name
;
6039 if ($CFG->emailfromvia
!= EMAIL_VIA_NEVER
) {
6040 $fromstring = get_string('emailvia', 'core', $fromdetails);
6042 $mail->FromName
= $fromstring;
6043 if (empty($replyto)) {
6044 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
6048 if (!empty($replyto)) {
6049 $tempreplyto[] = array($replyto, $replytoname);
6052 $temprecipients[] = array($user->email
, fullname($user));
6055 $mail->WordWrap
= $wordwrapwidth;
6057 if (!empty($from->customheaders
)) {
6058 // Add custom headers.
6059 if (is_array($from->customheaders
)) {
6060 foreach ($from->customheaders
as $customheader) {
6061 $mail->addCustomHeader($customheader);
6064 $mail->addCustomHeader($from->customheaders
);
6068 // If the X-PHP-Originating-Script email header is on then also add an additional
6069 // header with details of where exactly in moodle the email was triggered from,
6070 // either a call to message_send() or to email_to_user().
6071 if (ini_get('mail.add_x_header')) {
6073 $stack = debug_backtrace(false);
6074 $origin = $stack[0];
6076 foreach ($stack as $depth => $call) {
6077 if ($call['function'] == 'message_send') {
6082 $originheader = $CFG->wwwroot
. ' => ' . gethostname() . ':'
6083 . str_replace($CFG->dirroot
. '/', '', $origin['file']) . ':' . $origin['line'];
6084 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
6087 if (!empty($CFG->emailheaders
)) {
6088 $headers = array_map('trim', explode("\n", $CFG->emailheaders
));
6089 foreach ($headers as $header) {
6090 if (!empty($header)) {
6091 $mail->addCustomHeader($header);
6096 if (!empty($from->priority
)) {
6097 $mail->Priority
= $from->priority
;
6100 $renderer = $PAGE->get_renderer('core');
6102 'sitefullname' => $SITE->fullname
,
6103 'siteshortname' => $SITE->shortname
,
6104 'sitewwwroot' => $CFG->wwwroot
,
6105 'subject' => $subject,
6106 'prefix' => $CFG->emailsubjectprefix
,
6107 'to' => $user->email
,
6108 'toname' => fullname($user),
6109 'from' => $mail->From
,
6110 'fromname' => $mail->FromName
,
6112 if (!empty($tempreplyto[0])) {
6113 $context['replyto'] = $tempreplyto[0][0];
6114 $context['replytoname'] = $tempreplyto[0][1];
6116 if ($user->id
> 0) {
6117 $context['touserid'] = $user->id
;
6118 $context['tousername'] = $user->username
;
6121 if (!empty($user->mailformat
) && $user->mailformat
== 1) {
6122 // Only process html templates if the user preferences allow html email.
6124 if (!$messagehtml) {
6125 // If no html has been given, BUT there is an html wrapping template then
6126 // auto convert the text to html and then wrap it.
6127 $messagehtml = trim(text_to_html($messagetext));
6129 $context['body'] = $messagehtml;
6130 $messagehtml = $renderer->render_from_template('core/email_html', $context);
6133 $context['body'] = html_to_text(nl2br($messagetext));
6134 $mail->Subject
= $renderer->render_from_template('core/email_subject', $context);
6135 $mail->FromName
= $renderer->render_from_template('core/email_fromname', $context);
6136 $messagetext = $renderer->render_from_template('core/email_text', $context);
6138 // Autogenerate a MessageID if it's missing.
6139 if (empty($mail->MessageID
)) {
6140 $mail->MessageID
= generate_email_messageid();
6143 if ($messagehtml && !empty($user->mailformat
) && $user->mailformat
== 1) {
6144 // Don't ever send HTML to users who don't want it.
6145 $mail->isHTML(true);
6146 $mail->Encoding
= 'quoted-printable';
6147 $mail->Body
= $messagehtml;
6148 $mail->AltBody
= "\n$messagetext\n";
6150 $mail->IsHTML(false);
6151 $mail->Body
= "\n$messagetext\n";
6154 if ($attachment && $attachname) {
6155 if (preg_match( "~\\.\\.~" , $attachment )) {
6156 // Security check for ".." in dir path.
6157 $supportuser = core_user
::get_support_user();
6158 $temprecipients[] = array($supportuser->email
, fullname($supportuser, true));
6159 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6161 require_once($CFG->libdir
.'/filelib.php');
6162 $mimetype = mimeinfo('type', $attachname);
6164 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6165 // The absolute (real) path is also fetched to ensure that comparisons to allowed paths are compared equally.
6166 $attachpath = str_replace('\\', '/', realpath($attachment));
6168 // Build an array of all filepaths from which attachments can be added (normalised slashes, absolute/real path).
6169 $allowedpaths = array_map(function(string $path): string {
6170 return str_replace('\\', '/', realpath($path));
6175 $CFG->localcachedir
,
6177 $CFG->localrequestdir
,
6180 // Set addpath to true.
6183 // Check if attachment includes one of the allowed paths.
6184 foreach (array_filter($allowedpaths) as $allowedpath) {
6185 // Set addpath to false if the attachment includes one of the allowed paths.
6186 if (strpos($attachpath, $allowedpath) === 0) {
6192 // If the attachment is a full path to a file in the multiple allowed paths, use it as is,
6193 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6194 if ($addpath == true) {
6195 $attachment = $CFG->dataroot
. '/' . $attachment;
6198 $mail->addAttachment($attachment, $attachname, 'base64', $mimetype);
6202 // Check if the email should be sent in an other charset then the default UTF-8.
6203 if ((!empty($CFG->sitemailcharset
) ||
!empty($CFG->allowusermailcharset
))) {
6205 // Use the defined site mail charset or eventually the one preferred by the recipient.
6206 $charset = $CFG->sitemailcharset
;
6207 if (!empty($CFG->allowusermailcharset
)) {
6208 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id
)) {
6209 $charset = $useremailcharset;
6213 // Convert all the necessary strings if the charset is supported.
6214 $charsets = get_list_of_charsets();
6215 unset($charsets['UTF-8']);
6216 if (in_array($charset, $charsets)) {
6217 $mail->CharSet
= $charset;
6218 $mail->FromName
= core_text
::convert($mail->FromName
, 'utf-8', strtolower($charset));
6219 $mail->Subject
= core_text
::convert($mail->Subject
, 'utf-8', strtolower($charset));
6220 $mail->Body
= core_text
::convert($mail->Body
, 'utf-8', strtolower($charset));
6221 $mail->AltBody
= core_text
::convert($mail->AltBody
, 'utf-8', strtolower($charset));
6223 foreach ($temprecipients as $key => $values) {
6224 $temprecipients[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
6226 foreach ($tempreplyto as $key => $values) {
6227 $tempreplyto[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
6232 foreach ($temprecipients as $values) {
6233 $mail->addAddress($values[0], $values[1]);
6235 foreach ($tempreplyto as $values) {
6236 $mail->addReplyTo($values[0], $values[1]);
6239 if (!empty($CFG->emaildkimselector
)) {
6240 $domain = substr(strrchr($mail->From
, "@"), 1);
6241 $pempath = "{$CFG->dataroot}/dkim/{$domain}/{$CFG->emaildkimselector}.private";
6242 if (file_exists($pempath)) {
6243 $mail->DKIM_domain
= $domain;
6244 $mail->DKIM_private
= $pempath;
6245 $mail->DKIM_selector
= $CFG->emaildkimselector
;
6246 $mail->DKIM_identity
= $mail->From
;
6248 debugging("Email DKIM selector chosen due to {$mail->From} but no certificate found at $pempath", DEBUG_DEVELOPER
);
6252 if ($mail->send()) {
6253 set_send_count($user);
6254 if (!empty($mail->SMTPDebug
)) {
6259 // Trigger event for failing to send email.
6260 $event = \core\event\email_failed
::create(array(
6261 'context' => context_system
::instance(),
6262 'userid' => $from->id
,
6263 'relateduserid' => $user->id
,
6265 'subject' => $subject,
6266 'message' => $messagetext,
6267 'errorinfo' => $mail->ErrorInfo
6272 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo
);
6274 if (!empty($mail->SMTPDebug
)) {
6282 * Check to see if a user's real email address should be used for the "From" field.
6284 * @param object $from The user object for the user we are sending the email from.
6285 * @param object $user The user object that we are sending the email to.
6286 * @param array $unused No longer used.
6287 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6289 function can_send_from_real_email_address($from, $user, $unused = null) {
6291 if (!isset($CFG->allowedemaildomains
) ||
empty(trim($CFG->allowedemaildomains
))) {
6294 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains
));
6295 // Email is in the list of allowed domains for sending email,
6296 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6297 // in a course with the sender.
6298 if (\core\ip_utils
::is_domain_in_allowed_list(substr($from->email
, strpos($from->email
, '@') +
1), $alloweddomains)
6299 && ($from->maildisplay
== core_user
::MAILDISPLAY_EVERYONE
6300 ||
($from->maildisplay
== core_user
::MAILDISPLAY_COURSE_MEMBERS_ONLY
6301 && enrol_get_shared_courses($user, $from, false, true)))) {
6308 * Generate a signoff for emails based on support settings
6312 function generate_email_signoff() {
6316 if (!empty($CFG->supportname
)) {
6317 $signoff .= $CFG->supportname
."\n";
6319 if (!empty($CFG->supportemail
)) {
6320 $signoff .= $CFG->supportemail
."\n";
6322 if (!empty($CFG->supportpage
)) {
6323 $signoff .= $CFG->supportpage
."\n";
6329 * Sets specified user's password and send the new password to the user via email.
6331 * @param stdClass $user A {@link $USER} object
6332 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6333 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6335 function setnew_password_and_mail($user, $fasthash = false) {
6338 // We try to send the mail in language the user understands,
6339 // unfortunately the filter_string() does not support alternative langs yet
6340 // so multilang will not work properly for site->fullname.
6341 $lang = empty($user->lang
) ?
get_newuser_language() : $user->lang
;
6345 $supportuser = core_user
::get_support_user();
6347 $newpassword = generate_password();
6349 update_internal_user_password($user, $newpassword, $fasthash);
6351 $a = new stdClass();
6352 $a->firstname
= fullname($user, true);
6353 $a->sitename
= format_string($site->fullname
);
6354 $a->username
= $user->username
;
6355 $a->newpassword
= $newpassword;
6356 $a->link
= $CFG->wwwroot
.'/login/?lang='.$lang;
6357 $a->signoff
= generate_email_signoff();
6359 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6361 $subject = format_string($site->fullname
) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6363 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6364 return email_to_user($user, $supportuser, $subject, $message);
6369 * Resets specified user's password and send the new password to the user via email.
6371 * @param stdClass $user A {@link $USER} object
6372 * @return bool Returns true if mail was sent OK and false if there was an error.
6374 function reset_password_and_mail($user) {
6378 $supportuser = core_user
::get_support_user();
6380 $userauth = get_auth_plugin($user->auth
);
6381 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth
)) {
6382 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6386 $newpassword = generate_password();
6388 if (!$userauth->user_update_password($user, $newpassword)) {
6389 print_error("cannotsetpassword");
6392 $a = new stdClass();
6393 $a->firstname
= $user->firstname
;
6394 $a->lastname
= $user->lastname
;
6395 $a->sitename
= format_string($site->fullname
);
6396 $a->username
= $user->username
;
6397 $a->newpassword
= $newpassword;
6398 $a->link
= $CFG->wwwroot
.'/login/change_password.php';
6399 $a->signoff
= generate_email_signoff();
6401 $message = get_string('newpasswordtext', '', $a);
6403 $subject = format_string($site->fullname
) .': '. get_string('changedpassword');
6405 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6407 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6408 return email_to_user($user, $supportuser, $subject, $message);
6412 * Send email to specified user with confirmation text and activation link.
6414 * @param stdClass $user A {@link $USER} object
6415 * @param string $confirmationurl user confirmation URL
6416 * @return bool Returns true if mail was sent OK and false if there was an error.
6418 function send_confirmation_email($user, $confirmationurl = null) {
6422 $supportuser = core_user
::get_support_user();
6424 $data = new stdClass();
6425 $data->sitename
= format_string($site->fullname
);
6426 $data->admin
= generate_email_signoff();
6428 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname
));
6430 if (empty($confirmationurl)) {
6431 $confirmationurl = '/login/confirm.php';
6434 $confirmationurl = new moodle_url($confirmationurl);
6435 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6436 $confirmationurl->remove_params('data');
6437 $confirmationpath = $confirmationurl->out(false);
6439 // We need to custom encode the username to include trailing dots in the link.
6440 // Because of this custom encoding we can't use moodle_url directly.
6441 // Determine if a query string is present in the confirmation url.
6442 $hasquerystring = strpos($confirmationpath, '?') !== false;
6443 // Perform normal url encoding of the username first.
6444 $username = urlencode($user->username
);
6445 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6446 $username = str_replace('.', '%2E', $username);
6448 $data->link
= $confirmationpath . ( $hasquerystring ?
'&' : '?') . 'data='. $user->secret
.'/'. $username;
6450 $message = get_string('emailconfirmation', '', $data);
6451 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6453 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6454 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6458 * Sends a password change confirmation email.
6460 * @param stdClass $user A {@link $USER} object
6461 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6462 * @return bool Returns true if mail was sent OK and false if there was an error.
6464 function send_password_change_confirmation_email($user, $resetrecord) {
6468 $supportuser = core_user
::get_support_user();
6469 $pwresetmins = isset($CFG->pwresettime
) ?
floor($CFG->pwresettime
/ MINSECS
) : 30;
6471 $data = new stdClass();
6472 $data->firstname
= $user->firstname
;
6473 $data->lastname
= $user->lastname
;
6474 $data->username
= $user->username
;
6475 $data->sitename
= format_string($site->fullname
);
6476 $data->link
= $CFG->wwwroot
.'/login/forgot_password.php?token='. $resetrecord->token
;
6477 $data->admin
= generate_email_signoff();
6478 $data->resetminutes
= $pwresetmins;
6480 $message = get_string('emailresetconfirmation', '', $data);
6481 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname
));
6483 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6484 return email_to_user($user, $supportuser, $subject, $message);
6489 * Sends an email containing information on how to change your password.
6491 * @param stdClass $user A {@link $USER} object
6492 * @return bool Returns true if mail was sent OK and false if there was an error.
6494 function send_password_change_info($user) {
6496 $supportuser = core_user
::get_support_user();
6498 $data = new stdClass();
6499 $data->firstname
= $user->firstname
;
6500 $data->lastname
= $user->lastname
;
6501 $data->username
= $user->username
;
6502 $data->sitename
= format_string($site->fullname
);
6503 $data->admin
= generate_email_signoff();
6505 if (!is_enabled_auth($user->auth
)) {
6506 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6507 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6508 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6509 return email_to_user($user, $supportuser, $subject, $message);
6512 $userauth = get_auth_plugin($user->auth
);
6513 ['subject' => $subject, 'message' => $message] = $userauth->get_password_change_info($user);
6515 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6516 return email_to_user($user, $supportuser, $subject, $message);
6520 * Check that an email is allowed. It returns an error message if there was a problem.
6522 * @param string $email Content of email
6523 * @return string|false
6525 function email_is_not_allowed($email) {
6528 // Comparing lowercase domains.
6529 $email = strtolower($email);
6530 if (!empty($CFG->allowemailaddresses
)) {
6531 $allowed = explode(' ', strtolower($CFG->allowemailaddresses
));
6532 foreach ($allowed as $allowedpattern) {
6533 $allowedpattern = trim($allowedpattern);
6534 if (!$allowedpattern) {
6537 if (strpos($allowedpattern, '.') === 0) {
6538 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6539 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6543 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6547 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses
);
6549 } else if (!empty($CFG->denyemailaddresses
)) {
6550 $denied = explode(' ', strtolower($CFG->denyemailaddresses
));
6551 foreach ($denied as $deniedpattern) {
6552 $deniedpattern = trim($deniedpattern);
6553 if (!$deniedpattern) {
6556 if (strpos($deniedpattern, '.') === 0) {
6557 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6558 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6559 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
6562 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6563 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
6574 * Returns local file storage instance
6576 * @return file_storage
6578 function get_file_storage($reset = false) {
6592 require_once("$CFG->libdir/filelib.php");
6594 $fs = new file_storage();
6600 * Returns local file storage instance
6602 * @return file_browser
6604 function get_file_browser() {
6613 require_once("$CFG->libdir/filelib.php");
6615 $fb = new file_browser();
6621 * Returns file packer
6623 * @param string $mimetype default application/zip
6624 * @return file_packer
6626 function get_file_packer($mimetype='application/zip') {
6629 static $fp = array();
6631 if (isset($fp[$mimetype])) {
6632 return $fp[$mimetype];
6635 switch ($mimetype) {
6636 case 'application/zip':
6637 case 'application/vnd.moodle.profiling':
6638 $classname = 'zip_packer';
6641 case 'application/x-gzip' :
6642 $classname = 'tgz_packer';
6645 case 'application/vnd.moodle.backup':
6646 $classname = 'mbz_packer';
6653 require_once("$CFG->libdir/filestorage/$classname.php");
6654 $fp[$mimetype] = new $classname();
6656 return $fp[$mimetype];
6660 * Returns current name of file on disk if it exists.
6662 * @param string $newfile File to be verified
6663 * @return string Current name of file on disk if true
6665 function valid_uploaded_file($newfile) {
6666 if (empty($newfile)) {
6669 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6670 return $newfile['tmp_name'];
6677 * Returns the maximum size for uploading files.
6679 * There are seven possible upload limits:
6680 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6681 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6682 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6683 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6684 * 5. by the Moodle admin in $CFG->maxbytes
6685 * 6. by the teacher in the current course $course->maxbytes
6686 * 7. by the teacher for the current module, eg $assignment->maxbytes
6688 * These last two are passed to this function as arguments (in bytes).
6689 * Anything defined as 0 is ignored.
6690 * The smallest of all the non-zero numbers is returned.
6692 * @todo Finish documenting this function
6694 * @param int $sitebytes Set maximum size
6695 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6696 * @param int $modulebytes Current module ->maxbytes (in bytes)
6697 * @param bool $unused This parameter has been deprecated and is not used any more.
6698 * @return int The maximum size for uploading files.
6700 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6702 if (! $filesize = ini_get('upload_max_filesize')) {
6705 $minimumsize = get_real_size($filesize);
6707 if ($postsize = ini_get('post_max_size')) {
6708 $postsize = get_real_size($postsize);
6709 if ($postsize < $minimumsize) {
6710 $minimumsize = $postsize;
6714 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6715 $minimumsize = $sitebytes;
6718 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6719 $minimumsize = $coursebytes;
6722 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6723 $minimumsize = $modulebytes;
6726 return $minimumsize;
6730 * Returns the maximum size for uploading files for the current user
6732 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6734 * @param context $context The context in which to check user capabilities
6735 * @param int $sitebytes Set maximum size
6736 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6737 * @param int $modulebytes Current module ->maxbytes (in bytes)
6738 * @param stdClass $user The user
6739 * @param bool $unused This parameter has been deprecated and is not used any more.
6740 * @return int The maximum size for uploading files.
6742 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6750 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6751 return USER_CAN_IGNORE_FILE_SIZE_LIMITS
;
6754 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6758 * Returns an array of possible sizes in local language
6760 * Related to {@link get_max_upload_file_size()} - this function returns an
6761 * array of possible sizes in an array, translated to the
6764 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6766 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6767 * with the value set to 0. This option will be the first in the list.
6769 * @uses SORT_NUMERIC
6770 * @param int $sitebytes Set maximum size
6771 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6772 * @param int $modulebytes Current module ->maxbytes (in bytes)
6773 * @param int|array $custombytes custom upload size/s which will be added to list,
6774 * Only value/s smaller then maxsize will be added to list.
6777 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6780 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6784 if ($sitebytes == 0) {
6785 // Will get the minimum of upload_max_filesize or post_max_size.
6786 $sitebytes = get_max_upload_file_size();
6789 $filesize = array();
6790 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6791 5242880, 10485760, 20971520, 52428800, 104857600,
6792 262144000, 524288000, 786432000, 1073741824,
6793 2147483648, 4294967296, 8589934592);
6795 // If custombytes is given and is valid then add it to the list.
6796 if (is_number($custombytes) and $custombytes > 0) {
6797 $custombytes = (int)$custombytes;
6798 if (!in_array($custombytes, $sizelist)) {
6799 $sizelist[] = $custombytes;
6801 } else if (is_array($custombytes)) {
6802 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6805 // Allow maxbytes to be selected if it falls outside the above boundaries.
6806 if (isset($CFG->maxbytes
) && !in_array(get_real_size($CFG->maxbytes
), $sizelist)) {
6807 // Note: get_real_size() is used in order to prevent problems with invalid values.
6808 $sizelist[] = get_real_size($CFG->maxbytes
);
6811 foreach ($sizelist as $sizebytes) {
6812 if ($sizebytes < $maxsize && $sizebytes > 0) {
6813 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6820 (($modulebytes < $coursebytes ||
$coursebytes == 0) &&
6821 ($modulebytes < $sitebytes ||
$sitebytes == 0))) {
6822 $limitlevel = get_string('activity', 'core');
6823 $displaysize = display_size($modulebytes);
6824 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6826 } else if ($coursebytes && ($coursebytes < $sitebytes ||
$sitebytes == 0)) {
6827 $limitlevel = get_string('course', 'core');
6828 $displaysize = display_size($coursebytes);
6829 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6831 } else if ($sitebytes) {
6832 $limitlevel = get_string('site', 'core');
6833 $displaysize = display_size($sitebytes);
6834 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6837 krsort($filesize, SORT_NUMERIC
);
6839 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6840 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) +
$filesize;
6847 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6849 * If excludefiles is defined, then that file/directory is ignored
6850 * If getdirs is true, then (sub)directories are included in the output
6851 * If getfiles is true, then files are included in the output
6852 * (at least one of these must be true!)
6854 * @todo Finish documenting this function. Add examples of $excludefile usage.
6856 * @param string $rootdir A given root directory to start from
6857 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6858 * @param bool $descend If true then subdirectories are recursed as well
6859 * @param bool $getdirs If true then (sub)directories are included in the output
6860 * @param bool $getfiles If true then files are included in the output
6861 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6863 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6867 if (!$getdirs and !$getfiles) { // Nothing to show.
6871 if (!is_dir($rootdir)) { // Must be a directory.
6875 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6879 if (!is_array($excludefiles)) {
6880 $excludefiles = array($excludefiles);
6883 while (false !== ($file = readdir($dir))) {
6884 $firstchar = substr($file, 0, 1);
6885 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6888 $fullfile = $rootdir .'/'. $file;
6889 if (filetype($fullfile) == 'dir') {
6894 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6895 foreach ($subdirs as $subdir) {
6896 $dirs[] = $file .'/'. $subdir;
6899 } else if ($getfiles) {
6912 * Adds up all the files in a directory and works out the size.
6914 * @param string $rootdir The directory to start from
6915 * @param string $excludefile A file to exclude when summing directory size
6916 * @return int The summed size of all files and subfiles within the root directory
6918 function get_directory_size($rootdir, $excludefile='') {
6921 // Do it this way if we can, it's much faster.
6922 if (!empty($CFG->pathtodu
) && is_executable(trim($CFG->pathtodu
))) {
6923 $command = trim($CFG->pathtodu
).' -sk '.escapeshellarg($rootdir);
6926 exec($command, $output, $return);
6927 if (is_array($output)) {
6928 // We told it to return k.
6929 return get_real_size(intval($output[0]).'k');
6933 if (!is_dir($rootdir)) {
6934 // Must be a directory.
6938 if (!$dir = @opendir
($rootdir)) {
6939 // Can't open it for some reason.
6945 while (false !== ($file = readdir($dir))) {
6946 $firstchar = substr($file, 0, 1);
6947 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6950 $fullfile = $rootdir .'/'. $file;
6951 if (filetype($fullfile) == 'dir') {
6952 $size +
= get_directory_size($fullfile, $excludefile);
6954 $size +
= filesize($fullfile);
6963 * Converts bytes into display form
6965 * @static string $gb Localized string for size in gigabytes
6966 * @static string $mb Localized string for size in megabytes
6967 * @static string $kb Localized string for size in kilobytes
6968 * @static string $b Localized string for size in bytes
6969 * @param int $size The size to convert to human readable form
6972 function display_size($size) {
6976 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS
) {
6977 return get_string('unlimited');
6980 if (empty($units)) {
6981 $units[] = get_string('sizeb');
6982 $units[] = get_string('sizekb');
6983 $units[] = get_string('sizemb');
6984 $units[] = get_string('sizegb');
6985 $units[] = get_string('sizetb');
6986 $units[] = get_string('sizepb');
6989 if ($size >= 1024 ** 5) {
6990 $size = round($size / 1024 ** 5 * 10) / 10 . $units[5];
6991 } else if ($size >= 1024 ** 4) {
6992 $size = round($size / 1024 ** 4 * 10) / 10 . $units[4];
6993 } else if ($size >= 1024 ** 3) {
6994 $size = round($size / 1024 ** 3 * 10) / 10 . $units[3];
6995 } else if ($size >= 1024 ** 2) {
6996 $size = round($size / 1024 ** 2 * 10) / 10 . $units[2];
6997 } else if ($size >= 1024 ** 1) {
6998 $size = round($size / 1024 ** 1 * 10) / 10 . $units[1];
7000 $size = intval($size) .' '. $units[0]; // File sizes over 2GB can not work in 32bit PHP anyway.
7006 * Cleans a given filename by removing suspicious or troublesome characters
7008 * @see clean_param()
7009 * @param string $string file name
7010 * @return string cleaned file name
7012 function clean_filename($string) {
7013 return clean_param($string, PARAM_FILE
);
7016 // STRING TRANSLATION.
7019 * Returns the code for the current language
7024 function current_language() {
7025 global $CFG, $USER, $SESSION, $COURSE;
7027 if (!empty($SESSION->forcelang
)) {
7028 // Allows overriding course-forced language (useful for admins to check
7029 // issues in courses whose language they don't understand).
7030 // Also used by some code to temporarily get language-related information in a
7031 // specific language (see force_current_language()).
7032 $return = $SESSION->forcelang
;
7034 } else if (!empty($COURSE->id
) and $COURSE->id
!= SITEID
and !empty($COURSE->lang
)) {
7035 // Course language can override all other settings for this page.
7036 $return = $COURSE->lang
;
7038 } else if (!empty($SESSION->lang
)) {
7039 // Session language can override other settings.
7040 $return = $SESSION->lang
;
7042 } else if (!empty($USER->lang
)) {
7043 $return = $USER->lang
;
7045 } else if (isset($CFG->lang
)) {
7046 $return = $CFG->lang
;
7052 // Just in case this slipped in from somewhere by accident.
7053 $return = str_replace('_utf8', '', $return);
7059 * Returns parent language of current active language if defined
7062 * @param string $lang null means current language
7065 function get_parent_language($lang=null) {
7067 $parentlang = get_string_manager()->get_string('parentlanguage', 'langconfig', null, $lang);
7069 if ($parentlang === 'en') {
7077 * Force the current language to get strings and dates localised in the given language.
7079 * After calling this function, all strings will be provided in the given language
7080 * until this function is called again, or equivalent code is run.
7082 * @param string $language
7083 * @return string previous $SESSION->forcelang value
7085 function force_current_language($language) {
7087 $sessionforcelang = isset($SESSION->forcelang
) ?
$SESSION->forcelang
: '';
7088 if ($language !== $sessionforcelang) {
7089 // Seting forcelang to null or an empty string disables it's effect.
7090 if (empty($language) ||
get_string_manager()->translation_exists($language, false)) {
7091 $SESSION->forcelang
= $language;
7095 return $sessionforcelang;
7099 * Returns current string_manager instance.
7101 * The param $forcereload is needed for CLI installer only where the string_manager instance
7102 * must be replaced during the install.php script life time.
7105 * @param bool $forcereload shall the singleton be released and new instance created instead?
7106 * @return core_string_manager
7108 function get_string_manager($forcereload=false) {
7111 static $singleton = null;
7116 if ($singleton === null) {
7117 if (empty($CFG->early_install_lang
)) {
7119 $transaliases = array();
7120 if (empty($CFG->langlist
)) {
7121 $translist = array();
7123 $translist = explode(',', $CFG->langlist
);
7124 $translist = array_map('trim', $translist);
7125 // Each language in the $CFG->langlist can has an "alias" that would substitute the default language name.
7126 foreach ($translist as $i => $value) {
7127 $parts = preg_split('/\s*\|\s*/', $value, 2);
7128 if (count($parts) == 2) {
7129 $transaliases[$parts[0]] = $parts[1];
7130 $translist[$i] = $parts[0];
7135 if (!empty($CFG->config_php_settings
['customstringmanager'])) {
7136 $classname = $CFG->config_php_settings
['customstringmanager'];
7138 if (class_exists($classname)) {
7139 $implements = class_implements($classname);
7141 if (isset($implements['core_string_manager'])) {
7142 $singleton = new $classname($CFG->langotherroot
, $CFG->langlocalroot
, $translist, $transaliases);
7146 debugging('Unable to instantiate custom string manager: class '.$classname.
7147 ' does not implement the core_string_manager interface.');
7151 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7155 $singleton = new core_string_manager_standard($CFG->langotherroot
, $CFG->langlocalroot
, $translist, $transaliases);
7158 $singleton = new core_string_manager_install();
7166 * Returns a localized string.
7168 * Returns the translated string specified by $identifier as
7169 * for $module. Uses the same format files as STphp.
7170 * $a is an object, string or number that can be used
7171 * within translation strings
7173 * eg 'hello {$a->firstname} {$a->lastname}'
7176 * If you would like to directly echo the localized string use
7177 * the function {@link print_string()}
7179 * Example usage of this function involves finding the string you would
7180 * like a local equivalent of and using its identifier and module information
7181 * to retrieve it.<br/>
7182 * If you open moodle/lang/en/moodle.php and look near line 278
7183 * you will find a string to prompt a user for their word for 'course'
7185 * $string['course'] = 'Course';
7187 * So if you want to display the string 'Course'
7188 * in any language that supports it on your site
7189 * you just need to use the identifier 'course'
7191 * $mystring = '<strong>'. get_string('course') .'</strong>';
7194 * If the string you want is in another file you'd take a slightly
7195 * different approach. Looking in moodle/lang/en/calendar.php you find
7198 * $string['typecourse'] = 'Course event';
7200 * If you want to display the string "Course event" in any language
7201 * supported you would use the identifier 'typecourse' and the module 'calendar'
7202 * (because it is in the file calendar.php):
7204 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7207 * As a last resort, should the identifier fail to map to a string
7208 * the returned string will be [[ $identifier ]]
7210 * In Moodle 2.3 there is a new argument to this function $lazyload.
7211 * Setting $lazyload to true causes get_string to return a lang_string object
7212 * rather than the string itself. The fetching of the string is then put off until
7213 * the string object is first used. The object can be used by calling it's out
7214 * method or by casting the object to a string, either directly e.g.
7215 * (string)$stringobject
7216 * or indirectly by using the string within another string or echoing it out e.g.
7217 * echo $stringobject
7218 * return "<p>{$stringobject}</p>";
7219 * It is worth noting that using $lazyload and attempting to use the string as an
7220 * array key will cause a fatal error as objects cannot be used as array keys.
7221 * But you should never do that anyway!
7222 * For more information {@link lang_string}
7225 * @param string $identifier The key identifier for the localized string
7226 * @param string $component The module where the key identifier is stored,
7227 * usually expressed as the filename in the language pack without the
7228 * .php on the end but can also be written as mod/forum or grade/export/xls.
7229 * If none is specified then moodle.php is used.
7230 * @param string|object|array $a An object, string or number that can be used
7231 * within translation strings
7232 * @param bool $lazyload If set to true a string object is returned instead of
7233 * the string itself. The string then isn't calculated until it is first used.
7234 * @return string The localized string.
7235 * @throws coding_exception
7237 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7240 // If the lazy load argument has been supplied return a lang_string object
7242 // We need to make sure it is true (and a bool) as you will see below there
7243 // used to be a forth argument at one point.
7244 if ($lazyload === true) {
7245 return new lang_string($identifier, $component, $a);
7248 if ($CFG->debugdeveloper
&& clean_param($identifier, PARAM_STRINGID
) === '') {
7249 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER
);
7252 // There is now a forth argument again, this time it is a boolean however so
7253 // we can still check for the old extralocations parameter.
7254 if (!is_bool($lazyload) && !empty($lazyload)) {
7255 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7258 if (strpos($component, '/') !== false) {
7259 debugging('The module name you passed to get_string is the deprecated format ' .
7260 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER
);
7261 $componentpath = explode('/', $component);
7263 switch ($componentpath[0]) {
7265 $component = $componentpath[1];
7269 $component = 'block_'.$componentpath[1];
7272 $component = 'enrol_'.$componentpath[1];
7275 $component = 'format_'.$componentpath[1];
7278 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7283 $result = get_string_manager()->get_string($identifier, $component, $a);
7285 // Debugging feature lets you display string identifier and component.
7286 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
7287 $result .= ' {' . $identifier . '/' . $component . '}';
7293 * Converts an array of strings to their localized value.
7295 * @param array $array An array of strings
7296 * @param string $component The language module that these strings can be found in.
7297 * @return stdClass translated strings.
7299 function get_strings($array, $component = '') {
7300 $string = new stdClass
;
7301 foreach ($array as $item) {
7302 $string->$item = get_string($item, $component);
7308 * Prints out a translated string.
7310 * Prints out a translated string using the return value from the {@link get_string()} function.
7312 * Example usage of this function when the string is in the moodle.php file:<br/>
7315 * print_string('course');
7319 * Example usage of this function when the string is not in the moodle.php file:<br/>
7322 * print_string('typecourse', 'calendar');
7327 * @param string $identifier The key identifier for the localized string
7328 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7329 * @param string|object|array $a An object, string or number that can be used within translation strings
7331 function print_string($identifier, $component = '', $a = null) {
7332 echo get_string($identifier, $component, $a);
7336 * Returns a list of charset codes
7338 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7339 * (checking that such charset is supported by the texlib library!)
7341 * @return array And associative array with contents in the form of charset => charset
7343 function get_list_of_charsets() {
7346 'EUC-JP' => 'EUC-JP',
7347 'ISO-2022-JP'=> 'ISO-2022-JP',
7348 'ISO-8859-1' => 'ISO-8859-1',
7349 'SHIFT-JIS' => 'SHIFT-JIS',
7350 'GB2312' => 'GB2312',
7351 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7352 'UTF-8' => 'UTF-8');
7360 * Returns a list of valid and compatible themes
7364 function get_list_of_themes() {
7369 if (!empty($CFG->themelist
)) { // Use admin's list of themes.
7370 $themelist = explode(',', $CFG->themelist
);
7372 $themelist = array_keys(core_component
::get_plugin_list("theme"));
7375 foreach ($themelist as $key => $themename) {
7376 $theme = theme_config
::load($themename);
7377 $themes[$themename] = $theme;
7380 core_collator
::asort_objects_by_method($themes, 'get_theme_name');
7386 * Factory function for emoticon_manager
7388 * @return emoticon_manager singleton
7390 function get_emoticon_manager() {
7391 static $singleton = null;
7393 if (is_null($singleton)) {
7394 $singleton = new emoticon_manager();
7401 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7403 * Whenever this manager mentiones 'emoticon object', the following data
7404 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7405 * altidentifier and altcomponent
7407 * @see admin_setting_emoticons
7409 * @copyright 2010 David Mudrak
7410 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7412 class emoticon_manager
{
7415 * Returns the currently enabled emoticons
7417 * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
7418 * @return array of emoticon objects
7420 public function get_emoticons($selectable = false) {
7422 $notselectable = ['martin', 'egg'];
7424 if (empty($CFG->emoticons
)) {
7428 $emoticons = $this->decode_stored_config($CFG->emoticons
);
7430 if (!is_array($emoticons)) {
7431 // Something is wrong with the format of stored setting.
7432 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL
);
7436 foreach ($emoticons as $index => $emote) {
7437 if (in_array($emote->altidentifier
, $notselectable)) {
7439 unset($emoticons[$index]);
7448 * Converts emoticon object into renderable pix_emoticon object
7450 * @param stdClass $emoticon emoticon object
7451 * @param array $attributes explicit HTML attributes to set
7452 * @return pix_emoticon
7454 public function prepare_renderable_emoticon(stdClass
$emoticon, array $attributes = array()) {
7455 $stringmanager = get_string_manager();
7456 if ($stringmanager->string_exists($emoticon->altidentifier
, $emoticon->altcomponent
)) {
7457 $alt = get_string($emoticon->altidentifier
, $emoticon->altcomponent
);
7459 $alt = s($emoticon->text
);
7461 return new pix_emoticon($emoticon->imagename
, $alt, $emoticon->imagecomponent
, $attributes);
7465 * Encodes the array of emoticon objects into a string storable in config table
7467 * @see self::decode_stored_config()
7468 * @param array $emoticons array of emtocion objects
7471 public function encode_stored_config(array $emoticons) {
7472 return json_encode($emoticons);
7476 * Decodes the string into an array of emoticon objects
7478 * @see self::encode_stored_config()
7479 * @param string $encoded
7480 * @return string|null
7482 public function decode_stored_config($encoded) {
7483 $decoded = json_decode($encoded);
7484 if (!is_array($decoded)) {
7491 * Returns default set of emoticons supported by Moodle
7493 * @return array of sdtClasses
7495 public function default_emoticons() {
7497 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7498 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7499 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7500 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7501 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7502 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7503 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7504 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7505 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7506 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7507 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7508 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7509 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7510 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7511 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7512 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7513 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7514 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7515 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7516 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7517 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7518 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7519 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7520 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7521 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7522 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7523 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7524 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7525 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7526 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7531 * Helper method preparing the stdClass with the emoticon properties
7533 * @param string|array $text or array of strings
7534 * @param string $imagename to be used by {@link pix_emoticon}
7535 * @param string $altidentifier alternative string identifier, null for no alt
7536 * @param string $altcomponent where the alternative string is defined
7537 * @param string $imagecomponent to be used by {@link pix_emoticon}
7540 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7541 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7542 return (object)array(
7544 'imagename' => $imagename,
7545 'imagecomponent' => $imagecomponent,
7546 'altidentifier' => $altidentifier,
7547 'altcomponent' => $altcomponent,
7557 * @param string $data Data to encrypt.
7558 * @return string The now encrypted data.
7560 function rc4encrypt($data) {
7561 return endecrypt(get_site_identifier(), $data, '');
7567 * @param string $data Data to decrypt.
7568 * @return string The now decrypted data.
7570 function rc4decrypt($data) {
7571 return endecrypt(get_site_identifier(), $data, 'de');
7575 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7577 * @todo Finish documenting this function
7579 * @param string $pwd The password to use when encrypting or decrypting
7580 * @param string $data The data to be decrypted/encrypted
7581 * @param string $case Either 'de' for decrypt or '' for encrypt
7584 function endecrypt ($pwd, $data, $case) {
7586 if ($case == 'de') {
7587 $data = urldecode($data);
7592 $pwdlength = strlen($pwd);
7594 for ($i = 0; $i <= 255; $i++
) {
7595 $key[$i] = ord(substr($pwd, ($i %
$pwdlength), 1));
7601 for ($i = 0; $i <= 255; $i++
) {
7602 $x = ($x +
$box[$i] +
$key[$i]) %
256;
7603 $tempswap = $box[$i];
7604 $box[$i] = $box[$x];
7605 $box[$x] = $tempswap;
7613 for ($i = 0; $i < strlen($data); $i++
) {
7614 $a = ($a +
1) %
256;
7615 $j = ($j +
$box[$a]) %
256;
7617 $box[$a] = $box[$j];
7619 $k = $box[(($box[$a] +
$box[$j]) %
256)];
7620 $cipherby = ord(substr($data, $i, 1)) ^
$k;
7621 $cipher .= chr($cipherby);
7624 if ($case == 'de') {
7625 $cipher = urldecode(urlencode($cipher));
7627 $cipher = urlencode($cipher);
7633 // ENVIRONMENT CHECKING.
7636 * This method validates a plug name. It is much faster than calling clean_param.
7638 * @param string $name a string that might be a plugin name.
7639 * @return bool if this string is a valid plugin name.
7641 function is_valid_plugin_name($name) {
7642 // This does not work for 'mod', bad luck, use any other type.
7643 return core_component
::is_valid_plugin_name('tool', $name);
7647 * Get a list of all the plugins of a given type that define a certain API function
7648 * in a certain file. The plugin component names and function names are returned.
7650 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7651 * @param string $function the part of the name of the function after the
7652 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7653 * names like report_courselist_hook.
7654 * @param string $file the name of file within the plugin that defines the
7655 * function. Defaults to lib.php.
7656 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7657 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7659 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7662 // We don't include here as all plugin types files would be included.
7663 $plugins = get_plugins_with_function($function, $file, false);
7665 if (empty($plugins[$plugintype])) {
7669 $allplugins = core_component
::get_plugin_list($plugintype);
7671 // Reformat the array and include the files.
7672 $pluginfunctions = array();
7673 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7675 // Check that it has not been removed and the file is still available.
7676 if (!empty($allplugins[$pluginname])) {
7678 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR
. $file;
7679 if (file_exists($filepath)) {
7680 include_once($filepath);
7682 // Now that the file is loaded, we must verify the function still exists.
7683 if (function_exists($functionname)) {
7684 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7686 // Invalidate the cache for next run.
7687 \cache_helper
::invalidate_by_definition('core', 'plugin_functions');
7693 return $pluginfunctions;
7697 * Get a list of all the plugins that define a certain API function in a certain file.
7699 * @param string $function the part of the name of the function after the
7700 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7701 * names like report_courselist_hook.
7702 * @param string $file the name of file within the plugin that defines the
7703 * function. Defaults to lib.php.
7704 * @param bool $include Whether to include the files that contain the functions or not.
7705 * @return array with [plugintype][plugin] = functionname
7707 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7710 if (during_initial_install() ||
isset($CFG->upgraderunning
)) {
7711 // API functions _must not_ be called during an installation or upgrade.
7715 $cache = \cache
::make('core', 'plugin_functions');
7717 // Including both although I doubt that we will find two functions definitions with the same name.
7718 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7719 $key = $function . '_' . clean_param($file, PARAM_ALPHA
);
7720 $pluginfunctions = $cache->get($key);
7723 // Use the plugin manager to check that plugins are currently installed.
7724 $pluginmanager = \core_plugin_manager
::instance();
7726 if ($pluginfunctions !== false) {
7728 // Checking that the files are still available.
7729 foreach ($pluginfunctions as $plugintype => $plugins) {
7731 $allplugins = \core_component
::get_plugin_list($plugintype);
7732 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7733 foreach ($plugins as $plugin => $function) {
7734 if (!isset($installedplugins[$plugin])) {
7735 // Plugin code is still present on disk but it is not installed.
7740 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7741 if (empty($allplugins[$plugin])) {
7746 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR
. $file);
7747 if ($include && $fileexists) {
7748 // Include the files if it was requested.
7749 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR
. $file);
7750 } else if (!$fileexists) {
7751 // If the file is not available any more it should not be returned.
7756 // Check if the function still exists in the file.
7757 if ($include && !function_exists($function)) {
7764 // If the cache is dirty, we should fall through and let it rebuild.
7766 return $pluginfunctions;
7770 $pluginfunctions = array();
7772 // To fill the cached. Also, everything should continue working with cache disabled.
7773 $plugintypes = \core_component
::get_plugin_types();
7774 foreach ($plugintypes as $plugintype => $unused) {
7776 // We need to include files here.
7777 $pluginswithfile = \core_component
::get_plugin_list_with_file($plugintype, $file, true);
7778 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7779 foreach ($pluginswithfile as $plugin => $notused) {
7781 if (!isset($installedplugins[$plugin])) {
7785 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7787 $pluginfunction = false;
7788 if (function_exists($fullfunction)) {
7789 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7790 $pluginfunction = $fullfunction;
7792 } else if ($plugintype === 'mod') {
7793 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7794 $shortfunction = $plugin . '_' . $function;
7795 if (function_exists($shortfunction)) {
7796 $pluginfunction = $shortfunction;
7800 if ($pluginfunction) {
7801 if (empty($pluginfunctions[$plugintype])) {
7802 $pluginfunctions[$plugintype] = array();
7804 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7809 $cache->set($key, $pluginfunctions);
7811 return $pluginfunctions;
7816 * Lists plugin-like directories within specified directory
7818 * This function was originally used for standard Moodle plugins, please use
7819 * new core_component::get_plugin_list() now.
7821 * This function is used for general directory listing and backwards compatility.
7823 * @param string $directory relative directory from root
7824 * @param string $exclude dir name to exclude from the list (defaults to none)
7825 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7826 * @return array Sorted array of directory names found under the requested parameters
7828 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7833 if (empty($basedir)) {
7834 $basedir = $CFG->dirroot
.'/'. $directory;
7837 $basedir = $basedir .'/'. $directory;
7840 if ($CFG->debugdeveloper
and empty($exclude)) {
7841 // Make sure devs do not use this to list normal plugins,
7842 // this is intended for general directories that are not plugins!
7844 $subtypes = core_component
::get_plugin_types();
7845 if (in_array($basedir, $subtypes)) {
7846 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER
);
7851 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7852 if (!$dirhandle = opendir($basedir)) {
7853 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER
);
7856 while (false !== ($dir = readdir($dirhandle))) {
7857 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7858 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7859 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7862 if (filetype($basedir .'/'. $dir) != 'dir') {
7867 closedir($dirhandle);
7876 * Invoke plugin's callback functions
7878 * @param string $type plugin type e.g. 'mod'
7879 * @param string $name plugin name
7880 * @param string $feature feature name
7881 * @param string $action feature's action
7882 * @param array $params parameters of callback function, should be an array
7883 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7886 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7888 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7889 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7893 * Invoke component's callback functions
7895 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7896 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7897 * @param array $params parameters of callback function
7898 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7901 function component_callback($component, $function, array $params = array(), $default = null) {
7903 $functionname = component_callback_exists($component, $function);
7905 if ($params && (array_keys($params) !== range(0, count($params) - 1))) {
7906 // PHP 8 allows to have associative arrays in the call_user_func_array() parameters but
7907 // PHP 7 does not. Using associative arrays can result in different behavior in different PHP versions.
7908 // See https://php.watch/versions/8.0/named-parameters#named-params-call_user_func_array
7909 // This check can be removed when minimum PHP version for Moodle is raised to 8.
7910 debugging('Parameters array can not be an associative array while Moodle supports both PHP 7 and PHP 8.',
7912 $params = array_values($params);
7915 if ($functionname) {
7916 // Function exists, so just return function result.
7917 $ret = call_user_func_array($functionname, $params);
7918 if (is_null($ret)) {
7928 * Determine if a component callback exists and return the function name to call. Note that this
7929 * function will include the required library files so that the functioname returned can be
7932 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7933 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7934 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7935 * @throws coding_exception if invalid component specfied
7937 function component_callback_exists($component, $function) {
7938 global $CFG; // This is needed for the inclusions.
7940 $cleancomponent = clean_param($component, PARAM_COMPONENT
);
7941 if (empty($cleancomponent)) {
7942 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7944 $component = $cleancomponent;
7946 list($type, $name) = core_component
::normalize_component($component);
7947 $component = $type . '_' . $name;
7949 $oldfunction = $name.'_'.$function;
7950 $function = $component.'_'.$function;
7952 $dir = core_component
::get_component_directory($component);
7954 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7957 // Load library and look for function.
7958 if (file_exists($dir.'/lib.php')) {
7959 require_once($dir.'/lib.php');
7962 if (!function_exists($function) and function_exists($oldfunction)) {
7963 if ($type !== 'mod' and $type !== 'core') {
7964 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER
);
7966 $function = $oldfunction;
7969 if (function_exists($function)) {
7976 * Call the specified callback method on the provided class.
7978 * If the callback returns null, then the default value is returned instead.
7979 * If the class does not exist, then the default value is returned.
7981 * @param string $classname The name of the class to call upon.
7982 * @param string $methodname The name of the staticically defined method on the class.
7983 * @param array $params The arguments to pass into the method.
7984 * @param mixed $default The default value.
7985 * @return mixed The return value.
7987 function component_class_callback($classname, $methodname, array $params, $default = null) {
7988 if (!class_exists($classname)) {
7992 if (!method_exists($classname, $methodname)) {
7996 $fullfunction = $classname . '::' . $methodname;
7997 $result = call_user_func_array($fullfunction, $params);
7999 if (null === $result) {
8007 * Checks whether a plugin supports a specified feature.
8009 * @param string $type Plugin type e.g. 'mod'
8010 * @param string $name Plugin name e.g. 'forum'
8011 * @param string $feature Feature code (FEATURE_xx constant)
8012 * @param mixed $default default value if feature support unknown
8013 * @return mixed Feature result (false if not supported, null if feature is unknown,
8014 * otherwise usually true but may have other feature-specific value such as array)
8015 * @throws coding_exception
8017 function plugin_supports($type, $name, $feature, $default = null) {
8020 if ($type === 'mod' and $name === 'NEWMODULE') {
8021 // Somebody forgot to rename the module template.
8025 $component = clean_param($type . '_' . $name, PARAM_COMPONENT
);
8026 if (empty($component)) {
8027 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8032 if ($type === 'mod') {
8033 // We need this special case because we support subplugins in modules,
8034 // otherwise it would end up in infinite loop.
8035 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8036 include_once("$CFG->dirroot/mod/$name/lib.php");
8037 $function = $component.'_supports';
8038 if (!function_exists($function)) {
8039 // Legacy non-frankenstyle function name.
8040 $function = $name.'_supports';
8045 if (!$path = core_component
::get_plugin_directory($type, $name)) {
8046 // Non existent plugin type.
8049 if (file_exists("$path/lib.php")) {
8050 include_once("$path/lib.php");
8051 $function = $component.'_supports';
8055 if ($function and function_exists($function)) {
8056 $supports = $function($feature);
8057 if (is_null($supports)) {
8058 // Plugin does not know - use default.
8065 // Plugin does not care, so use default.
8070 * Returns true if the current version of PHP is greater that the specified one.
8072 * @todo Check PHP version being required here is it too low?
8074 * @param string $version The version of php being tested.
8077 function check_php_version($version='5.2.4') {
8078 return (version_compare(phpversion(), $version) >= 0);
8082 * Determine if moodle installation requires update.
8084 * Checks version numbers of main code and all plugins to see
8085 * if there are any mismatches.
8089 function moodle_needs_upgrading() {
8092 if (empty($CFG->version
)) {
8096 // There is no need to purge plugininfo caches here because
8097 // these caches are not used during upgrade and they are purged after
8100 if (empty($CFG->allversionshash
)) {
8104 $hash = core_component
::get_all_versions_hash();
8106 return ($hash !== $CFG->allversionshash
);
8110 * Returns the major version of this site
8112 * Moodle version numbers consist of three numbers separated by a dot, for
8113 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
8114 * called major version. This function extracts the major version from either
8115 * $CFG->release (default) or eventually from the $release variable defined in
8116 * the main version.php.
8118 * @param bool $fromdisk should the version if source code files be used
8119 * @return string|false the major version like '2.3', false if could not be determined
8121 function moodle_major_version($fromdisk = false) {
8126 require($CFG->dirroot
.'/version.php');
8127 if (empty($release)) {
8132 if (empty($CFG->release
)) {
8135 $release = $CFG->release
;
8138 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8148 * Gets the system locale
8150 * @return string Retuns the current locale.
8152 function moodle_getlocale() {
8155 // Fetch the correct locale based on ostype.
8156 if ($CFG->ostype
== 'WINDOWS') {
8157 $stringtofetch = 'localewin';
8159 $stringtofetch = 'locale';
8162 if (!empty($CFG->locale
)) { // Override locale for all language packs.
8163 return $CFG->locale
;
8166 return get_string($stringtofetch, 'langconfig');
8170 * Sets the system locale
8173 * @param string $locale Can be used to force a locale
8175 function moodle_setlocale($locale='') {
8178 static $currentlocale = ''; // Last locale caching.
8180 $oldlocale = $currentlocale;
8182 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8183 if (!empty($locale)) {
8184 $currentlocale = $locale;
8186 $currentlocale = moodle_getlocale();
8189 // Do nothing if locale already set up.
8190 if ($oldlocale == $currentlocale) {
8194 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8195 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8196 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8198 // Get current values.
8199 $monetary= setlocale (LC_MONETARY
, 0);
8200 $numeric = setlocale (LC_NUMERIC
, 0);
8201 $ctype = setlocale (LC_CTYPE
, 0);
8202 if ($CFG->ostype
!= 'WINDOWS') {
8203 $messages= setlocale (LC_MESSAGES
, 0);
8205 // Set locale to all.
8206 $result = setlocale (LC_ALL
, $currentlocale);
8207 // If setting of locale fails try the other utf8 or utf-8 variant,
8208 // some operating systems support both (Debian), others just one (OSX).
8209 if ($result === false) {
8210 if (stripos($currentlocale, '.UTF-8') !== false) {
8211 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8212 setlocale (LC_ALL
, $newlocale);
8213 } else if (stripos($currentlocale, '.UTF8') !== false) {
8214 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8215 setlocale (LC_ALL
, $newlocale);
8219 setlocale (LC_MONETARY
, $monetary);
8220 setlocale (LC_NUMERIC
, $numeric);
8221 if ($CFG->ostype
!= 'WINDOWS') {
8222 setlocale (LC_MESSAGES
, $messages);
8224 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8225 // To workaround a well-known PHP problem with Turkish letter Ii.
8226 setlocale (LC_CTYPE
, $ctype);
8231 * Count words in a string.
8233 * Words are defined as things between whitespace.
8236 * @param string $string The text to be searched for words. May be HTML.
8237 * @return int The count of words in the specified string
8239 function count_words($string) {
8240 // Before stripping tags, add a space after the close tag of anything that is not obviously inline.
8241 // Also, br is a special case because it definitely delimits a word, but has no close tag.
8242 $string = preg_replace('~
8243 ( # Capture the tag we match.
8244 </ # Start of close tag.
8245 (?! # Do not match any of these specific close tag names.
8246 a> | b> | del> | em> | i> |
8247 ins> | s> | small> |
8248 strong> | sub> | sup> | u>
8250 \w+ # But, apart from those execptions, match any tag name.
8251 > # End of close tag.
8253 <br> | <br\s*/> # Special cases that are not close tags.
8255 ~x', '$1 ', $string); // Add a space after the close tag.
8256 // Now remove HTML tags.
8257 $string = strip_tags($string);
8258 // Decode HTML entities.
8259 $string = html_entity_decode($string);
8261 // Now, the word count is the number of blocks of characters separated
8262 // by any sort of space. That seems to be the definition used by all other systems.
8263 // To be precise about what is considered to separate words:
8264 // * Anything that Unicode considers a 'Separator'
8265 // * Anything that Unicode considers a 'Control character'
8266 // * An em- or en- dash.
8267 return count(preg_split('~[\p{Z}\p{Cc}—–]+~u', $string, -1, PREG_SPLIT_NO_EMPTY
));
8271 * Count letters in a string.
8273 * Letters are defined as chars not in tags and different from whitespace.
8276 * @param string $string The text to be searched for letters. May be HTML.
8277 * @return int The count of letters in the specified text.
8279 function count_letters($string) {
8280 $string = strip_tags($string); // Tags are out now.
8281 $string = html_entity_decode($string);
8282 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8284 return core_text
::strlen($string);
8288 * Generate and return a random string of the specified length.
8290 * @param int $length The length of the string to be created.
8293 function random_string($length=15) {
8294 $randombytes = random_bytes_emulate($length);
8295 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8296 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8297 $pool .= '0123456789';
8298 $poollen = strlen($pool);
8300 for ($i = 0; $i < $length; $i++
) {
8301 $rand = ord($randombytes[$i]);
8302 $string .= substr($pool, ($rand%
($poollen)), 1);
8308 * Generate a complex random string (useful for md5 salts)
8310 * This function is based on the above {@link random_string()} however it uses a
8311 * larger pool of characters and generates a string between 24 and 32 characters
8313 * @param int $length Optional if set generates a string to exactly this length
8316 function complex_random_string($length=null) {
8317 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8318 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8319 $poollen = strlen($pool);
8320 if ($length===null) {
8321 $length = floor(rand(24, 32));
8323 $randombytes = random_bytes_emulate($length);
8325 for ($i = 0; $i < $length; $i++
) {
8326 $rand = ord($randombytes[$i]);
8327 $string .= $pool[($rand%
$poollen)];
8333 * Try to generates cryptographically secure pseudo-random bytes.
8335 * Note this is achieved by fallbacking between:
8336 * - PHP 7 random_bytes().
8337 * - OpenSSL openssl_random_pseudo_bytes().
8338 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8340 * @param int $length requested length in bytes
8341 * @return string binary data
8343 function random_bytes_emulate($length) {
8346 debugging('Invalid random bytes length', DEBUG_DEVELOPER
);
8349 if (function_exists('random_bytes')) {
8350 // Use PHP 7 goodness.
8351 $hash = @random_bytes
($length);
8352 if ($hash !== false) {
8356 if (function_exists('openssl_random_pseudo_bytes')) {
8357 // If you have the openssl extension enabled.
8358 $hash = openssl_random_pseudo_bytes($length);
8359 if ($hash !== false) {
8364 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8365 $staticdata = serialize($CFG) . serialize($_SERVER);
8368 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8369 } while (strlen($hash) < $length);
8371 return substr($hash, 0, $length);
8375 * Given some text (which may contain HTML) and an ideal length,
8376 * this function truncates the text neatly on a word boundary if possible
8379 * @param string $text text to be shortened
8380 * @param int $ideal ideal string length
8381 * @param boolean $exact if false, $text will not be cut mid-word
8382 * @param string $ending The string to append if the passed string is truncated
8383 * @return string $truncate shortened string
8385 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8386 // If the plain text is shorter than the maximum length, return the whole text.
8387 if (core_text
::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8391 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8392 // and only tag in its 'line'.
8393 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER
);
8395 $totallength = core_text
::strlen($ending);
8398 // This array stores information about open and close tags and their position
8399 // in the truncated string. Each item in the array is an object with fields
8400 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8401 // (byte position in truncated text).
8402 $tagdetails = array();
8404 foreach ($lines as $linematchings) {
8405 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8406 if (!empty($linematchings[1])) {
8407 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8408 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8409 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8410 // Record closing tag.
8411 $tagdetails[] = (object) array(
8413 'tag' => core_text
::strtolower($tagmatchings[1]),
8414 'pos' => core_text
::strlen($truncate),
8417 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8418 // Record opening tag.
8419 $tagdetails[] = (object) array(
8421 'tag' => core_text
::strtolower($tagmatchings[1]),
8422 'pos' => core_text
::strlen($truncate),
8424 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8425 $tagdetails[] = (object) array(
8427 'tag' => core_text
::strtolower('if'),
8428 'pos' => core_text
::strlen($truncate),
8430 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8431 $tagdetails[] = (object) array(
8433 'tag' => core_text
::strtolower('if'),
8434 'pos' => core_text
::strlen($truncate),
8438 // Add html-tag to $truncate'd text.
8439 $truncate .= $linematchings[1];
8442 // Calculate the length of the plain text part of the line; handle entities as one character.
8443 $contentlength = core_text
::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8444 if ($totallength +
$contentlength > $ideal) {
8445 // The number of characters which are left.
8446 $left = $ideal - $totallength;
8447 $entitieslength = 0;
8448 // Search for html entities.
8449 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
)) {
8450 // Calculate the real length of all entities in the legal range.
8451 foreach ($entities[0] as $entity) {
8452 if ($entity[1]+
1-$entitieslength <= $left) {
8454 $entitieslength +
= core_text
::strlen($entity[0]);
8456 // No more characters left.
8461 $breakpos = $left +
$entitieslength;
8463 // If the words shouldn't be cut in the middle...
8465 // Search the last occurence of a space.
8466 for (; $breakpos > 0; $breakpos--) {
8467 if ($char = core_text
::substr($linematchings[2], $breakpos, 1)) {
8468 if ($char === '.' or $char === ' ') {
8471 } else if (strlen($char) > 2) {
8472 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8479 if ($breakpos == 0) {
8480 // This deals with the test_shorten_text_no_spaces case.
8481 $breakpos = $left +
$entitieslength;
8482 } else if ($breakpos > $left +
$entitieslength) {
8483 // This deals with the previous for loop breaking on the first char.
8484 $breakpos = $left +
$entitieslength;
8487 $truncate .= core_text
::substr($linematchings[2], 0, $breakpos);
8488 // Maximum length is reached, so get off the loop.
8491 $truncate .= $linematchings[2];
8492 $totallength +
= $contentlength;
8495 // If the maximum length is reached, get off the loop.
8496 if ($totallength >= $ideal) {
8501 // Add the defined ending to the text.
8502 $truncate .= $ending;
8504 // Now calculate the list of open html tags based on the truncate position.
8505 $opentags = array();
8506 foreach ($tagdetails as $taginfo) {
8507 if ($taginfo->open
) {
8508 // Add tag to the beginning of $opentags list.
8509 array_unshift($opentags, $taginfo->tag
);
8511 // Can have multiple exact same open tags, close the last one.
8512 $pos = array_search($taginfo->tag
, array_reverse($opentags, true));
8513 if ($pos !== false) {
8514 unset($opentags[$pos]);
8519 // Close all unclosed html-tags.
8520 foreach ($opentags as $tag) {
8521 if ($tag === 'if') {
8522 $truncate .= '<!--<![endif]-->';
8524 $truncate .= '</' . $tag . '>';
8532 * Shortens a given filename by removing characters positioned after the ideal string length.
8533 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8534 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8536 * @param string $filename file name
8537 * @param int $length ideal string length
8538 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8539 * @return string $shortened shortened file name
8541 function shorten_filename($filename, $length = MAX_FILENAME_SIZE
, $includehash = false) {
8542 $shortened = $filename;
8543 // Extract a part of the filename if it's char size exceeds the ideal string length.
8544 if (core_text
::strlen($filename) > $length) {
8545 // Exclude extension if present in filename.
8546 $mimetypes = get_mimetypes_array();
8547 $extension = pathinfo($filename, PATHINFO_EXTENSION
);
8548 if ($extension && !empty($mimetypes[$extension])) {
8549 $basename = pathinfo($filename, PATHINFO_FILENAME
);
8550 $hash = empty($includehash) ?
'' : ' - ' . substr(sha1($basename), 0, 10);
8551 $shortened = core_text
::substr($basename, 0, $length - strlen($hash)) . $hash;
8552 $shortened .= '.' . $extension;
8554 $hash = empty($includehash) ?
'' : ' - ' . substr(sha1($filename), 0, 10);
8555 $shortened = core_text
::substr($filename, 0, $length - strlen($hash)) . $hash;
8562 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8564 * @param array $path The paths to reduce the length.
8565 * @param int $length Ideal string length
8566 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8567 * @return array $result Shortened paths in array.
8569 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE
, $includehash = false) {
8572 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8573 $carry[] = shorten_filename($singlepath, $length, $includehash);
8581 * Given dates in seconds, how many weeks is the date from startdate
8582 * The first week is 1, the second 2 etc ...
8584 * @param int $startdate Timestamp for the start date
8585 * @param int $thedate Timestamp for the end date
8588 function getweek ($startdate, $thedate) {
8589 if ($thedate < $startdate) {
8593 return floor(($thedate - $startdate) / WEEKSECS
) +
1;
8597 * Returns a randomly generated password of length $maxlen. inspired by
8599 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8600 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8602 * @param int $maxlen The maximum size of the password being generated.
8605 function generate_password($maxlen=10) {
8608 if (empty($CFG->passwordpolicy
)) {
8609 $fillers = PASSWORD_DIGITS
;
8610 $wordlist = file($CFG->wordlist
);
8611 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8612 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8613 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8614 $password = $word1 . $filler1 . $word2;
8616 $minlen = !empty($CFG->minpasswordlength
) ?
$CFG->minpasswordlength
: 0;
8617 $digits = $CFG->minpassworddigits
;
8618 $lower = $CFG->minpasswordlower
;
8619 $upper = $CFG->minpasswordupper
;
8620 $nonalphanum = $CFG->minpasswordnonalphanum
;
8621 $total = $lower +
$upper +
$digits +
$nonalphanum;
8622 // Var minlength should be the greater one of the two ( $minlen and $total ).
8623 $minlen = $minlen < $total ?
$total : $minlen;
8624 // Var maxlen can never be smaller than minlen.
8625 $maxlen = $minlen > $maxlen ?
$minlen : $maxlen;
8626 $additional = $maxlen - $total;
8628 // Make sure we have enough characters to fulfill
8629 // complexity requirements.
8630 $passworddigits = PASSWORD_DIGITS
;
8631 while ($digits > strlen($passworddigits)) {
8632 $passworddigits .= PASSWORD_DIGITS
;
8634 $passwordlower = PASSWORD_LOWER
;
8635 while ($lower > strlen($passwordlower)) {
8636 $passwordlower .= PASSWORD_LOWER
;
8638 $passwordupper = PASSWORD_UPPER
;
8639 while ($upper > strlen($passwordupper)) {
8640 $passwordupper .= PASSWORD_UPPER
;
8642 $passwordnonalphanum = PASSWORD_NONALPHANUM
;
8643 while ($nonalphanum > strlen($passwordnonalphanum)) {
8644 $passwordnonalphanum .= PASSWORD_NONALPHANUM
;
8647 // Now mix and shuffle it all.
8648 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8649 substr(str_shuffle ($passwordupper), 0, $upper) .
8650 substr(str_shuffle ($passworddigits), 0, $digits) .
8651 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8652 substr(str_shuffle ($passwordlower .
8655 $passwordnonalphanum), 0 , $additional));
8658 return substr ($password, 0, $maxlen);
8662 * Given a float, prints it nicely.
8663 * Localized floats must not be used in calculations!
8665 * The stripzeros feature is intended for making numbers look nicer in small
8666 * areas where it is not necessary to indicate the degree of accuracy by showing
8667 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8668 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8670 * @param float $float The float to print
8671 * @param int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision).
8672 * @param bool $localized use localized decimal separator
8673 * @param bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after
8674 * the decimal point are always striped if $decimalpoints is -1.
8675 * @return string locale float
8677 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8678 if (is_null($float)) {
8682 $separator = get_string('decsep', 'langconfig');
8686 if ($decimalpoints == -1) {
8687 // The following counts the number of decimals.
8688 // It is safe as both floatval() and round() functions have same behaviour when non-numeric values are provided.
8689 $floatval = floatval($float);
8690 for ($decimalpoints = 0; $floatval != round($float, $decimalpoints); $decimalpoints++
);
8693 $result = number_format($float, $decimalpoints, $separator, '');
8695 // Remove zeros and final dot if not needed.
8696 $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
8702 * Converts locale specific floating point/comma number back to standard PHP float value
8703 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8705 * @param string $localefloat locale aware float representation
8706 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8707 * @return mixed float|bool - false or the parsed float.
8709 function unformat_float($localefloat, $strict = false) {
8710 $localefloat = trim($localefloat);
8712 if ($localefloat == '') {
8716 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8717 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8719 if ($strict && !is_numeric($localefloat)) {
8723 return (float)$localefloat;
8727 * Given a simple array, this shuffles it up just like shuffle()
8728 * Unlike PHP's shuffle() this function works on any machine.
8730 * @param array $array The array to be rearranged
8733 function swapshuffle($array) {
8735 $last = count($array) - 1;
8736 for ($i = 0; $i <= $last; $i++
) {
8737 $from = rand(0, $last);
8739 $array[$i] = $array[$from];
8740 $array[$from] = $curr;
8746 * Like {@link swapshuffle()}, but works on associative arrays
8748 * @param array $array The associative array to be rearranged
8751 function swapshuffle_assoc($array) {
8753 $newarray = array();
8754 $newkeys = swapshuffle(array_keys($array));
8756 foreach ($newkeys as $newkey) {
8757 $newarray[$newkey] = $array[$newkey];
8763 * Given an arbitrary array, and a number of draws,
8764 * this function returns an array with that amount
8765 * of items. The indexes are retained.
8767 * @todo Finish documenting this function
8769 * @param array $array
8773 function draw_rand_array($array, $draws) {
8777 $last = count($array);
8779 if ($draws > $last) {
8783 while ($draws > 0) {
8786 $keys = array_keys($array);
8787 $rand = rand(0, $last);
8789 $return[$keys[$rand]] = $array[$keys[$rand]];
8790 unset($array[$keys[$rand]]);
8799 * Calculate the difference between two microtimes
8801 * @param string $a The first Microtime
8802 * @param string $b The second Microtime
8805 function microtime_diff($a, $b) {
8806 list($adec, $asec) = explode(' ', $a);
8807 list($bdec, $bsec) = explode(' ', $b);
8808 return $bsec - $asec +
$bdec - $adec;
8812 * Given a list (eg a,b,c,d,e) this function returns
8813 * an array of 1->a, 2->b, 3->c etc
8815 * @param string $list The string to explode into array bits
8816 * @param string $separator The separator used within the list string
8817 * @return array The now assembled array
8819 function make_menu_from_list($list, $separator=',') {
8821 $array = array_reverse(explode($separator, $list), true);
8822 foreach ($array as $key => $item) {
8823 $outarray[$key+
1] = trim($item);
8829 * Creates an array that represents all the current grades that
8830 * can be chosen using the given grading type.
8833 * are scales, zero is no grade, and positive numbers are maximum
8836 * @todo Finish documenting this function or better deprecated this completely!
8838 * @param int $gradingtype
8841 function make_grades_menu($gradingtype) {
8845 if ($gradingtype < 0) {
8846 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8847 return make_menu_from_list($scale->scale
);
8849 } else if ($gradingtype > 0) {
8850 for ($i=$gradingtype; $i>=0; $i--) {
8851 $grades[$i] = $i .' / '. $gradingtype;
8859 * make_unique_id_code
8861 * @todo Finish documenting this function
8864 * @param string $extra Extra string to append to the end of the code
8867 function make_unique_id_code($extra = '') {
8869 $hostname = 'unknownhost';
8870 if (!empty($_SERVER['HTTP_HOST'])) {
8871 $hostname = $_SERVER['HTTP_HOST'];
8872 } else if (!empty($_ENV['HTTP_HOST'])) {
8873 $hostname = $_ENV['HTTP_HOST'];
8874 } else if (!empty($_SERVER['SERVER_NAME'])) {
8875 $hostname = $_SERVER['SERVER_NAME'];
8876 } else if (!empty($_ENV['SERVER_NAME'])) {
8877 $hostname = $_ENV['SERVER_NAME'];
8880 $date = gmdate("ymdHis");
8882 $random = random_string(6);
8885 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8887 return $hostname .'+'. $date .'+'. $random;
8893 * Function to check the passed address is within the passed subnet
8895 * The parameter is a comma separated string of subnet definitions.
8896 * Subnet strings can be in one of three formats:
8897 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8898 * 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)
8899 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8900 * Code for type 1 modified from user posted comments by mediator at
8901 * {@link http://au.php.net/manual/en/function.ip2long.php}
8903 * @param string $addr The address you are checking
8904 * @param string $subnetstr The string of subnet addresses
8907 function address_in_subnet($addr, $subnetstr) {
8909 if ($addr == '0.0.0.0') {
8912 $subnets = explode(',', $subnetstr);
8914 $addr = trim($addr);
8915 $addr = cleanremoteaddr($addr, false); // Normalise.
8916 if ($addr === null) {
8919 $addrparts = explode(':', $addr);
8921 $ipv6 = strpos($addr, ':');
8923 foreach ($subnets as $subnet) {
8924 $subnet = trim($subnet);
8925 if ($subnet === '') {
8929 if (strpos($subnet, '/') !== false) {
8930 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8931 list($ip, $mask) = explode('/', $subnet);
8932 $mask = trim($mask);
8933 if (!is_number($mask)) {
8934 continue; // Incorect mask number, eh?
8936 $ip = cleanremoteaddr($ip, false); // Normalise.
8940 if (strpos($ip, ':') !== false) {
8945 if ($mask > 128 or $mask < 0) {
8946 continue; // Nonsense.
8949 return true; // Any address.
8952 if ($ip === $addr) {
8957 $ipparts = explode(':', $ip);
8958 $modulo = $mask %
16;
8959 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8960 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8961 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8965 $pos = ($mask-$modulo)/16;
8966 $ipnet = hexdec($ipparts[$pos]);
8967 $addrnet = hexdec($addrparts[$pos]);
8968 $mask = 0xffff << (16 - $modulo);
8969 if (($addrnet & $mask) == ($ipnet & $mask)) {
8979 if ($mask > 32 or $mask < 0) {
8980 continue; // Nonsense.
8986 if ($ip === $addr) {
8991 $mask = 0xffffffff << (32 - $mask);
8992 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8997 } else if (strpos($subnet, '-') !== false) {
8998 // 2: xxx.xxx.xxx.xxx-yyy or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy. A range of IP addresses in the last group.
8999 $parts = explode('-', $subnet);
9000 if (count($parts) != 2) {
9004 if (strpos($subnet, ':') !== false) {
9009 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9010 if ($ipstart === null) {
9013 $ipparts = explode(':', $ipstart);
9014 $start = hexdec(array_pop($ipparts));
9015 $ipparts[] = trim($parts[1]);
9016 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
9017 if ($ipend === null) {
9021 $ipnet = implode(':', $ipparts);
9022 if (strpos($addr, $ipnet) !== 0) {
9025 $ipparts = explode(':', $ipend);
9026 $end = hexdec($ipparts[7]);
9028 $addrend = hexdec($addrparts[7]);
9030 if (($addrend >= $start) and ($addrend <= $end)) {
9039 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9040 if ($ipstart === null) {
9043 $ipparts = explode('.', $ipstart);
9044 $ipparts[3] = trim($parts[1]);
9045 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
9046 if ($ipend === null) {
9050 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9056 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9057 if (strpos($subnet, ':') !== false) {
9062 $parts = explode(':', $subnet);
9063 $count = count($parts);
9064 if ($parts[$count-1] === '') {
9065 unset($parts[$count-1]); // Trim trailing :'s.
9067 $subnet = implode('.', $parts);
9069 $isip = cleanremoteaddr($subnet, false); // Normalise.
9070 if ($isip !== null) {
9071 if ($isip === $addr) {
9075 } else if ($count > 8) {
9078 $zeros = array_fill(0, 8-$count, '0');
9079 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9080 if (address_in_subnet($addr, $subnet)) {
9089 $parts = explode('.', $subnet);
9090 $count = count($parts);
9091 if ($parts[$count-1] === '') {
9092 unset($parts[$count-1]); // Trim trailing .
9094 $subnet = implode('.', $parts);
9097 $subnet = cleanremoteaddr($subnet, false); // Normalise.
9098 if ($subnet === $addr) {
9102 } else if ($count > 4) {
9105 $zeros = array_fill(0, 4-$count, '0');
9106 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9107 if (address_in_subnet($addr, $subnet)) {
9118 * For outputting debugging info
9120 * @param string $string The string to write
9121 * @param string $eol The end of line char(s) to use
9122 * @param string $sleep Period to make the application sleep
9123 * This ensures any messages have time to display before redirect
9125 function mtrace($string, $eol="\n", $sleep=0) {
9128 if (isset($CFG->mtrace_wrapper
) && function_exists($CFG->mtrace_wrapper
)) {
9129 $fn = $CFG->mtrace_wrapper
;
9132 } else if (defined('STDOUT') && !PHPUNIT_TEST
&& !defined('BEHAT_TEST')) {
9133 // We must explicitly call the add_line function here.
9134 // Uses of fwrite to STDOUT are not picked up by ob_start.
9135 if ($output = \core\task\logmanager
::add_line("{$string}{$eol}")) {
9136 fwrite(STDOUT
, $output);
9139 echo $string . $eol;
9145 // Delay to keep message on user's screen in case of subsequent redirect.
9152 * Replace 1 or more slashes or backslashes to 1 slash
9154 * @param string $path The path to strip
9155 * @return string the path with double slashes removed
9157 function cleardoubleslashes ($path) {
9158 return preg_replace('/(\/|\\\){1,}/', '/', $path);
9162 * Is the current ip in a given list?
9164 * @param string $list
9167 function remoteip_in_list($list) {
9168 $clientip = getremoteaddr(null);
9171 // Ensure access on cli.
9174 return \core\ip_utils
::is_ip_in_subnet_list($clientip, $list);
9178 * Returns most reliable client address
9180 * @param string $default If an address can't be determined, then return this
9181 * @return string The remote IP address
9183 function getremoteaddr($default='0.0.0.0') {
9186 if (!isset($CFG->getremoteaddrconf
)) {
9187 // This will happen, for example, before just after the upgrade, as the
9188 // user is redirected to the admin screen.
9189 $variablestoskip = GETREMOTEADDR_SKIP_DEFAULT
;
9191 $variablestoskip = $CFG->getremoteaddrconf
;
9193 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP
)) {
9194 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9195 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9196 return $address ?
$address : $default;
9199 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR
)) {
9200 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9201 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9203 $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
9205 return !\core\ip_utils
::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore ??
'', ',');
9208 // Multiple proxies can append values to this header including an
9209 // untrusted original request header so we must only trust the last ip.
9210 $address = end($forwardedaddresses);
9212 if (substr_count($address, ":") > 1) {
9213 // Remove port and brackets from IPv6.
9214 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9215 $address = $matches[1];
9218 // Remove port from IPv4.
9219 if (substr_count($address, ":") == 1) {
9220 $parts = explode(":", $address);
9221 $address = $parts[0];
9225 $address = cleanremoteaddr($address);
9226 return $address ?
$address : $default;
9229 if (!empty($_SERVER['REMOTE_ADDR'])) {
9230 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9231 return $address ?
$address : $default;
9238 * Cleans an ip address. Internal addresses are now allowed.
9239 * (Originally local addresses were not allowed.)
9241 * @param string $addr IPv4 or IPv6 address
9242 * @param bool $compress use IPv6 address compression
9243 * @return string normalised ip address string, null if error
9245 function cleanremoteaddr($addr, $compress=false) {
9246 $addr = trim($addr);
9248 if (strpos($addr, ':') !== false) {
9249 // Can be only IPv6.
9250 $parts = explode(':', $addr);
9251 $count = count($parts);
9253 if (strpos($parts[$count-1], '.') !== false) {
9254 // Legacy ipv4 notation.
9255 $last = array_pop($parts);
9256 $ipv4 = cleanremoteaddr($last, true);
9257 if ($ipv4 === null) {
9260 $bits = explode('.', $ipv4);
9261 $parts[] = dechex($bits[0]).dechex($bits[1]);
9262 $parts[] = dechex($bits[2]).dechex($bits[3]);
9263 $count = count($parts);
9264 $addr = implode(':', $parts);
9267 if ($count < 3 or $count > 8) {
9268 return null; // Severly malformed.
9272 if (strpos($addr, '::') === false) {
9273 return null; // Malformed.
9276 $insertat = array_search('', $parts, true);
9277 $missing = array_fill(0, 1 +
8 - $count, '0');
9278 array_splice($parts, $insertat, 1, $missing);
9279 foreach ($parts as $key => $part) {
9286 $adr = implode(':', $parts);
9287 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9288 return null; // Incorrect format - sorry.
9291 // Normalise 0s and case.
9292 $parts = array_map('hexdec', $parts);
9293 $parts = array_map('dechex', $parts);
9295 $result = implode(':', $parts);
9301 if ($result === '0:0:0:0:0:0:0:0') {
9302 return '::'; // All addresses.
9305 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9306 if ($compressed !== $result) {
9310 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9311 if ($compressed !== $result) {
9315 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9316 if ($compressed !== $result) {
9323 // First get all things that look like IPv4 addresses.
9325 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9330 foreach ($parts as $key => $match) {
9334 $parts[$key] = (int)$match; // Normalise 0s.
9337 return implode('.', $parts);
9342 * Is IP address a public address?
9344 * @param string $ip The ip to check
9345 * @return bool true if the ip is public
9347 function ip_is_public($ip) {
9348 return (bool) filter_var($ip, FILTER_VALIDATE_IP
, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
));
9352 * This function will make a complete copy of anything it's given,
9353 * regardless of whether it's an object or not.
9355 * @param mixed $thing Something you want cloned
9356 * @return mixed What ever it is you passed it
9358 function fullclone($thing) {
9359 return unserialize(serialize($thing));
9363 * Used to make sure that $min <= $value <= $max
9365 * Make sure that value is between min, and max
9367 * @param int $min The minimum value
9368 * @param int $value The value to check
9369 * @param int $max The maximum value
9372 function bounded_number($min, $value, $max) {
9373 if ($value < $min) {
9376 if ($value > $max) {
9383 * Check if there is a nested array within the passed array
9385 * @param array $array
9386 * @return bool true if there is a nested array false otherwise
9388 function array_is_nested($array) {
9389 foreach ($array as $value) {
9390 if (is_array($value)) {
9398 * get_performance_info() pairs up with init_performance_info()
9399 * loaded in setup.php. Returns an array with 'html' and 'txt'
9400 * values ready for use, and each of the individual stats provided
9401 * separately as well.
9405 function get_performance_info() {
9406 global $CFG, $PERF, $DB, $PAGE;
9409 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9412 if (!empty($CFG->themedesignermode
)) {
9413 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9414 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9416 $info['html'] .= '<ul class="list-unstyled row mx-md-0">'; // Holds userfriendly HTML representation.
9418 $info['realtime'] = microtime_diff($PERF->starttime
, microtime());
9420 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9421 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9423 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9424 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ??
"NULL") . ' ';
9426 if (function_exists('memory_get_usage')) {
9427 $info['memory_total'] = memory_get_usage();
9428 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory
;
9429 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9430 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9431 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9434 if (function_exists('memory_get_peak_usage')) {
9435 $info['memory_peak'] = memory_get_peak_usage();
9436 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9437 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9440 $info['html'] .= '</ul><ul class="list-unstyled row mx-md-0">';
9441 $inc = get_included_files();
9442 $info['includecount'] = count($inc);
9443 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9444 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9446 if (!empty($CFG->early_install_lang
) or empty($PAGE)) {
9447 // We can not track more performance before installation or before PAGE init, sorry.
9451 $filtermanager = filter_manager
::instance();
9452 if (method_exists($filtermanager, 'get_performance_summary')) {
9453 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9454 $info = array_merge($filterinfo, $info);
9455 foreach ($filterinfo as $key => $value) {
9456 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9457 $info['txt'] .= "$key: $value ";
9461 $stringmanager = get_string_manager();
9462 if (method_exists($stringmanager, 'get_performance_summary')) {
9463 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9464 $info = array_merge($filterinfo, $info);
9465 foreach ($filterinfo as $key => $value) {
9466 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9467 $info['txt'] .= "$key: $value ";
9471 if (!empty($PERF->logwrites
)) {
9472 $info['logwrites'] = $PERF->logwrites
;
9473 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9474 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9477 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites
);
9478 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9479 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9481 if ($DB->want_read_slave()) {
9482 $info['dbreads_slave'] = $DB->perf_get_reads_slave();
9483 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads from slave: '.$info['dbreads_slave'].'</li> ';
9484 $info['txt'] .= 'db reads from slave: '.$info['dbreads_slave'].' ';
9487 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9488 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9489 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9491 if (function_exists('posix_times')) {
9492 $ptimes = posix_times();
9493 if (is_array($ptimes)) {
9494 foreach ($ptimes as $key => $val) {
9495 $info[$key] = $ptimes[$key] - $PERF->startposixtimes
[$key];
9497 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9498 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9499 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9503 // Grab the load average for the last minute.
9504 // /proc will only work under some linux configurations
9505 // while uptime is there under MacOSX/Darwin and other unices.
9506 if (is_readable('/proc/loadavg') && $loadavg = @file
('/proc/loadavg')) {
9507 list($serverload) = explode(' ', $loadavg[0]);
9509 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `
/usr
/bin
/uptime`
) {
9510 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9511 $serverload = $matches[1];
9513 trigger_error('Could not parse uptime output!');
9516 if (!empty($serverload)) {
9517 $info['serverload'] = $serverload;
9518 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9519 $info['txt'] .= "serverload: {$info['serverload']} ";
9522 // Display size of session if session started.
9523 if ($si = \core\session\manager
::get_performance_info()) {
9524 $info['sessionsize'] = $si['size'];
9525 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9526 $info['txt'] .= $si['txt'];
9529 $info['html'] .= '</ul>';
9531 if ($stats = cache_helper
::get_stats()) {
9533 $table = new html_table();
9534 $table->attributes
['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9535 $table->head
= ['Mode', 'Cache item', 'Static', 'H', 'M', get_string('mappingprimary', 'cache'), 'H', 'M', 'S'];
9537 $table->align
= ['left', 'left', 'left', 'right', 'right', 'left', 'right', 'right', 'right'];
9539 $text = 'Caches used (hits/misses/sets): ';
9545 // We want to align static caches into their own column.
9547 foreach ($stats as $definition => $details) {
9548 $numstores = count($details['stores']);
9549 $first = key($details['stores']);
9550 if ($first !== cache_store
::STATIC_ACCEL
) {
9551 $numstores++
; // Add a blank space for the missing static store.
9553 $maxstores = max($maxstores, $numstores);
9558 while ($storec++
< ($maxstores - 2)) {
9559 if ($storec == ($maxstores - 2)) {
9560 $table->head
[] = get_string('mappingfinal', 'cache');
9562 $table->head
[] = "Store $storec";
9564 $table->align
[] = 'left';
9565 $table->align
[] = 'right';
9566 $table->align
[] = 'right';
9567 $table->align
[] = 'right';
9568 $table->head
[] = 'H';
9569 $table->head
[] = 'M';
9570 $table->head
[] = 'S';
9575 foreach ($stats as $definition => $details) {
9576 switch ($details['mode']) {
9577 case cache_store
::MODE_APPLICATION
:
9578 $modeclass = 'application';
9579 $mode = ' <span title="application cache">App</span>';
9581 case cache_store
::MODE_SESSION
:
9582 $modeclass = 'session';
9583 $mode = ' <span title="session cache">Ses</span>';
9585 case cache_store
::MODE_REQUEST
:
9586 $modeclass = 'request';
9587 $mode = ' <span title="request cache">Req</span>';
9590 $row = [$mode, $definition];
9592 $text .= "$definition {";
9595 foreach ($details['stores'] as $store => $data) {
9597 if ($storec == 0 && $store !== cache_store
::STATIC_ACCEL
) {
9604 $hits +
= $data['hits'];
9605 $misses +
= $data['misses'];
9606 $sets +
= $data['sets'];
9607 if ($data['hits'] == 0 and $data['misses'] > 0) {
9608 $cachestoreclass = 'nohits bg-danger';
9609 } else if ($data['hits'] < $data['misses']) {
9610 $cachestoreclass = 'lowhits bg-warning text-dark';
9612 $cachestoreclass = 'hihits';
9614 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9615 $cell = new html_table_cell($store);
9616 $cell->attributes
= ['class' => $cachestoreclass];
9618 $cell = new html_table_cell($data['hits']);
9619 $cell->attributes
= ['class' => $cachestoreclass];
9621 $cell = new html_table_cell($data['misses']);
9622 $cell->attributes
= ['class' => $cachestoreclass];
9625 if ($store !== cache_store
::STATIC_ACCEL
) {
9626 // The static cache is never set.
9627 $cell = new html_table_cell($data['sets']);
9628 $cell->attributes
= ['class' => $cachestoreclass];
9633 while ($storec++
< $maxstores) {
9641 $table->data
[] = $row;
9644 $html .= html_writer
::table($table);
9646 // Now lets also show sub totals for each cache store.
9648 $storetotal = ['hits' => 0, 'misses' => 0, 'sets' => 0];
9649 foreach ($stats as $definition => $details) {
9650 foreach ($details['stores'] as $store => $data) {
9651 if (!array_key_exists($store, $storetotals)) {
9652 $storetotals[$store] = ['hits' => 0, 'misses' => 0, 'sets' => 0];
9654 $storetotals[$store]['class'] = $data['class'];
9655 $storetotals[$store]['hits'] +
= $data['hits'];
9656 $storetotals[$store]['misses'] +
= $data['misses'];
9657 $storetotals[$store]['sets'] +
= $data['sets'];
9658 $storetotal['hits'] +
= $data['hits'];
9659 $storetotal['misses'] +
= $data['misses'];
9660 $storetotal['sets'] +
= $data['sets'];
9664 $table = new html_table();
9665 $table->attributes
['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9666 $table->head
= [get_string('storename', 'cache'), get_string('type_cachestore', 'plugin'), 'H', 'M', 'S'];
9668 $table->align
= ['left', 'left', 'right', 'right', 'right'];
9670 ksort($storetotals);
9672 foreach ($storetotals as $store => $data) {
9674 if ($data['hits'] == 0 and $data['misses'] > 0) {
9675 $cachestoreclass = 'nohits bg-danger';
9676 } else if ($data['hits'] < $data['misses']) {
9677 $cachestoreclass = 'lowhits bg-warning text-dark';
9679 $cachestoreclass = 'hihits';
9681 $cell = new html_table_cell($store);
9682 $cell->attributes
= ['class' => $cachestoreclass];
9684 $cell = new html_table_cell($data['class']);
9685 $cell->attributes
= ['class' => $cachestoreclass];
9687 $cell = new html_table_cell($data['hits']);
9688 $cell->attributes
= ['class' => $cachestoreclass];
9690 $cell = new html_table_cell($data['misses']);
9691 $cell->attributes
= ['class' => $cachestoreclass];
9693 $cell = new html_table_cell($data['sets']);
9694 $cell->attributes
= ['class' => $cachestoreclass];
9696 $table->data
[] = $row;
9699 get_string('total'),
9701 $storetotal['hits'],
9702 $storetotal['misses'],
9703 $storetotal['sets'],
9705 $table->data
[] = $row;
9707 $html .= html_writer
::table($table);
9709 $info['cachesused'] = "$hits / $misses / $sets";
9710 $info['html'] .= $html;
9711 $info['txt'] .= $text.'. ';
9713 $info['cachesused'] = '0 / 0 / 0';
9714 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9715 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9718 $info['html'] = '<div class="performanceinfo siteinfo container-fluid px-md-0 overflow-auto mt-3">'.$info['html'].'</div>';
9723 * Renames a file or directory to a unique name within the same directory.
9725 * This function is designed to avoid any potential race conditions, and select an unused name.
9727 * @param string $filepath Original filepath
9728 * @param string $prefix Prefix to use for the temporary name
9729 * @return string|bool New file path or false if failed
9730 * @since Moodle 3.10
9732 function rename_to_unused_name(string $filepath, string $prefix = '_temp_') {
9733 $dir = dirname($filepath);
9734 $basename = $dir . '/' . $prefix;
9736 while ($limit < 100) {
9737 // Select a new name based on a random number.
9738 $newfilepath = $basename . md5(mt_rand());
9740 // Attempt a rename to that new name.
9741 if (@rename
($filepath, $newfilepath)) {
9742 return $newfilepath;
9745 // The first time, do some sanity checks, maybe it is failing for a good reason and there
9746 // is no point trying 100 times if so.
9747 if ($limit === 0 && (!file_exists($filepath) ||
!is_writable($dir))) {
9756 * Delete directory or only its content
9758 * @param string $dir directory path
9759 * @param bool $contentonly
9760 * @return bool success, true also if dir does not exist
9762 function remove_dir($dir, $contentonly=false) {
9763 if (!is_dir($dir)) {
9768 if (!$contentonly) {
9769 // Start by renaming the directory; this will guarantee that other processes don't write to it
9770 // while it is in the process of being deleted.
9771 $tempdir = rename_to_unused_name($dir);
9773 // If the rename was successful then delete the $tempdir instead.
9776 // If the rename fails, we will continue through and attempt to delete the directory
9777 // without renaming it since that is likely to at least delete most of the files.
9780 if (!$handle = opendir($dir)) {
9784 while (false!==($item = readdir($handle))) {
9785 if ($item != '.' && $item != '..') {
9786 if (is_dir($dir.'/'.$item)) {
9787 $result = remove_dir($dir.'/'.$item) && $result;
9789 $result = unlink($dir.'/'.$item) && $result;
9795 clearstatcache(); // Make sure file stat cache is properly invalidated.
9798 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9799 clearstatcache(); // Make sure file stat cache is properly invalidated.
9804 * Detect if an object or a class contains a given property
9805 * will take an actual object or the name of a class
9807 * @param mix $obj Name of class or real object to test
9808 * @param string $property name of property to find
9809 * @return bool true if property exists
9811 function object_property_exists( $obj, $property ) {
9812 if (is_string( $obj )) {
9813 $properties = get_class_vars( $obj );
9815 $properties = get_object_vars( $obj );
9817 return array_key_exists( $property, $properties );
9821 * Converts an object into an associative array
9823 * This function converts an object into an associative array by iterating
9824 * over its public properties. Because this function uses the foreach
9825 * construct, Iterators are respected. It works recursively on arrays of objects.
9826 * Arrays and simple values are returned as is.
9828 * If class has magic properties, it can implement IteratorAggregate
9829 * and return all available properties in getIterator()
9834 function convert_to_array($var) {
9837 // Loop over elements/properties.
9838 foreach ($var as $key => $value) {
9839 // Recursively convert objects.
9840 if (is_object($value) ||
is_array($value)) {
9841 $result[$key] = convert_to_array($value);
9843 // Simple values are untouched.
9844 $result[$key] = $value;
9851 * Detect a custom script replacement in the data directory that will
9852 * replace an existing moodle script
9854 * @return string|bool full path name if a custom script exists, false if no custom script exists
9856 function custom_script_path() {
9857 global $CFG, $SCRIPT;
9859 if ($SCRIPT === null) {
9860 // Probably some weird external script.
9864 $scriptpath = $CFG->customscripts
. $SCRIPT;
9866 // Check the custom script exists.
9867 if (file_exists($scriptpath) and is_file($scriptpath)) {
9875 * Returns whether or not the user object is a remote MNET user. This function
9876 * is in moodlelib because it does not rely on loading any of the MNET code.
9878 * @param object $user A valid user object
9879 * @return bool True if the user is from a remote Moodle.
9881 function is_mnet_remote_user($user) {
9884 if (!isset($CFG->mnet_localhost_id
)) {
9885 include_once($CFG->dirroot
. '/mnet/lib.php');
9886 $env = new mnet_environment();
9891 return (!empty($user->mnethostid
) && $user->mnethostid
!= $CFG->mnet_localhost_id
);
9895 * This function will search for browser prefereed languages, setting Moodle
9896 * to use the best one available if $SESSION->lang is undefined
9898 function setup_lang_from_browser() {
9899 global $CFG, $SESSION, $USER;
9901 if (!empty($SESSION->lang
) or !empty($USER->lang
) or empty($CFG->autolang
)) {
9902 // Lang is defined in session or user profile, nothing to do.
9906 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9910 // Extract and clean langs from headers.
9911 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9912 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9913 $rawlangs = explode(',', $rawlangs); // Convert to array.
9917 foreach ($rawlangs as $lang) {
9918 if (strpos($lang, ';') === false) {
9919 $langs[(string)$order] = $lang;
9920 $order = $order-0.01;
9922 $parts = explode(';', $lang);
9923 $pos = strpos($parts[1], '=');
9924 $langs[substr($parts[1], $pos+
1)] = $parts[0];
9927 krsort($langs, SORT_NUMERIC
);
9929 // Look for such langs under standard locations.
9930 foreach ($langs as $lang) {
9931 // Clean it properly for include.
9932 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR
));
9933 if (get_string_manager()->translation_exists($lang, false)) {
9934 // Lang exists, set it in session.
9935 $SESSION->lang
= $lang;
9936 // We have finished. Go out.
9944 * Check if $url matches anything in proxybypass list
9946 * Any errors just result in the proxy being used (least bad)
9948 * @param string $url url to check
9949 * @return boolean true if we should bypass the proxy
9951 function is_proxybypass( $url ) {
9955 if (empty($CFG->proxyhost
) or empty($CFG->proxybypass
)) {
9959 // Get the host part out of the url.
9960 if (!$host = parse_url( $url, PHP_URL_HOST
)) {
9964 // Get the possible bypass hosts into an array.
9965 $matches = explode( ',', $CFG->proxybypass
);
9967 // Check for a match.
9968 // (IPs need to match the left hand side and hosts the right of the url,
9969 // but we can recklessly check both as there can't be a false +ve).
9970 foreach ($matches as $match) {
9971 $match = trim($match);
9973 // Try for IP match (Left side).
9974 $lhs = substr($host, 0, strlen($match));
9975 if (strcasecmp($match, $lhs)==0) {
9979 // Try for host match (Right side).
9980 $rhs = substr($host, -strlen($match));
9981 if (strcasecmp($match, $rhs)==0) {
9991 * Check if the passed navigation is of the new style
9993 * @param mixed $navigation
9994 * @return bool true for yes false for no
9996 function is_newnav($navigation) {
9997 if (is_array($navigation) && !empty($navigation['newnav'])) {
10005 * Checks whether the given variable name is defined as a variable within the given object.
10007 * This will NOT work with stdClass objects, which have no class variables.
10009 * @param string $var The variable name
10010 * @param object $object The object to check
10013 function in_object_vars($var, $object) {
10014 $classvars = get_class_vars(get_class($object));
10015 $classvars = array_keys($classvars);
10016 return in_array($var, $classvars);
10020 * Returns an array without repeated objects.
10021 * This function is similar to array_unique, but for arrays that have objects as values
10023 * @param array $array
10024 * @param bool $keepkeyassoc
10027 function object_array_unique($array, $keepkeyassoc = true) {
10028 $duplicatekeys = array();
10031 foreach ($array as $key => $val) {
10032 // Convert objects to arrays, in_array() does not support objects.
10033 if (is_object($val)) {
10034 $val = (array)$val;
10037 if (!in_array($val, $tmp)) {
10040 $duplicatekeys[] = $key;
10044 foreach ($duplicatekeys as $key) {
10045 unset($array[$key]);
10048 return $keepkeyassoc ?
$array : array_values($array);
10052 * Is a userid the primary administrator?
10054 * @param int $userid int id of user to check
10057 function is_primary_admin($userid) {
10058 $primaryadmin = get_admin();
10060 if ($userid == $primaryadmin->id
) {
10068 * Returns the site identifier
10070 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
10072 function get_site_identifier() {
10074 // Check to see if it is missing. If so, initialise it.
10075 if (empty($CFG->siteidentifier
)) {
10076 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
10079 return $CFG->siteidentifier
;
10083 * Check whether the given password has no more than the specified
10084 * number of consecutive identical characters.
10086 * @param string $password password to be checked against the password policy
10087 * @param integer $maxchars maximum number of consecutive identical characters
10090 function check_consecutive_identical_characters($password, $maxchars) {
10092 if ($maxchars < 1) {
10093 return true; // Zero 0 is to disable this check.
10095 if (strlen($password) <= $maxchars) {
10096 return true; // Too short to fail this test.
10099 $previouschar = '';
10100 $consecutivecount = 1;
10101 foreach (str_split($password) as $char) {
10102 if ($char != $previouschar) {
10103 $consecutivecount = 1;
10105 $consecutivecount++
;
10106 if ($consecutivecount > $maxchars) {
10107 return false; // Check failed already.
10111 $previouschar = $char;
10118 * Helper function to do partial function binding.
10119 * so we can use it for preg_replace_callback, for example
10120 * this works with php functions, user functions, static methods and class methods
10121 * it returns you a callback that you can pass on like so:
10123 * $callback = partial('somefunction', $arg1, $arg2);
10125 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
10127 * $obj = new someclass();
10128 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
10130 * and then the arguments that are passed through at calltime are appended to the argument list.
10132 * @param mixed $function a php callback
10133 * @param mixed $arg1,... $argv arguments to partially bind with
10134 * @return array Array callback
10136 function partial() {
10137 if (!class_exists('partial')) {
10139 * Used to manage function binding.
10140 * @copyright 2009 Penny Leach
10141 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10145 public $values = array();
10146 /** @var string The function to call as a callback. */
10150 * @param string $func
10151 * @param array $args
10153 public function __construct($func, $args) {
10154 $this->values
= $args;
10155 $this->func
= $func;
10158 * Calls the callback function.
10161 public function method() {
10162 $args = func_get_args();
10163 return call_user_func_array($this->func
, array_merge($this->values
, $args));
10167 $args = func_get_args();
10168 $func = array_shift($args);
10169 $p = new partial($func, $args);
10170 return array($p, 'method');
10174 * helper function to load up and initialise the mnet environment
10175 * this must be called before you use mnet functions.
10177 * @return mnet_environment the equivalent of old $MNET global
10179 function get_mnet_environment() {
10181 require_once($CFG->dirroot
. '/mnet/lib.php');
10182 static $instance = null;
10183 if (empty($instance)) {
10184 $instance = new mnet_environment();
10191 * during xmlrpc server code execution, any code wishing to access
10192 * information about the remote peer must use this to get it.
10194 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
10196 function get_mnet_remote_client() {
10197 if (!defined('MNET_SERVER')) {
10198 debugging(get_string('notinxmlrpcserver', 'mnet'));
10201 global $MNET_REMOTE_CLIENT;
10202 if (isset($MNET_REMOTE_CLIENT)) {
10203 return $MNET_REMOTE_CLIENT;
10209 * during the xmlrpc server code execution, this will be called
10210 * to setup the object returned by {@link get_mnet_remote_client}
10212 * @param mnet_remote_client $client the client to set up
10213 * @throws moodle_exception
10215 function set_mnet_remote_client($client) {
10216 if (!defined('MNET_SERVER')) {
10217 throw new moodle_exception('notinxmlrpcserver', 'mnet');
10219 global $MNET_REMOTE_CLIENT;
10220 $MNET_REMOTE_CLIENT = $client;
10224 * return the jump url for a given remote user
10225 * this is used for rewriting forum post links in emails, etc
10227 * @param stdclass $user the user to get the idp url for
10229 function mnet_get_idp_jump_url($user) {
10232 static $mnetjumps = array();
10233 if (!array_key_exists($user->mnethostid
, $mnetjumps)) {
10234 $idp = mnet_get_peer_host($user->mnethostid
);
10235 $idpjumppath = mnet_get_app_jumppath($idp->applicationid
);
10236 $mnetjumps[$user->mnethostid
] = $idp->wwwroot
. $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot
. '&wantsurl=';
10238 return $mnetjumps[$user->mnethostid
];
10242 * Gets the homepage to use for the current user
10244 * @return int One of HOMEPAGE_*
10246 function get_home_page() {
10249 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage
)) {
10250 if ($CFG->defaulthomepage
== HOMEPAGE_MY
) {
10251 return HOMEPAGE_MY
;
10253 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY
);
10256 return HOMEPAGE_SITE
;
10260 * Gets the name of a course to be displayed when showing a list of courses.
10261 * By default this is just $course->fullname but user can configure it. The
10262 * result of this function should be passed through print_string.
10263 * @param stdClass|core_course_list_element $course Moodle course object
10264 * @return string Display name of course (either fullname or short + fullname)
10266 function get_course_display_name_for_list($course) {
10268 if (!empty($CFG->courselistshortnames
)) {
10269 if (!($course instanceof stdClass
)) {
10270 $course = (object)convert_to_array($course);
10272 return get_string('courseextendednamedisplay', '', $course);
10274 return $course->fullname
;
10279 * Safe analogue of unserialize() that can only parse arrays
10281 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
10282 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
10283 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
10285 * @param string $expression
10286 * @return array|bool either parsed array or false if parsing was impossible.
10288 function unserialize_array($expression) {
10290 // Find nested arrays, parse them and store in $subs , substitute with special string.
10291 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
10292 $key = '--SUB' . count($subs) . '--';
10293 $subs[$key] = unserialize_array($matches[2]);
10294 if ($subs[$key] === false) {
10297 $expression = str_replace($matches[2], $key . ';', $expression);
10300 // Check the expression is an array.
10301 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
10304 // Get the size and elements of an array (key;value;key;value;....).
10305 $parts = explode(';', $matches1[2]);
10306 $size = intval($matches1[1]);
10307 if (count($parts) < $size * 2 +
1) {
10310 // Analyze each part and make sure it is an integer or string or a substitute.
10312 for ($i = 0; $i < $size * 2; $i++
) {
10313 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
10314 $parts[$i] = (int)$matches2[1];
10315 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
10316 $parts[$i] = $matches3[2];
10317 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
10318 $parts[$i] = $subs[$parts[$i]];
10323 // Combine keys and values.
10324 for ($i = 0; $i < $size * 2; $i +
= 2) {
10325 $value[$parts[$i]] = $parts[$i+
1];
10331 * Safe method for unserializing given input that is expected to contain only a serialized instance of an stdClass object
10333 * If any class type other than stdClass is included in the input string, it will not be instantiated and will be cast to an
10334 * stdClass object. The initial cast to array, then back to object is to ensure we are always returning the correct type,
10335 * otherwise we would return an instances of {@see __PHP_Incomplete_class} for malformed strings
10337 * @param string $input
10340 function unserialize_object(string $input): stdClass
{
10341 $instance = (array) unserialize($input, ['allowed_classes' => [stdClass
::class]]);
10342 return (object) $instance;
10346 * The lang_string class
10348 * This special class is used to create an object representation of a string request.
10349 * It is special because processing doesn't occur until the object is first used.
10350 * The class was created especially to aid performance in areas where strings were
10351 * required to be generated but were not necessarily used.
10352 * As an example the admin tree when generated uses over 1500 strings, of which
10353 * normally only 1/3 are ever actually printed at any time.
10354 * The performance advantage is achieved by not actually processing strings that
10355 * arn't being used, as such reducing the processing required for the page.
10357 * How to use the lang_string class?
10358 * There are two methods of using the lang_string class, first through the
10359 * forth argument of the get_string function, and secondly directly.
10360 * The following are examples of both.
10361 * 1. Through get_string calls e.g.
10362 * $string = get_string($identifier, $component, $a, true);
10363 * $string = get_string('yes', 'moodle', null, true);
10364 * 2. Direct instantiation
10365 * $string = new lang_string($identifier, $component, $a, $lang);
10366 * $string = new lang_string('yes');
10368 * How do I use a lang_string object?
10369 * The lang_string object makes use of a magic __toString method so that you
10370 * are able to use the object exactly as you would use a string in most cases.
10371 * This means you are able to collect it into a variable and then directly
10372 * echo it, or concatenate it into another string, or similar.
10373 * The other thing you can do is manually get the string by calling the
10374 * lang_strings out method e.g.
10375 * $string = new lang_string('yes');
10377 * Also worth noting is that the out method can take one argument, $lang which
10378 * allows the developer to change the language on the fly.
10380 * When should I use a lang_string object?
10381 * The lang_string object is designed to be used in any situation where a
10382 * string may not be needed, but needs to be generated.
10383 * The admin tree is a good example of where lang_string objects should be
10385 * A more practical example would be any class that requries strings that may
10386 * not be printed (after all classes get renderer by renderers and who knows
10387 * what they will do ;))
10389 * When should I not use a lang_string object?
10390 * Don't use lang_strings when you are going to use a string immediately.
10391 * There is no need as it will be processed immediately and there will be no
10392 * advantage, and in fact perhaps a negative hit as a class has to be
10393 * instantiated for a lang_string object, however get_string won't require
10397 * 1. You cannot use a lang_string object as an array offset. Doing so will
10398 * result in PHP throwing an error. (You can use it as an object property!)
10402 * @copyright 2011 Sam Hemelryk
10403 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10405 class lang_string
{
10407 /** @var string The strings identifier */
10408 protected $identifier;
10409 /** @var string The strings component. Default '' */
10410 protected $component = '';
10411 /** @var array|stdClass Any arguments required for the string. Default null */
10412 protected $a = null;
10413 /** @var string The language to use when processing the string. Default null */
10414 protected $lang = null;
10416 /** @var string The processed string (once processed) */
10417 protected $string = null;
10420 * A special boolean. If set to true then the object has been woken up and
10421 * cannot be regenerated. If this is set then $this->string MUST be used.
10424 protected $forcedstring = false;
10427 * Constructs a lang_string object
10429 * This function should do as little processing as possible to ensure the best
10430 * performance for strings that won't be used.
10432 * @param string $identifier The strings identifier
10433 * @param string $component The strings component
10434 * @param stdClass|array $a Any arguments the string requires
10435 * @param string $lang The language to use when processing the string.
10436 * @throws coding_exception
10438 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10439 if (empty($component)) {
10440 $component = 'moodle';
10443 $this->identifier
= $identifier;
10444 $this->component
= $component;
10445 $this->lang
= $lang;
10447 // We MUST duplicate $a to ensure that it if it changes by reference those
10448 // changes are not carried across.
10449 // To do this we always ensure $a or its properties/values are strings
10450 // and that any properties/values that arn't convertable are forgotten.
10452 if (is_scalar($a)) {
10454 } else if ($a instanceof lang_string
) {
10455 $this->a
= $a->out();
10456 } else if (is_object($a) or is_array($a)) {
10458 $this->a
= array();
10459 foreach ($a as $key => $value) {
10460 // Make sure conversion errors don't get displayed (results in '').
10461 if (is_array($value)) {
10462 $this->a
[$key] = '';
10463 } else if (is_object($value)) {
10464 if (method_exists($value, '__toString')) {
10465 $this->a
[$key] = $value->__toString();
10467 $this->a
[$key] = '';
10470 $this->a
[$key] = (string)$value;
10476 if (debugging(false, DEBUG_DEVELOPER
)) {
10477 if (clean_param($this->identifier
, PARAM_STRINGID
) == '') {
10478 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10480 if (!empty($this->component
) && clean_param($this->component
, PARAM_COMPONENT
) == '') {
10481 throw new coding_exception('Invalid string compontent. Please check your string definition');
10483 if (!get_string_manager()->string_exists($this->identifier
, $this->component
)) {
10484 debugging('String does not exist. Please check your string definition for '.$this->identifier
.'/'.$this->component
, DEBUG_DEVELOPER
);
10490 * Processes the string.
10492 * This function actually processes the string, stores it in the string property
10493 * and then returns it.
10494 * You will notice that this function is VERY similar to the get_string method.
10495 * That is because it is pretty much doing the same thing.
10496 * However as this function is an upgrade it isn't as tolerant to backwards
10500 * @throws coding_exception
10502 protected function get_string() {
10505 // Check if we need to process the string.
10506 if ($this->string === null) {
10507 // Check the quality of the identifier.
10508 if ($CFG->debugdeveloper
&& clean_param($this->identifier
, PARAM_STRINGID
) === '') {
10509 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
);
10512 // Process the string.
10513 $this->string = get_string_manager()->get_string($this->identifier
, $this->component
, $this->a
, $this->lang
);
10514 // Debugging feature lets you display string identifier and component.
10515 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
10516 $this->string .= ' {' . $this->identifier
. '/' . $this->component
. '}';
10519 // Return the string.
10520 return $this->string;
10524 * Returns the string
10526 * @param string $lang The langauge to use when processing the string
10529 public function out($lang = null) {
10530 if ($lang !== null && $lang != $this->lang
&& ($this->lang
== null && $lang != current_language())) {
10531 if ($this->forcedstring
) {
10532 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang
.' used)', DEBUG_DEVELOPER
);
10533 return $this->get_string();
10535 $translatedstring = new lang_string($this->identifier
, $this->component
, $this->a
, $lang);
10536 return $translatedstring->out();
10538 return $this->get_string();
10542 * Magic __toString method for printing a string
10546 public function __toString() {
10547 return $this->get_string();
10551 * Magic __set_state method used for var_export
10553 * @param array $array
10556 public static function __set_state(array $array): self
{
10557 $tmp = new lang_string($array['identifier'], $array['component'], $array['a'], $array['lang']);
10558 $tmp->string = $array['string'];
10559 $tmp->forcedstring
= $array['forcedstring'];
10564 * Prepares the lang_string for sleep and stores only the forcedstring and
10565 * string properties... the string cannot be regenerated so we need to ensure
10566 * it is generated for this.
10570 public function __sleep() {
10571 $this->get_string();
10572 $this->forcedstring
= true;
10573 return array('forcedstring', 'string', 'lang');
10577 * Returns the identifier.
10581 public function get_identifier() {
10582 return $this->identifier
;
10586 * Returns the component.
10590 public function get_component() {
10591 return $this->component
;
10596 * Get human readable name describing the given callable.
10598 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10599 * It does not check if the callable actually exists.
10601 * @param callable|string|array $callable
10602 * @return string|bool Human readable name of callable, or false if not a valid callable.
10604 function get_callable_name($callable) {
10606 if (!is_callable($callable, true, $name)) {
10615 * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10616 * Never put your faith on this function and rely on its accuracy as there might be false positives.
10617 * It just performs some simple checks, and mainly is used for places where we want to hide some options
10618 * such as site registration when $CFG->wwwroot is not publicly accessible.
10619 * Good thing is there is no false negative.
10620 * Note that it's possible to force the result of this check by specifying $CFG->site_is_public in config.php
10624 function site_is_public() {
10627 // Return early if site admin has forced this setting.
10628 if (isset($CFG->site_is_public
)) {
10629 return (bool)$CFG->site_is_public
;
10632 $host = parse_url($CFG->wwwroot
, PHP_URL_HOST
);
10634 if ($host === 'localhost' ||
preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10636 } else if (\core\ip_utils
::is_ip_address($host) && !ip_is_public($host)) {
10638 } else if (($address = \core\ip_utils
::get_ip_address($host)) && !ip_is_public($address)) {