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);
463 /** Type of module */
464 define('FEATURE_MOD_PURPOSE', 'mod_purpose');
465 /** Module purpose administration */
466 define('MOD_PURPOSE_ADMINISTRATION', 'administration');
467 /** Module purpose assessment */
468 define('MOD_PURPOSE_ASSESSMENT', 'assessment');
469 /** Module purpose communication */
470 define('MOD_PURPOSE_COLLABORATION', 'collaboration');
471 /** Module purpose communication */
472 define('MOD_PURPOSE_COMMUNICATION', 'communication');
473 /** Module purpose content */
474 define('MOD_PURPOSE_CONTENT', 'content');
475 /** Module purpose interface */
476 define('MOD_PURPOSE_INTERFACE', 'interface');
477 /** Module purpose other */
478 define('MOD_PURPOSE_OTHER', 'other');
481 * Security token used for allowing access
482 * from external application such as web services.
483 * Scripts do not use any session, performance is relatively
484 * low because we need to load access info in each request.
485 * Scripts are executed in parallel.
487 define('EXTERNAL_TOKEN_PERMANENT', 0);
490 * Security token used for allowing access
491 * of embedded applications, the code is executed in the
492 * active user session. Token is invalidated after user logs out.
493 * Scripts are executed serially - normal session locking is used.
495 define('EXTERNAL_TOKEN_EMBEDDED', 1);
498 * The home page should be the site home
500 define('HOMEPAGE_SITE', 0);
502 * The home page should be the users my page
504 define('HOMEPAGE_MY', 1);
506 * The home page can be chosen by the user
508 define('HOMEPAGE_USER', 2);
510 * The home page should be the users my courses page
512 define('HOMEPAGE_MYCOURSES', 3);
515 * URL of the Moodle sites registration portal.
517 defined('HUB_MOODLEORGHUBURL') ||
define('HUB_MOODLEORGHUBURL', 'https://stats.moodle.org');
520 * Moodle mobile app service name
522 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
525 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
527 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
530 * Course display settings: display all sections on one page.
532 define('COURSE_DISPLAY_SINGLEPAGE', 0);
534 * Course display settings: split pages into a page per section.
536 define('COURSE_DISPLAY_MULTIPAGE', 1);
539 * Authentication constant: String used in password field when password is not stored.
541 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
544 * Email from header to never include via information.
546 define('EMAIL_VIA_NEVER', 0);
549 * Email from header to always include via information.
551 define('EMAIL_VIA_ALWAYS', 1);
554 * Email from header to only include via information if the address is no-reply.
556 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
558 // PARAMETER HANDLING.
561 * Returns a particular value for the named variable, taken from
562 * POST or GET. If the parameter doesn't exist then an error is
563 * thrown because we require this variable.
565 * This function should be used to initialise all required values
566 * in a script that are based on parameters. Usually it will be
568 * $id = required_param('id', PARAM_INT);
570 * Please note the $type parameter is now required and the value can not be array.
572 * @param string $parname the name of the page parameter we want
573 * @param string $type expected type of parameter
575 * @throws coding_exception
577 function required_param($parname, $type) {
578 if (func_num_args() != 2 or empty($parname) or empty($type)) {
579 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
581 // POST has precedence.
582 if (isset($_POST[$parname])) {
583 $param = $_POST[$parname];
584 } else if (isset($_GET[$parname])) {
585 $param = $_GET[$parname];
587 print_error('missingparam', '', '', $parname);
590 if (is_array($param)) {
591 debugging('Invalid array parameter detected in required_param(): '.$parname);
592 // TODO: switch to fatal error in Moodle 2.3.
593 return required_param_array($parname, $type);
596 return clean_param($param, $type);
600 * Returns a particular array value for the named variable, taken from
601 * POST or GET. If the parameter doesn't exist then an error is
602 * thrown because we require this variable.
604 * This function should be used to initialise all required values
605 * in a script that are based on parameters. Usually it will be
607 * $ids = required_param_array('ids', PARAM_INT);
609 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
611 * @param string $parname the name of the page parameter we want
612 * @param string $type expected type of parameter
614 * @throws coding_exception
616 function required_param_array($parname, $type) {
617 if (func_num_args() != 2 or empty($parname) or empty($type)) {
618 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
620 // POST has precedence.
621 if (isset($_POST[$parname])) {
622 $param = $_POST[$parname];
623 } else if (isset($_GET[$parname])) {
624 $param = $_GET[$parname];
626 print_error('missingparam', '', '', $parname);
628 if (!is_array($param)) {
629 print_error('missingparam', '', '', $parname);
633 foreach ($param as $key => $value) {
634 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
635 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
638 $result[$key] = clean_param($value, $type);
645 * Returns a particular value for the named variable, taken from
646 * POST or GET, otherwise returning a given default.
648 * This function should be used to initialise all optional values
649 * in a script that are based on parameters. Usually it will be
651 * $name = optional_param('name', 'Fred', PARAM_TEXT);
653 * Please note the $type parameter is now required and the value can not be array.
655 * @param string $parname the name of the page parameter we want
656 * @param mixed $default the default value to return if nothing is found
657 * @param string $type expected type of parameter
659 * @throws coding_exception
661 function optional_param($parname, $default, $type) {
662 if (func_num_args() != 3 or empty($parname) or empty($type)) {
663 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
666 // POST has precedence.
667 if (isset($_POST[$parname])) {
668 $param = $_POST[$parname];
669 } else if (isset($_GET[$parname])) {
670 $param = $_GET[$parname];
675 if (is_array($param)) {
676 debugging('Invalid array parameter detected in required_param(): '.$parname);
677 // TODO: switch to $default in Moodle 2.3.
678 return optional_param_array($parname, $default, $type);
681 return clean_param($param, $type);
685 * Returns a particular array value for the named variable, taken from
686 * POST or GET, otherwise returning a given default.
688 * This function should be used to initialise all optional values
689 * in a script that are based on parameters. Usually it will be
691 * $ids = optional_param('id', array(), PARAM_INT);
693 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
695 * @param string $parname the name of the page parameter we want
696 * @param mixed $default the default value to return if nothing is found
697 * @param string $type expected type of parameter
699 * @throws coding_exception
701 function optional_param_array($parname, $default, $type) {
702 if (func_num_args() != 3 or empty($parname) or empty($type)) {
703 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
706 // POST has precedence.
707 if (isset($_POST[$parname])) {
708 $param = $_POST[$parname];
709 } else if (isset($_GET[$parname])) {
710 $param = $_GET[$parname];
714 if (!is_array($param)) {
715 debugging('optional_param_array() expects array parameters only: '.$parname);
720 foreach ($param as $key => $value) {
721 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
722 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
725 $result[$key] = clean_param($value, $type);
732 * Strict validation of parameter values, the values are only converted
733 * to requested PHP type. Internally it is using clean_param, the values
734 * before and after cleaning must be equal - otherwise
735 * an invalid_parameter_exception is thrown.
736 * Objects and classes are not accepted.
738 * @param mixed $param
739 * @param string $type PARAM_ constant
740 * @param bool $allownull are nulls valid value?
741 * @param string $debuginfo optional debug information
742 * @return mixed the $param value converted to PHP type
743 * @throws invalid_parameter_exception if $param is not of given type
745 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED
, $debuginfo='') {
746 if (is_null($param)) {
747 if ($allownull == NULL_ALLOWED
) {
750 throw new invalid_parameter_exception($debuginfo);
753 if (is_array($param) or is_object($param)) {
754 throw new invalid_parameter_exception($debuginfo);
757 $cleaned = clean_param($param, $type);
759 if ($type == PARAM_FLOAT
) {
760 // Do not detect precision loss here.
761 if (is_float($param) or is_int($param)) {
763 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
764 throw new invalid_parameter_exception($debuginfo);
766 } else if ((string)$param !== (string)$cleaned) {
767 // Conversion to string is usually lossless.
768 throw new invalid_parameter_exception($debuginfo);
775 * Makes sure array contains only the allowed types, this function does not validate array key names!
778 * $options = clean_param($options, PARAM_INT);
781 * @param array $param the variable array we are cleaning
782 * @param string $type expected format of param after cleaning.
783 * @param bool $recursive clean recursive arrays
785 * @throws coding_exception
787 function clean_param_array(array $param = null, $type, $recursive = false) {
788 // Convert null to empty array.
789 $param = (array)$param;
790 foreach ($param as $key => $value) {
791 if (is_array($value)) {
793 $param[$key] = clean_param_array($value, $type, true);
795 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
798 $param[$key] = clean_param($value, $type);
805 * Used by {@link optional_param()} and {@link required_param()} to
806 * clean the variables and/or cast to specific types, based on
809 * $course->format = clean_param($course->format, PARAM_ALPHA);
810 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
813 * @param mixed $param the variable we are cleaning
814 * @param string $type expected format of param after cleaning.
816 * @throws coding_exception
818 function clean_param($param, $type) {
821 if (is_array($param)) {
822 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
823 } else if (is_object($param)) {
824 if (method_exists($param, '__toString')) {
825 $param = $param->__toString();
827 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
833 // No cleaning at all.
834 $param = fix_utf8($param);
837 case PARAM_RAW_TRIMMED
:
838 // No cleaning, but strip leading and trailing whitespace.
839 $param = fix_utf8($param);
843 // General HTML cleaning, try to use more specific type if possible this is deprecated!
844 // Please use more specific type instead.
845 if (is_numeric($param)) {
848 $param = fix_utf8($param);
849 // Sweep for scripts, etc.
850 return clean_text($param);
852 case PARAM_CLEANHTML
:
853 // Clean html fragment.
854 $param = fix_utf8($param);
855 // Sweep for scripts, etc.
856 $param = clean_text($param, FORMAT_HTML
);
860 // Convert to integer.
865 return (float)$param;
867 case PARAM_LOCALISEDFLOAT
:
869 return unformat_float($param, true);
872 // Remove everything not `a-z`.
873 return preg_replace('/[^a-zA-Z]/i', '', $param);
876 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
877 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
880 // Remove everything not `a-zA-Z0-9`.
881 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
883 case PARAM_ALPHANUMEXT
:
884 // Remove everything not `a-zA-Z0-9_-`.
885 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
888 // Remove everything not `0-9,`.
889 return preg_replace('/[^0-9,]/i', '', $param);
892 // Convert to 1 or 0.
893 $tempstr = strtolower($param);
894 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
896 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
899 $param = empty($param) ?
0 : 1;
905 $param = fix_utf8($param);
906 return strip_tags($param);
909 // Leave only tags needed for multilang.
910 $param = fix_utf8($param);
911 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
912 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
914 if (strpos($param, '</lang>') !== false) {
915 // Old and future mutilang syntax.
916 $param = strip_tags($param, '<lang>');
917 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
921 foreach ($matches[0] as $match) {
922 if ($match === '</lang>') {
930 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
941 } else if (strpos($param, '</span>') !== false) {
942 // Current problematic multilang syntax.
943 $param = strip_tags($param, '<span>');
944 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
948 foreach ($matches[0] as $match) {
949 if ($match === '</span>') {
957 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
969 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
970 return strip_tags($param);
972 case PARAM_COMPONENT
:
973 // We do not want any guessing here, either the name is correct or not
974 // please note only normalised component names are accepted.
975 if (!preg_match('/^[a-z][a-z0-9]*(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
978 if (strpos($param, '__') !== false) {
981 if (strpos($param, 'mod_') === 0) {
982 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
983 if (substr_count($param, '_') != 1) {
991 // We do not want any guessing here, either the name is correct or not.
992 if (!is_valid_plugin_name($param)) {
998 // Remove everything not a-zA-Z0-9_- .
999 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
1001 case PARAM_SAFEPATH
:
1002 // Remove everything not a-zA-Z0-9/_- .
1003 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
1006 // Strip all suspicious characters from filename.
1007 $param = fix_utf8($param);
1008 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
1009 if ($param === '.' ||
$param === '..') {
1015 // Strip all suspicious characters from file path.
1016 $param = fix_utf8($param);
1017 $param = str_replace('\\', '/', $param);
1019 // Explode the path and clean each element using the PARAM_FILE rules.
1020 $breadcrumb = explode('/', $param);
1021 foreach ($breadcrumb as $key => $crumb) {
1022 if ($crumb === '.' && $key === 0) {
1023 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1025 $crumb = clean_param($crumb, PARAM_FILE
);
1027 $breadcrumb[$key] = $crumb;
1029 $param = implode('/', $breadcrumb);
1031 // Remove multiple current path (./././) and multiple slashes (///).
1032 $param = preg_replace('~//+~', '/', $param);
1033 $param = preg_replace('~/(\./)+~', '/', $param);
1037 // Allow FQDN or IPv4 dotted quad.
1038 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1039 // Match ipv4 dotted quad.
1040 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1041 // Confirm values are ok.
1042 if ( $match[0] > 255
1045 ||
$match[4] > 255 ) {
1046 // Hmmm, what kind of dotted quad is this?
1049 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1050 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1051 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1053 // All is ok - $param is respected.
1062 $param = fix_utf8($param);
1063 include_once($CFG->dirroot
. '/lib/validateurlsyntax.php');
1064 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1065 // All is ok, param is respected.
1072 case PARAM_LOCALURL
:
1073 // Allow http absolute, root relative and relative URLs within wwwroot.
1074 $param = clean_param($param, PARAM_URL
);
1075 if (!empty($param)) {
1077 if ($param === $CFG->wwwroot
) {
1079 } else if (preg_match(':^/:', $param)) {
1080 // Root-relative, ok!
1081 } else if (preg_match('/^' . preg_quote($CFG->wwwroot
. '/', '/') . '/i', $param)) {
1082 // Absolute, and matches our wwwroot.
1084 // Relative - let's make sure there are no tricks.
1085 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1095 $param = trim($param);
1096 // PEM formatted strings may contain letters/numbers and the symbols:
1100 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1101 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1102 list($wholething, $body) = $matches;
1103 unset($wholething, $matches);
1104 $b64 = clean_param($body, PARAM_BASE64
);
1106 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1114 if (!empty($param)) {
1115 // PEM formatted strings may contain letters/numbers and the symbols
1119 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1122 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY
);
1123 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1124 // than (or equal to) 64 characters long.
1125 for ($i=0, $j=count($lines); $i < $j; $i++
) {
1127 if (64 < strlen($lines[$i])) {
1133 if (64 != strlen($lines[$i])) {
1137 return implode("\n", $lines);
1143 $param = fix_utf8($param);
1144 // Please note it is not safe to use the tag name directly anywhere,
1145 // it must be processed with s(), urlencode() before embedding anywhere.
1146 // Remove some nasties.
1147 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1148 // Convert many whitespace chars into one.
1149 $param = preg_replace('/\s+/u', ' ', $param);
1150 $param = core_text
::substr(trim($param), 0, TAG_MAX_LENGTH
);
1154 $param = fix_utf8($param);
1155 $tags = explode(',', $param);
1157 foreach ($tags as $tag) {
1158 $res = clean_param($tag, PARAM_TAG
);
1164 return implode(',', $result);
1169 case PARAM_CAPABILITY
:
1170 if (get_capability_info($param)) {
1176 case PARAM_PERMISSION
:
1177 $param = (int)$param;
1178 if (in_array($param, array(CAP_INHERIT
, CAP_ALLOW
, CAP_PREVENT
, CAP_PROHIBIT
))) {
1185 $param = clean_param($param, PARAM_PLUGIN
);
1186 if (empty($param)) {
1188 } else if (exists_auth_plugin($param)) {
1195 $param = clean_param($param, PARAM_SAFEDIR
);
1196 if (get_string_manager()->translation_exists($param)) {
1199 // Specified language is not installed or param malformed.
1204 $param = clean_param($param, PARAM_PLUGIN
);
1205 if (empty($param)) {
1207 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1209 } else if (!empty($CFG->themedir
) and file_exists("$CFG->themedir/$param/config.php")) {
1212 // Specified theme is not installed.
1216 case PARAM_USERNAME
:
1217 $param = fix_utf8($param);
1218 $param = trim($param);
1219 // Convert uppercase to lowercase MDL-16919.
1220 $param = core_text
::strtolower($param);
1221 if (empty($CFG->extendedusernamechars
)) {
1222 $param = str_replace(" " , "", $param);
1223 // Regular expression, eliminate all chars EXCEPT:
1224 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1225 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1230 $param = fix_utf8($param);
1231 if (validate_email($param)) {
1237 case PARAM_STRINGID
:
1238 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1244 case PARAM_TIMEZONE
:
1245 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1246 $param = fix_utf8($param);
1247 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1248 if (preg_match($timezonepattern, $param)) {
1255 // Doh! throw error, switched parameters in optional_param or another serious problem.
1256 print_error("unknownparamtype", '', '', $type);
1261 * Whether the PARAM_* type is compatible in RTL.
1263 * Being compatible with RTL means that the data they contain can flow
1264 * from right-to-left or left-to-right without compromising the user experience.
1266 * Take URLs for example, they are not RTL compatible as they should always
1267 * flow from the left to the right. This also applies to numbers, email addresses,
1268 * configuration snippets, base64 strings, etc...
1270 * This function tries to best guess which parameters can contain localised strings.
1272 * @param string $paramtype Constant PARAM_*.
1275 function is_rtl_compatible($paramtype) {
1276 return $paramtype == PARAM_TEXT ||
$paramtype == PARAM_NOTAGS
;
1280 * Makes sure the data is using valid utf8, invalid characters are discarded.
1282 * Note: this function is not intended for full objects with methods and private properties.
1284 * @param mixed $value
1285 * @return mixed with proper utf-8 encoding
1287 function fix_utf8($value) {
1288 if (is_null($value) or $value === '') {
1291 } else if (is_string($value)) {
1292 if ((string)(int)$value === $value) {
1296 // No null bytes expected in our data, so let's remove it.
1297 $value = str_replace("\0", '', $value);
1299 // Note: this duplicates min_fix_utf8() intentionally.
1300 static $buggyiconv = null;
1301 if ($buggyiconv === null) {
1302 $buggyiconv = (!function_exists('iconv') or @iconv
('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1306 if (function_exists('mb_convert_encoding')) {
1307 $subst = mb_substitute_character();
1308 mb_substitute_character('none');
1309 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1310 mb_substitute_character($subst);
1313 // Warn admins on admin/index.php page.
1318 $result = @iconv
('UTF-8', 'UTF-8//IGNORE', $value);
1323 } else if (is_array($value)) {
1324 foreach ($value as $k => $v) {
1325 $value[$k] = fix_utf8($v);
1329 } else if (is_object($value)) {
1330 // Do not modify original.
1331 $value = clone($value);
1332 foreach ($value as $k => $v) {
1333 $value->$k = fix_utf8($v);
1338 // This is some other type, no utf-8 here.
1344 * Return true if given value is integer or string with integer value
1346 * @param mixed $value String or Int
1347 * @return bool true if number, false if not
1349 function is_number($value) {
1350 if (is_int($value)) {
1352 } else if (is_string($value)) {
1353 return ((string)(int)$value) === $value;
1360 * Returns host part from url.
1362 * @param string $url full url
1363 * @return string host, null if not found
1365 function get_host_from_url($url) {
1366 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1374 * Tests whether anything was returned by text editor
1376 * This function is useful for testing whether something you got back from
1377 * the HTML editor actually contains anything. Sometimes the HTML editor
1378 * appear to be empty, but actually you get back a <br> tag or something.
1380 * @param string $string a string containing HTML.
1381 * @return boolean does the string contain any actual content - that is text,
1382 * images, objects, etc.
1384 function html_is_blank($string) {
1385 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1389 * Set a key in global configuration
1391 * Set a key/value pair in both this session's {@link $CFG} global variable
1392 * and in the 'config' database table for future sessions.
1394 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1395 * In that case it doesn't affect $CFG.
1397 * A NULL value will delete the entry.
1399 * NOTE: this function is called from lib/db/upgrade.php
1401 * @param string $name the key to set
1402 * @param string $value the value to set (without magic quotes)
1403 * @param string $plugin (optional) the plugin scope, default null
1404 * @return bool true or exception
1406 function set_config($name, $value, $plugin=null) {
1409 if (empty($plugin)) {
1410 if (!array_key_exists($name, $CFG->config_php_settings
)) {
1411 // So it's defined for this invocation at least.
1412 if (is_null($value)) {
1415 // Settings from db are always strings.
1416 $CFG->$name = (string)$value;
1420 if ($DB->get_field('config', 'name', array('name' => $name))) {
1421 if ($value === null) {
1422 $DB->delete_records('config', array('name' => $name));
1424 $DB->set_field('config', 'value', $value, array('name' => $name));
1427 if ($value !== null) {
1428 $config = new stdClass();
1429 $config->name
= $name;
1430 $config->value
= $value;
1431 $DB->insert_record('config', $config, false);
1433 // When setting config during a Behat test (in the CLI script, not in the web browser
1434 // requests), remember which ones are set so that we can clear them later.
1435 if (defined('BEHAT_TEST')) {
1436 if (!property_exists($CFG, 'behat_cli_added_config')) {
1437 $CFG->behat_cli_added_config
= [];
1439 $CFG->behat_cli_added_config
[$name] = true;
1442 if ($name === 'siteidentifier') {
1443 cache_helper
::update_site_identifier($value);
1445 cache_helper
::invalidate_by_definition('core', 'config', array(), 'core');
1448 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1449 if ($value===null) {
1450 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1452 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1455 if ($value !== null) {
1456 $config = new stdClass();
1457 $config->plugin
= $plugin;
1458 $config->name
= $name;
1459 $config->value
= $value;
1460 $DB->insert_record('config_plugins', $config, false);
1463 cache_helper
::invalidate_by_definition('core', 'config', array(), $plugin);
1470 * Get configuration values from the global config table
1471 * or the config_plugins table.
1473 * If called with one parameter, it will load all the config
1474 * variables for one plugin, and return them as an object.
1476 * If called with 2 parameters it will return a string single
1477 * value or false if the value is not found.
1479 * NOTE: this function is called from lib/db/upgrade.php
1481 * @param string $plugin full component name
1482 * @param string $name default null
1483 * @return mixed hash-like object or single value, return false no config found
1484 * @throws dml_exception
1486 function get_config($plugin, $name = null) {
1489 if ($plugin === 'moodle' ||
$plugin === 'core' ||
empty($plugin)) {
1490 $forced =& $CFG->config_php_settings
;
1494 if (array_key_exists($plugin, $CFG->forced_plugin_settings
)) {
1495 $forced =& $CFG->forced_plugin_settings
[$plugin];
1502 if (!isset($CFG->siteidentifier
)) {
1504 // This may throw an exception during installation, which is how we detect the
1505 // need to install the database. For more details see {@see initialise_cfg()}.
1506 $CFG->siteidentifier
= $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1507 } catch (dml_exception
$ex) {
1508 // Set siteidentifier to false. We don't want to trip this continually.
1509 $siteidentifier = false;
1514 if (!empty($name)) {
1515 if (array_key_exists($name, $forced)) {
1516 return (string)$forced[$name];
1517 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1518 return $CFG->siteidentifier
;
1522 $cache = cache
::make('core', 'config');
1523 $result = $cache->get($plugin);
1524 if ($result === false) {
1525 // The user is after a recordset.
1527 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1529 // This part is not really used any more, but anyway...
1530 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1532 $cache->set($plugin, $result);
1535 if (!empty($name)) {
1536 if (array_key_exists($name, $result)) {
1537 return $result[$name];
1542 if ($plugin === 'core') {
1543 $result['siteidentifier'] = $CFG->siteidentifier
;
1546 foreach ($forced as $key => $value) {
1547 if (is_null($value) or is_array($value) or is_object($value)) {
1548 // We do not want any extra mess here, just real settings that could be saved in db.
1549 unset($result[$key]);
1551 // Convert to string as if it went through the DB.
1552 $result[$key] = (string)$value;
1556 return (object)$result;
1560 * Removes a key from global configuration.
1562 * NOTE: this function is called from lib/db/upgrade.php
1564 * @param string $name the key to set
1565 * @param string $plugin (optional) the plugin scope
1566 * @return boolean whether the operation succeeded.
1568 function unset_config($name, $plugin=null) {
1571 if (empty($plugin)) {
1573 $DB->delete_records('config', array('name' => $name));
1574 cache_helper
::invalidate_by_definition('core', 'config', array(), 'core');
1576 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1577 cache_helper
::invalidate_by_definition('core', 'config', array(), $plugin);
1584 * Remove all the config variables for a given plugin.
1586 * NOTE: this function is called from lib/db/upgrade.php
1588 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1589 * @return boolean whether the operation succeeded.
1591 function unset_all_config_for_plugin($plugin) {
1593 // Delete from the obvious config_plugins first.
1594 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1595 // Next delete any suspect settings from config.
1596 $like = $DB->sql_like('name', '?', true, true, false, '|');
1597 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1598 $DB->delete_records_select('config', $like, $params);
1599 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1600 cache_helper
::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1606 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1608 * All users are verified if they still have the necessary capability.
1610 * @param string $value the value of the config setting.
1611 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1612 * @param bool $includeadmins include administrators.
1613 * @return array of user objects.
1615 function get_users_from_config($value, $capability, $includeadmins = true) {
1616 if (empty($value) or $value === '$@NONE@$') {
1620 // We have to make sure that users still have the necessary capability,
1621 // it should be faster to fetch them all first and then test if they are present
1622 // instead of validating them one-by-one.
1623 $users = get_users_by_capability(context_system
::instance(), $capability);
1624 if ($includeadmins) {
1625 $admins = get_admins();
1626 foreach ($admins as $admin) {
1627 $users[$admin->id
] = $admin;
1631 if ($value === '$@ALL@$') {
1635 $result = array(); // Result in correct order.
1636 $allowed = explode(',', $value);
1637 foreach ($allowed as $uid) {
1638 if (isset($users[$uid])) {
1639 $user = $users[$uid];
1640 $result[$user->id
] = $user;
1649 * Invalidates browser caches and cached data in temp.
1653 function purge_all_caches() {
1658 * Selectively invalidate different types of cache.
1660 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1661 * areas alone or in combination.
1663 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1664 * 'muc' Purge MUC caches?
1665 * 'theme' Purge theme cache?
1666 * 'lang' Purge language string cache?
1667 * 'js' Purge javascript cache?
1668 * 'filter' Purge text filter cache?
1669 * 'other' Purge all other caches?
1671 function purge_caches($options = []) {
1672 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1673 if (empty(array_filter($options))) {
1674 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1676 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1678 if ($options['muc']) {
1679 cache_helper
::purge_all();
1681 if ($options['theme']) {
1682 theme_reset_all_caches();
1684 if ($options['lang']) {
1685 get_string_manager()->reset_caches();
1687 if ($options['js']) {
1688 js_reset_all_caches();
1690 if ($options['template']) {
1691 template_reset_all_caches();
1693 if ($options['filter']) {
1694 reset_text_filters_cache();
1696 if ($options['other']) {
1697 purge_other_caches();
1702 * Purge all non-MUC caches not otherwise purged in purge_caches.
1704 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1705 * {@link phpunit_util::reset_dataroot()}
1707 function purge_other_caches() {
1709 if (class_exists('core_plugin_manager')) {
1710 core_plugin_manager
::reset_caches();
1713 // Bump up cacherev field for all courses.
1715 increment_revision_number('course', 'cacherev', '');
1716 } catch (moodle_exception
$e) {
1717 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1720 $DB->reset_caches();
1722 // Purge all other caches: rss, simplepie, etc.
1724 remove_dir($CFG->cachedir
.'', true);
1726 // Make sure cache dir is writable, throws exception if not.
1727 make_cache_directory('');
1729 // This is the only place where we purge local caches, we are only adding files there.
1730 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1731 remove_dir($CFG->localcachedir
, true);
1732 set_config('localcachedirpurged', time());
1733 make_localcache_directory('', true);
1734 \core\task\manager
::clear_static_caches();
1738 * Get volatile flags
1740 * @param string $type
1741 * @param int $changedsince default null
1742 * @return array records array
1744 function get_cache_flags($type, $changedsince = null) {
1747 $params = array('type' => $type, 'expiry' => time());
1748 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1749 if ($changedsince !== null) {
1750 $params['changedsince'] = $changedsince;
1751 $sqlwhere .= " AND timemodified > :changedsince";
1754 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1755 foreach ($flags as $flag) {
1756 $cf[$flag->name
] = $flag->value
;
1763 * Get volatile flags
1765 * @param string $type
1766 * @param string $name
1767 * @param int $changedsince default null
1768 * @return string|false The cache flag value or false
1770 function get_cache_flag($type, $name, $changedsince=null) {
1773 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1775 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1776 if ($changedsince !== null) {
1777 $params['changedsince'] = $changedsince;
1778 $sqlwhere .= " AND timemodified > :changedsince";
1781 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1785 * Set a volatile flag
1787 * @param string $type the "type" namespace for the key
1788 * @param string $name the key to set
1789 * @param string $value the value to set (without magic quotes) - null will remove the flag
1790 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1791 * @return bool Always returns true
1793 function set_cache_flag($type, $name, $value, $expiry = null) {
1796 $timemodified = time();
1797 if ($expiry === null ||
$expiry < $timemodified) {
1798 $expiry = $timemodified +
24 * 60 * 60;
1800 $expiry = (int)$expiry;
1803 if ($value === null) {
1804 unset_cache_flag($type, $name);
1808 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE
)) {
1809 // This is a potential problem in DEBUG_DEVELOPER.
1810 if ($f->value
== $value and $f->expiry
== $expiry and $f->timemodified
== $timemodified) {
1811 return true; // No need to update.
1814 $f->expiry
= $expiry;
1815 $f->timemodified
= $timemodified;
1816 $DB->update_record('cache_flags', $f);
1818 $f = new stdClass();
1819 $f->flagtype
= $type;
1822 $f->expiry
= $expiry;
1823 $f->timemodified
= $timemodified;
1824 $DB->insert_record('cache_flags', $f);
1830 * Removes a single volatile flag
1832 * @param string $type the "type" namespace for the key
1833 * @param string $name the key to set
1836 function unset_cache_flag($type, $name) {
1838 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1843 * Garbage-collect volatile flags
1845 * @return bool Always returns true
1847 function gc_cache_flags() {
1849 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1853 // USER PREFERENCE API.
1856 * Refresh user preference cache. This is used most often for $USER
1857 * object that is stored in session, but it also helps with performance in cron script.
1859 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1862 * @category preference
1864 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1865 * @param int $cachelifetime Cache life time on the current page (in seconds)
1866 * @throws coding_exception
1869 function check_user_preferences_loaded(stdClass
$user, $cachelifetime = 120) {
1871 // Static cache, we need to check on each page load, not only every 2 minutes.
1872 static $loadedusers = array();
1874 if (!isset($user->id
)) {
1875 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1878 if (empty($user->id
) or isguestuser($user->id
)) {
1879 // No permanent storage for not-logged-in users and guest.
1880 if (!isset($user->preference
)) {
1881 $user->preference
= array();
1888 if (isset($loadedusers[$user->id
]) and isset($user->preference
) and isset($user->preference
['_lastloaded'])) {
1889 // Already loaded at least once on this page. Are we up to date?
1890 if ($user->preference
['_lastloaded'] +
$cachelifetime > $timenow) {
1891 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1894 } else if (!get_cache_flag('userpreferenceschanged', $user->id
, $user->preference
['_lastloaded'])) {
1895 // No change since the lastcheck on this page.
1896 $user->preference
['_lastloaded'] = $timenow;
1901 // OK, so we have to reload all preferences.
1902 $loadedusers[$user->id
] = true;
1903 $user->preference
= $DB->get_records_menu('user_preferences', array('userid' => $user->id
), '', 'name,value'); // All values.
1904 $user->preference
['_lastloaded'] = $timenow;
1908 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1910 * NOTE: internal function, do not call from other code.
1914 * @param integer $userid the user whose prefs were changed.
1916 function mark_user_preferences_changed($userid) {
1919 if (empty($userid) or isguestuser($userid)) {
1920 // No cache flags for guest and not-logged-in users.
1924 set_cache_flag('userpreferenceschanged', $userid, 1, time() +
$CFG->sessiontimeout
);
1928 * Sets a preference for the specified user.
1930 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1932 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1935 * @category preference
1937 * @param string $name The key to set as preference for the specified user
1938 * @param string $value The value to set for the $name key in the specified user's
1939 * record, null means delete current value.
1940 * @param stdClass|int|null $user A moodle user object or id, null means current user
1941 * @throws coding_exception
1942 * @return bool Always true or exception
1944 function set_user_preference($name, $value, $user = null) {
1947 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1948 throw new coding_exception('Invalid preference name in set_user_preference() call');
1951 if (is_null($value)) {
1952 // Null means delete current.
1953 return unset_user_preference($name, $user);
1954 } else if (is_object($value)) {
1955 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1956 } else if (is_array($value)) {
1957 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1959 // Value column maximum length is 1333 characters.
1960 $value = (string)$value;
1961 if (core_text
::strlen($value) > 1333) {
1962 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1965 if (is_null($user)) {
1967 } else if (isset($user->id
)) {
1968 // It is a valid object.
1969 } else if (is_numeric($user)) {
1970 $user = (object)array('id' => (int)$user);
1972 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1975 check_user_preferences_loaded($user);
1977 if (empty($user->id
) or isguestuser($user->id
)) {
1978 // No permanent storage for not-logged-in users and guest.
1979 $user->preference
[$name] = $value;
1983 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => $name))) {
1984 if ($preference->value
=== $value and isset($user->preference
[$name]) and $user->preference
[$name] === $value) {
1985 // Preference already set to this value.
1988 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id
));
1991 $preference = new stdClass();
1992 $preference->userid
= $user->id
;
1993 $preference->name
= $name;
1994 $preference->value
= $value;
1995 $DB->insert_record('user_preferences', $preference);
1998 // Update value in cache.
1999 $user->preference
[$name] = $value;
2000 // Update the $USER in case where we've not a direct reference to $USER.
2001 if ($user !== $USER && $user->id
== $USER->id
) {
2002 $USER->preference
[$name] = $value;
2005 // Set reload flag for other sessions.
2006 mark_user_preferences_changed($user->id
);
2012 * Sets a whole array of preferences for the current user
2014 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2017 * @category preference
2019 * @param array $prefarray An array of key/value pairs to be set
2020 * @param stdClass|int|null $user A moodle user object or id, null means current user
2021 * @return bool Always true or exception
2023 function set_user_preferences(array $prefarray, $user = null) {
2024 foreach ($prefarray as $name => $value) {
2025 set_user_preference($name, $value, $user);
2031 * Unsets a preference completely by deleting it from the database
2033 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2036 * @category preference
2038 * @param string $name The key to unset as preference for the specified user
2039 * @param stdClass|int|null $user A moodle user object or id, null means current user
2040 * @throws coding_exception
2041 * @return bool Always true or exception
2043 function unset_user_preference($name, $user = null) {
2046 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2047 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2050 if (is_null($user)) {
2052 } else if (isset($user->id
)) {
2053 // It is a valid object.
2054 } else if (is_numeric($user)) {
2055 $user = (object)array('id' => (int)$user);
2057 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2060 check_user_preferences_loaded($user);
2062 if (empty($user->id
) or isguestuser($user->id
)) {
2063 // No permanent storage for not-logged-in user and guest.
2064 unset($user->preference
[$name]);
2069 $DB->delete_records('user_preferences', array('userid' => $user->id
, 'name' => $name));
2071 // Delete the preference from cache.
2072 unset($user->preference
[$name]);
2073 // Update the $USER in case where we've not a direct reference to $USER.
2074 if ($user !== $USER && $user->id
== $USER->id
) {
2075 unset($USER->preference
[$name]);
2078 // Set reload flag for other sessions.
2079 mark_user_preferences_changed($user->id
);
2085 * Used to fetch user preference(s)
2087 * If no arguments are supplied this function will return
2088 * all of the current user preferences as an array.
2090 * If a name is specified then this function
2091 * attempts to return that particular preference value. If
2092 * none is found, then the optional value $default is returned,
2095 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2098 * @category preference
2100 * @param string $name Name of the key to use in finding a preference value
2101 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2102 * @param stdClass|int|null $user A moodle user object or id, null means current user
2103 * @throws coding_exception
2104 * @return string|mixed|null A string containing the value of a single preference. An
2105 * array with all of the preferences or null
2107 function get_user_preferences($name = null, $default = null, $user = null) {
2110 if (is_null($name)) {
2112 } else if (is_numeric($name) or $name === '_lastloaded') {
2113 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2116 if (is_null($user)) {
2118 } else if (isset($user->id
)) {
2119 // Is a valid object.
2120 } else if (is_numeric($user)) {
2121 if ($USER->id
== $user) {
2124 $user = (object)array('id' => (int)$user);
2127 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2130 check_user_preferences_loaded($user);
2134 return $user->preference
;
2135 } else if (isset($user->preference
[$name])) {
2136 // The single string value.
2137 return $user->preference
[$name];
2139 // Default value (null if not specified).
2144 // FUNCTIONS FOR HANDLING TIME.
2147 * Given Gregorian date parts in user time produce a GMT timestamp.
2151 * @param int $year The year part to create timestamp of
2152 * @param int $month The month part to create timestamp of
2153 * @param int $day The day part to create timestamp of
2154 * @param int $hour The hour part to create timestamp of
2155 * @param int $minute The minute part to create timestamp of
2156 * @param int $second The second part to create timestamp of
2157 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2158 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2159 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2160 * applied only if timezone is 99 or string.
2161 * @return int GMT timestamp
2163 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2164 $date = new DateTime('now', core_date
::get_user_timezone_object($timezone));
2165 $date->setDate((int)$year, (int)$month, (int)$day);
2166 $date->setTime((int)$hour, (int)$minute, (int)$second);
2168 $time = $date->getTimestamp();
2170 if ($time === false) {
2171 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2172 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2175 // Moodle BC DST stuff.
2177 $time +
= dst_offset_on($time, $timezone);
2185 * Format a date/time (seconds) as weeks, days, hours etc as needed
2187 * Given an amount of time in seconds, returns string
2188 * formatted nicely as years, days, hours etc as needed
2196 * @param int $totalsecs Time in seconds
2197 * @param stdClass $str Should be a time object
2198 * @return string A nicely formatted date/time string
2200 function format_time($totalsecs, $str = null) {
2202 $totalsecs = abs($totalsecs);
2205 // Create the str structure the slow way.
2206 $str = new stdClass();
2207 $str->day
= get_string('day');
2208 $str->days
= get_string('days');
2209 $str->hour
= get_string('hour');
2210 $str->hours
= get_string('hours');
2211 $str->min
= get_string('min');
2212 $str->mins
= get_string('mins');
2213 $str->sec
= get_string('sec');
2214 $str->secs
= get_string('secs');
2215 $str->year
= get_string('year');
2216 $str->years
= get_string('years');
2219 $years = floor($totalsecs/YEARSECS
);
2220 $remainder = $totalsecs - ($years*YEARSECS
);
2221 $days = floor($remainder/DAYSECS
);
2222 $remainder = $totalsecs - ($days*DAYSECS
);
2223 $hours = floor($remainder/HOURSECS
);
2224 $remainder = $remainder - ($hours*HOURSECS
);
2225 $mins = floor($remainder/MINSECS
);
2226 $secs = $remainder - ($mins*MINSECS
);
2228 $ss = ($secs == 1) ?
$str->sec
: $str->secs
;
2229 $sm = ($mins == 1) ?
$str->min
: $str->mins
;
2230 $sh = ($hours == 1) ?
$str->hour
: $str->hours
;
2231 $sd = ($days == 1) ?
$str->day
: $str->days
;
2232 $sy = ($years == 1) ?
$str->year
: $str->years
;
2241 $oyears = $years .' '. $sy;
2244 $odays = $days .' '. $sd;
2247 $ohours = $hours .' '. $sh;
2250 $omins = $mins .' '. $sm;
2253 $osecs = $secs .' '. $ss;
2257 return trim($oyears .' '. $odays);
2260 return trim($odays .' '. $ohours);
2263 return trim($ohours .' '. $omins);
2266 return trim($omins .' '. $osecs);
2271 return get_string('now');
2275 * Returns a formatted string that represents a date in user time.
2279 * @param int $date the timestamp in UTC, as obtained from the database.
2280 * @param string $format strftime format. You should probably get this using
2281 * get_string('strftime...', 'langconfig');
2282 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2283 * not 99 then daylight saving will not be added.
2284 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2285 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2286 * If false then the leading zero is maintained.
2287 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2288 * @return string the formatted date/time.
2290 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2291 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2292 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2296 * Returns a html "time" tag with both the exact user date with timezone information
2297 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2301 * @param int $date the timestamp in UTC, as obtained from the database.
2302 * @param string $format strftime format. You should probably get this using
2303 * get_string('strftime...', 'langconfig');
2304 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2305 * not 99 then daylight saving will not be added.
2306 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2307 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2308 * If false then the leading zero is maintained.
2309 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2310 * @return string the formatted date/time.
2312 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2313 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2314 if (CLI_SCRIPT
&& !PHPUNIT_TEST
) {
2315 return $userdatestr;
2317 $machinedate = new DateTime();
2318 $machinedate->setTimestamp(intval($date));
2319 $machinedate->setTimezone(core_date
::get_user_timezone_object());
2321 return html_writer
::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime
::W3C
)]);
2325 * Returns a formatted date ensuring it is UTF-8.
2327 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2328 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2330 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2331 * @param string $format strftime format.
2332 * @param int|float|string $tz the user timezone
2333 * @return string the formatted date/time.
2334 * @since Moodle 2.3.3
2336 function date_format_string($date, $format, $tz = 99) {
2339 $localewincharset = null;
2340 // Get the calendar type user is using.
2341 if ($CFG->ostype
== 'WINDOWS') {
2342 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2343 $localewincharset = $calendartype->locale_win_charset();
2346 if ($localewincharset) {
2347 $format = core_text
::convert($format, 'utf-8', $localewincharset);
2350 date_default_timezone_set(core_date
::get_user_timezone($tz));
2351 $datestring = strftime($format, $date);
2352 core_date
::set_default_server_timezone();
2354 if ($localewincharset) {
2355 $datestring = core_text
::convert($datestring, $localewincharset, 'utf-8');
2362 * Given a $time timestamp in GMT (seconds since epoch),
2363 * returns an array that represents the Gregorian date in user time
2367 * @param int $time Timestamp in GMT
2368 * @param float|int|string $timezone user timezone
2369 * @return array An array that represents the date in user time
2371 function usergetdate($time, $timezone=99) {
2372 if ($time === null) {
2373 // PHP8 and PHP7 return different results when getdate(null) is called.
2374 // Display warning and cast to 0 to make sure the usergetdate() behaves consistently on all versions of PHP.
2375 // In the future versions of Moodle we may consider adding a strict typehint.
2376 debugging('usergetdate() expects parameter $time to be int, null given', DEBUG_DEVELOPER
);
2380 date_default_timezone_set(core_date
::get_user_timezone($timezone));
2381 $result = getdate($time);
2382 core_date
::set_default_server_timezone();
2388 * Given a GMT timestamp (seconds since epoch), offsets it by
2389 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2391 * NOTE: this function does not include DST properly,
2392 * you should use the PHP date stuff instead!
2396 * @param int $date Timestamp in GMT
2397 * @param float|int|string $timezone user timezone
2400 function usertime($date, $timezone=99) {
2401 $userdate = new DateTime('@' . $date);
2402 $userdate->setTimezone(core_date
::get_user_timezone_object($timezone));
2403 $dst = dst_offset_on($date, $timezone);
2405 return $date - $userdate->getOffset() +
$dst;
2409 * Get a formatted string representation of an interval between two unix timestamps.
2412 * $intervalstring = get_time_interval_string(12345600, 12345660);
2413 * Will produce the string:
2416 * @param int $time1 unix timestamp
2417 * @param int $time2 unix timestamp
2418 * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2419 * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2421 function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
2422 $dtdate = new DateTime();
2423 $dtdate->setTimeStamp($time1);
2424 $dtdate2 = new DateTime();
2425 $dtdate2->setTimeStamp($time2);
2426 $interval = $dtdate2->diff($dtdate);
2427 $format = empty($format) ?
get_string('dateintervaldayshoursmins', 'langconfig') : $format;
2428 return $interval->format($format);
2432 * Given a time, return the GMT timestamp of the most recent midnight
2433 * for the current user.
2437 * @param int $date Timestamp in GMT
2438 * @param float|int|string $timezone user timezone
2439 * @return int Returns a GMT timestamp
2441 function usergetmidnight($date, $timezone=99) {
2443 $userdate = usergetdate($date, $timezone);
2445 // Time of midnight of this user's day, in GMT.
2446 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2451 * Returns a string that prints the user's timezone
2455 * @param float|int|string $timezone user timezone
2458 function usertimezone($timezone=99) {
2459 $tz = core_date
::get_user_timezone($timezone);
2460 return core_date
::get_localised_timezone($tz);
2464 * Returns a float or a string which denotes the user's timezone
2465 * 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)
2466 * means that for this timezone there are also DST rules to be taken into account
2467 * Checks various settings and picks the most dominant of those which have a value
2471 * @param float|int|string $tz timezone to calculate GMT time offset before
2472 * calculating user timezone, 99 is default user timezone
2473 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2474 * @return float|string
2476 function get_user_timezone($tz = 99) {
2481 isset($CFG->forcetimezone
) ?
$CFG->forcetimezone
: 99,
2482 isset($USER->timezone
) ?
$USER->timezone
: 99,
2483 isset($CFG->timezone
) ?
$CFG->timezone
: 99,
2488 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2489 foreach ($timezones as $nextvalue) {
2490 if ((empty($tz) && !is_numeric($tz)) ||
$tz == 99) {
2494 return is_numeric($tz) ?
(float) $tz : $tz;
2498 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2499 * - Note: Daylight saving only works for string timezones and not for float.
2503 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2504 * @param int|float|string $strtimezone user timezone
2507 function dst_offset_on($time, $strtimezone = null) {
2508 $tz = core_date
::get_user_timezone($strtimezone);
2509 $date = new DateTime('@' . $time);
2510 $date->setTimezone(new DateTimeZone($tz));
2511 if ($date->format('I') == '1') {
2512 if ($tz === 'Australia/Lord_Howe') {
2521 * Calculates when the day appears in specific month
2525 * @param int $startday starting day of the month
2526 * @param int $weekday The day when week starts (normally taken from user preferences)
2527 * @param int $month The month whose day is sought
2528 * @param int $year The year of the month whose day is sought
2531 function find_day_in_month($startday, $weekday, $month, $year) {
2532 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2534 $daysinmonth = days_in_month($month, $year);
2535 $daysinweek = count($calendartype->get_weekdays());
2537 if ($weekday == -1) {
2538 // Don't care about weekday, so return:
2539 // abs($startday) if $startday != -1
2540 // $daysinmonth otherwise.
2541 return ($startday == -1) ?
$daysinmonth : abs($startday);
2544 // From now on we 're looking for a specific weekday.
2545 // Give "end of month" its actual value, since we know it.
2546 if ($startday == -1) {
2547 $startday = -1 * $daysinmonth;
2550 // Starting from day $startday, the sign is the direction.
2551 if ($startday < 1) {
2552 $startday = abs($startday);
2553 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2555 // This is the last such weekday of the month.
2556 $lastinmonth = $daysinmonth +
$weekday - $lastmonthweekday;
2557 if ($lastinmonth > $daysinmonth) {
2558 $lastinmonth -= $daysinweek;
2561 // Find the first such weekday <= $startday.
2562 while ($lastinmonth > $startday) {
2563 $lastinmonth -= $daysinweek;
2566 return $lastinmonth;
2568 $indexweekday = dayofweek($startday, $month, $year);
2570 $diff = $weekday - $indexweekday;
2572 $diff +
= $daysinweek;
2575 // This is the first such weekday of the month equal to or after $startday.
2576 $firstfromindex = $startday +
$diff;
2578 return $firstfromindex;
2583 * Calculate the number of days in a given month
2587 * @param int $month The month whose day count is sought
2588 * @param int $year The year of the month whose day count is sought
2591 function days_in_month($month, $year) {
2592 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2593 return $calendartype->get_num_days_in_month($year, $month);
2597 * Calculate the position in the week of a specific calendar day
2601 * @param int $day The day of the date whose position in the week is sought
2602 * @param int $month The month of the date whose position in the week is sought
2603 * @param int $year The year of the date whose position in the week is sought
2606 function dayofweek($day, $month, $year) {
2607 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2608 return $calendartype->get_weekday($year, $month, $day);
2611 // USER AUTHENTICATION AND LOGIN.
2614 * Returns full login url.
2616 * Any form submissions for authentication to this URL must include username,
2617 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2619 * @return string login url
2621 function get_login_url() {
2624 return "$CFG->wwwroot/login/index.php";
2628 * This function checks that the current user is logged in and has the
2629 * required privileges
2631 * This function checks that the current user is logged in, and optionally
2632 * whether they are allowed to be in a particular course and view a particular
2634 * If they are not logged in, then it redirects them to the site login unless
2635 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2636 * case they are automatically logged in as guests.
2637 * If $courseid is given and the user is not enrolled in that course then the
2638 * user is redirected to the course enrolment page.
2639 * If $cm is given and the course module is hidden and the user is not a teacher
2640 * in the course then the user is redirected to the course home page.
2642 * When $cm parameter specified, this function sets page layout to 'module'.
2643 * You need to change it manually later if some other layout needed.
2645 * @package core_access
2648 * @param mixed $courseorid id of the course or course object
2649 * @param bool $autologinguest default true
2650 * @param object $cm course module object
2651 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2652 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2653 * in order to keep redirects working properly. MDL-14495
2654 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2655 * @return mixed Void, exit, and die depending on path
2656 * @throws coding_exception
2657 * @throws require_login_exception
2658 * @throws moodle_exception
2660 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2661 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2663 // Must not redirect when byteserving already started.
2664 if (!empty($_SERVER['HTTP_RANGE'])) {
2665 $preventredirect = true;
2669 // We cannot redirect for AJAX scripts either.
2670 $preventredirect = true;
2673 // Setup global $COURSE, themes, language and locale.
2674 if (!empty($courseorid)) {
2675 if (is_object($courseorid)) {
2676 $course = $courseorid;
2677 } else if ($courseorid == SITEID
) {
2678 $course = clone($SITE);
2680 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST
);
2683 if ($cm->course
!= $course->id
) {
2684 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2686 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2687 if (!($cm instanceof cm_info
)) {
2688 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2689 // db queries so this is not really a performance concern, however it is obviously
2690 // better if you use get_fast_modinfo to get the cm before calling this.
2691 $modinfo = get_fast_modinfo($course);
2692 $cm = $modinfo->get_cm($cm->id
);
2696 // Do not touch global $COURSE via $PAGE->set_course(),
2697 // the reasons is we need to be able to call require_login() at any time!!
2700 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2704 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2705 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2706 // risk leading the user back to the AJAX request URL.
2707 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT
) {
2708 $setwantsurltome = false;
2711 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2712 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out
) && !empty($CFG->dbsessions
)) {
2713 if ($preventredirect) {
2714 throw new require_login_session_timeout_exception();
2716 if ($setwantsurltome) {
2717 $SESSION->wantsurl
= qualified_me();
2719 redirect(get_login_url());
2723 // If the user is not even logged in yet then make sure they are.
2724 if (!isloggedin()) {
2725 if ($autologinguest and !empty($CFG->guestloginbutton
) and !empty($CFG->autologinguests
)) {
2726 if (!$guest = get_complete_user_data('id', $CFG->siteguest
)) {
2727 // Misconfigured site guest, just redirect to login page.
2728 redirect(get_login_url());
2729 exit; // Never reached.
2731 $lang = isset($SESSION->lang
) ?
$SESSION->lang
: $CFG->lang
;
2732 complete_user_login($guest);
2733 $USER->autologinguest
= true;
2734 $SESSION->lang
= $lang;
2736 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2737 if ($preventredirect) {
2738 throw new require_login_exception('You are not logged in');
2741 if ($setwantsurltome) {
2742 $SESSION->wantsurl
= qualified_me();
2745 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2746 $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
2747 foreach($authsequence as $authname) {
2748 $authplugin = get_auth_plugin($authname);
2749 $authplugin->pre_loginpage_hook();
2752 $modinfo = get_fast_modinfo($course);
2753 $cm = $modinfo->get_cm($cm->id
);
2755 set_access_log_user();
2760 // If we're still not logged in then go to the login page
2761 if (!isloggedin()) {
2762 redirect(get_login_url());
2763 exit; // Never reached.
2768 // Loginas as redirection if needed.
2769 if ($course->id
!= SITEID
and \core\session\manager
::is_loggedinas()) {
2770 if ($USER->loginascontext
->contextlevel
== CONTEXT_COURSE
) {
2771 if ($USER->loginascontext
->instanceid
!= $course->id
) {
2772 print_error('loginasonecourse', '', $CFG->wwwroot
.'/course/view.php?id='.$USER->loginascontext
->instanceid
);
2777 // Check whether the user should be changing password (but only if it is REALLY them).
2778 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager
::is_loggedinas()) {
2779 $userauth = get_auth_plugin($USER->auth
);
2780 if ($userauth->can_change_password() and !$preventredirect) {
2781 if ($setwantsurltome) {
2782 $SESSION->wantsurl
= qualified_me();
2784 if ($changeurl = $userauth->change_password_url()) {
2785 // Use plugin custom url.
2786 redirect($changeurl);
2788 // Use moodle internal method.
2789 redirect($CFG->wwwroot
.'/login/change_password.php');
2791 } else if ($userauth->can_change_password()) {
2792 throw new moodle_exception('forcepasswordchangenotice');
2794 throw new moodle_exception('nopasswordchangeforced', 'auth');
2798 // Check that the user account is properly set up. If we can't redirect to
2799 // edit their profile and this is not a WS request, perform just the lax check.
2800 // It will allow them to use filepicker on the profile edit page.
2802 if ($preventredirect && !WS_SERVER
) {
2803 $usernotfullysetup = user_not_fully_set_up($USER, false);
2805 $usernotfullysetup = user_not_fully_set_up($USER, true);
2808 if ($usernotfullysetup) {
2809 if ($preventredirect) {
2810 throw new moodle_exception('usernotfullysetup');
2812 if ($setwantsurltome) {
2813 $SESSION->wantsurl
= qualified_me();
2815 redirect($CFG->wwwroot
.'/user/edit.php?id='. $USER->id
.'&course='. SITEID
);
2818 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2821 if (\core\session\manager
::is_loggedinas()) {
2822 // During a "logged in as" session we should force all content to be cleaned because the
2823 // logged in user will be viewing potentially malicious user generated content.
2824 // See MDL-63786 for more details.
2825 $CFG->forceclean
= true;
2828 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2830 // Do not bother admins with any formalities, except for activities pending deletion.
2831 if (is_siteadmin() && !($cm && $cm->deletioninprogress
)) {
2832 // Set the global $COURSE.
2834 $PAGE->set_cm($cm, $course);
2835 $PAGE->set_pagelayout('incourse');
2836 } else if (!empty($courseorid)) {
2837 $PAGE->set_course($course);
2839 // Set accesstime or the user will appear offline which messes up messaging.
2840 // Do not update access time for webservice or ajax requests.
2841 if (!WS_SERVER
&& !AJAX_SCRIPT
) {
2842 user_accesstime_log($course->id
);
2845 foreach ($afterlogins as $plugintype => $plugins) {
2846 foreach ($plugins as $pluginfunction) {
2847 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2853 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2854 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2855 if (!defined('NO_SITEPOLICY_CHECK')) {
2856 define('NO_SITEPOLICY_CHECK', false);
2859 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2860 // Do not test if the script explicitly asked for skipping the site policies check.
2861 if (!$USER->policyagreed
&& !is_siteadmin() && !NO_SITEPOLICY_CHECK
) {
2862 $manager = new \core_privacy\local\sitepolicy\
manager();
2863 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2864 if ($preventredirect) {
2865 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2867 if ($setwantsurltome) {
2868 $SESSION->wantsurl
= qualified_me();
2870 redirect($policyurl);
2874 // Fetch the system context, the course context, and prefetch its child contexts.
2875 $sysctx = context_system
::instance();
2876 $coursecontext = context_course
::instance($course->id
, MUST_EXIST
);
2878 $cmcontext = context_module
::instance($cm->id
, MUST_EXIST
);
2883 // If the site is currently under maintenance, then print a message.
2884 if (!empty($CFG->maintenance_enabled
) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2885 if ($preventredirect) {
2886 throw new require_login_exception('Maintenance in progress');
2888 $PAGE->set_context(null);
2889 print_maintenance_message();
2892 // Make sure the course itself is not hidden.
2893 if ($course->id
== SITEID
) {
2894 // Frontpage can not be hidden.
2896 if (is_role_switched($course->id
)) {
2897 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2899 if (!$course->visible
and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2900 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2901 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2902 if ($preventredirect) {
2903 throw new require_login_exception('Course is hidden');
2905 $PAGE->set_context(null);
2906 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2907 // the navigation will mess up when trying to find it.
2908 navigation_node
::override_active_url(new moodle_url('/'));
2909 notice(get_string('coursehidden'), $CFG->wwwroot
.'/');
2914 // Is the user enrolled?
2915 if ($course->id
== SITEID
) {
2916 // Everybody is enrolled on the frontpage.
2918 if (\core\session\manager
::is_loggedinas()) {
2919 // Make sure the REAL person can access this course first.
2920 $realuser = \core\session\manager
::get_realuser();
2921 if (!is_enrolled($coursecontext, $realuser->id
, '', true) and
2922 !is_viewing($coursecontext, $realuser->id
) and !is_siteadmin($realuser->id
)) {
2923 if ($preventredirect) {
2924 throw new require_login_exception('Invalid course login-as access');
2926 $PAGE->set_context(null);
2927 echo $OUTPUT->header();
2928 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot
.'/');
2934 if (is_role_switched($course->id
)) {
2935 // Ok, user had to be inside this course before the switch.
2938 } else if (is_viewing($coursecontext, $USER)) {
2939 // Ok, no need to mess with enrol.
2943 if (isset($USER->enrol
['enrolled'][$course->id
])) {
2944 if ($USER->enrol
['enrolled'][$course->id
] > time()) {
2946 if (isset($USER->enrol
['tempguest'][$course->id
])) {
2947 unset($USER->enrol
['tempguest'][$course->id
]);
2948 remove_temp_course_roles($coursecontext);
2952 unset($USER->enrol
['enrolled'][$course->id
]);
2955 if (isset($USER->enrol
['tempguest'][$course->id
])) {
2956 if ($USER->enrol
['tempguest'][$course->id
] == 0) {
2958 } else if ($USER->enrol
['tempguest'][$course->id
] > time()) {
2962 unset($USER->enrol
['tempguest'][$course->id
]);
2963 remove_temp_course_roles($coursecontext);
2969 $until = enrol_get_enrolment_end($coursecontext->instanceid
, $USER->id
);
2970 if ($until !== false) {
2971 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2973 $until = ENROL_MAX_TIMESTAMP
;
2975 $USER->enrol
['enrolled'][$course->id
] = $until;
2978 } else if (core_course_category
::can_view_course_info($course)) {
2979 $params = array('courseid' => $course->id
, 'status' => ENROL_INSTANCE_ENABLED
);
2980 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2981 $enrols = enrol_get_plugins(true);
2982 // First ask all enabled enrol instances in course if they want to auto enrol user.
2983 foreach ($instances as $instance) {
2984 if (!isset($enrols[$instance->enrol
])) {
2987 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2988 $until = $enrols[$instance->enrol
]->try_autoenrol($instance);
2989 if ($until !== false) {
2991 $until = ENROL_MAX_TIMESTAMP
;
2993 $USER->enrol
['enrolled'][$course->id
] = $until;
2998 // If not enrolled yet try to gain temporary guest access.
3000 foreach ($instances as $instance) {
3001 if (!isset($enrols[$instance->enrol
])) {
3004 // Get a duration for the guest access, a timestamp in the future or false.
3005 $until = $enrols[$instance->enrol
]->try_guestaccess($instance);
3006 if ($until !== false and $until > time()) {
3007 $USER->enrol
['tempguest'][$course->id
] = $until;
3014 // User is not enrolled and is not allowed to browse courses here.
3015 if ($preventredirect) {
3016 throw new require_login_exception('Course is not available');
3018 $PAGE->set_context(null);
3019 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3020 // the navigation will mess up when trying to find it.
3021 navigation_node
::override_active_url(new moodle_url('/'));
3022 notice(get_string('coursehidden'), $CFG->wwwroot
.'/');
3028 if ($preventredirect) {
3029 throw new require_login_exception('Not enrolled');
3031 if ($setwantsurltome) {
3032 $SESSION->wantsurl
= qualified_me();
3034 redirect($CFG->wwwroot
.'/enrol/index.php?id='. $course->id
);
3038 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3039 if ($cm && $cm->deletioninprogress
) {
3040 if ($preventredirect) {
3041 throw new moodle_exception('activityisscheduledfordeletion');
3043 require_once($CFG->dirroot
. '/course/lib.php');
3044 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3047 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3048 if ($cm && !$cm->uservisible
) {
3049 if ($preventredirect) {
3050 throw new require_login_exception('Activity is hidden');
3052 // Get the error message that activity is not available and why (if explanation can be shown to the user).
3053 $PAGE->set_course($course);
3054 $renderer = $PAGE->get_renderer('course');
3055 $message = $renderer->course_section_cm_unavailable_error_message($cm);
3056 redirect(course_get_url($course), $message, null, \core\output\notification
::NOTIFY_ERROR
);
3059 // Set the global $COURSE.
3061 $PAGE->set_cm($cm, $course);
3062 $PAGE->set_pagelayout('incourse');
3063 } else if (!empty($courseorid)) {
3064 $PAGE->set_course($course);
3067 foreach ($afterlogins as $plugintype => $plugins) {
3068 foreach ($plugins as $pluginfunction) {
3069 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3073 // Finally access granted, update lastaccess times.
3074 // Do not update access time for webservice or ajax requests.
3075 if (!WS_SERVER
&& !AJAX_SCRIPT
) {
3076 user_accesstime_log($course->id
);
3081 * A convenience function for where we must be logged in as admin
3084 function require_admin() {
3085 require_login(null, false);
3086 require_capability('moodle/site:config', context_system
::instance());
3090 * This function just makes sure a user is logged out.
3092 * @package core_access
3095 function require_logout() {
3098 if (!isloggedin()) {
3099 // This should not happen often, no need for hooks or events here.
3100 \core\session\manager
::terminate_current();
3104 // Execute hooks before action.
3105 $authplugins = array();
3106 $authsequence = get_enabled_auth_plugins();
3107 foreach ($authsequence as $authname) {
3108 $authplugins[$authname] = get_auth_plugin($authname);
3109 $authplugins[$authname]->prelogout_hook();
3112 // Store info that gets removed during logout.
3113 $sid = session_id();
3114 $event = \core\event\user_loggedout
::create(
3116 'userid' => $USER->id
,
3117 'objectid' => $USER->id
,
3118 'other' => array('sessionid' => $sid),
3121 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3122 $event->add_record_snapshot('sessions', $session);
3125 // Clone of $USER object to be used by auth plugins.
3126 $user = fullclone($USER);
3128 // Delete session record and drop $_SESSION content.
3129 \core\session\manager
::terminate_current();
3131 // Trigger event AFTER action.
3134 // Hook to execute auth plugins redirection after event trigger.
3135 foreach ($authplugins as $authplugin) {
3136 $authplugin->postlogout_hook($user);
3141 * Weaker version of require_login()
3143 * This is a weaker version of {@link require_login()} which only requires login
3144 * when called from within a course rather than the site page, unless
3145 * the forcelogin option is turned on.
3146 * @see require_login()
3148 * @package core_access
3151 * @param mixed $courseorid The course object or id in question
3152 * @param bool $autologinguest Allow autologin guests if that is wanted
3153 * @param object $cm Course activity module if known
3154 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3155 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3156 * in order to keep redirects working properly. MDL-14495
3157 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3159 * @throws coding_exception
3161 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3162 global $CFG, $PAGE, $SITE;
3163 $issite = ((is_object($courseorid) and $courseorid->id
== SITEID
)
3164 or (!is_object($courseorid) and $courseorid == SITEID
));
3165 if ($issite && !empty($cm) && !($cm instanceof cm_info
)) {
3166 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3167 // db queries so this is not really a performance concern, however it is obviously
3168 // better if you use get_fast_modinfo to get the cm before calling this.
3169 if (is_object($courseorid)) {
3170 $course = $courseorid;
3172 $course = clone($SITE);
3174 $modinfo = get_fast_modinfo($course);
3175 $cm = $modinfo->get_cm($cm->id
);
3177 if (!empty($CFG->forcelogin
)) {
3178 // Login required for both SITE and courses.
3179 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3181 } else if ($issite && !empty($cm) and !$cm->uservisible
) {
3182 // Always login for hidden activities.
3183 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3185 } else if (isloggedin() && !isguestuser()) {
3186 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3187 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3189 } else if ($issite) {
3190 // Login for SITE not required.
3191 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3192 if (!empty($courseorid)) {
3193 if (is_object($courseorid)) {
3194 $course = $courseorid;
3196 $course = clone $SITE;
3199 if ($cm->course
!= $course->id
) {
3200 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3202 $PAGE->set_cm($cm, $course);
3203 $PAGE->set_pagelayout('incourse');
3205 $PAGE->set_course($course);
3208 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3209 $PAGE->set_course($PAGE->course
);
3211 // Do not update access time for webservice or ajax requests.
3212 if (!WS_SERVER
&& !AJAX_SCRIPT
) {
3213 user_accesstime_log(SITEID
);
3218 // Course login always required.
3219 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3224 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3226 * @param string $keyvalue the key value
3227 * @param string $script unique script identifier
3228 * @param int $instance instance id
3229 * @return stdClass the key entry in the user_private_key table
3231 * @throws moodle_exception
3233 function validate_user_key($keyvalue, $script, $instance) {
3236 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3237 print_error('invalidkey');
3240 if (!empty($key->validuntil
) and $key->validuntil
< time()) {
3241 print_error('expiredkey');
3244 if ($key->iprestriction
) {
3245 $remoteaddr = getremoteaddr(null);
3246 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction
)) {
3247 print_error('ipmismatch');
3254 * Require key login. Function terminates with error if key not found or incorrect.
3256 * @uses NO_MOODLE_COOKIES
3257 * @uses PARAM_ALPHANUM
3258 * @param string $script unique script identifier
3259 * @param int $instance optional instance id
3260 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3261 * @return int Instance ID
3263 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3266 if (!NO_MOODLE_COOKIES
) {
3267 print_error('sessioncookiesdisable');
3271 \core\session\manager
::write_close();
3273 if (null === $keyvalue) {
3274 $keyvalue = required_param('key', PARAM_ALPHANUM
);
3277 $key = validate_user_key($keyvalue, $script, $instance);
3279 if (!$user = $DB->get_record('user', array('id' => $key->userid
))) {
3280 print_error('invaliduserid');
3283 core_user
::require_active_user($user, true, true);
3285 // Emulate normal session.
3286 enrol_check_plugins($user);
3287 \core\session\manager
::set_user($user);
3289 // Note we are not using normal login.
3290 if (!defined('USER_KEY_LOGIN')) {
3291 define('USER_KEY_LOGIN', true);
3294 // Return instance id - it might be empty.
3295 return $key->instance
;
3299 * Creates a new private user access key.
3301 * @param string $script unique target identifier
3302 * @param int $userid
3303 * @param int $instance optional instance id
3304 * @param string $iprestriction optional ip restricted access
3305 * @param int $validuntil key valid only until given data
3306 * @return string access key value
3308 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3311 $key = new stdClass();
3312 $key->script
= $script;
3313 $key->userid
= $userid;
3314 $key->instance
= $instance;
3315 $key->iprestriction
= $iprestriction;
3316 $key->validuntil
= $validuntil;
3317 $key->timecreated
= time();
3319 // Something long and unique.
3320 $key->value
= md5($userid.'_'.time().random_string(40));
3321 while ($DB->record_exists('user_private_key', array('value' => $key->value
))) {
3323 $key->value
= md5($userid.'_'.time().random_string(40));
3325 $DB->insert_record('user_private_key', $key);
3330 * Delete the user's new private user access keys for a particular script.
3332 * @param string $script unique target identifier
3333 * @param int $userid
3336 function delete_user_key($script, $userid) {
3338 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3342 * Gets a private user access key (and creates one if one doesn't exist).
3344 * @param string $script unique target identifier
3345 * @param int $userid
3346 * @param int $instance optional instance id
3347 * @param string $iprestriction optional ip restricted access
3348 * @param int $validuntil key valid only until given date
3349 * @return string access key value
3351 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3354 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3355 'instance' => $instance, 'iprestriction' => $iprestriction,
3356 'validuntil' => $validuntil))) {
3359 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3365 * Modify the user table by setting the currently logged in user's last login to now.
3367 * @return bool Always returns true
3369 function update_user_login_times() {
3370 global $USER, $DB, $SESSION;
3372 if (isguestuser()) {
3373 // Do not update guest access times/ips for performance.
3379 $user = new stdClass();
3380 $user->id
= $USER->id
;
3382 // Make sure all users that logged in have some firstaccess.
3383 if ($USER->firstaccess
== 0) {
3384 $USER->firstaccess
= $user->firstaccess
= $now;
3387 // Store the previous current as lastlogin.
3388 $USER->lastlogin
= $user->lastlogin
= $USER->currentlogin
;
3390 $USER->currentlogin
= $user->currentlogin
= $now;
3392 // Function user_accesstime_log() may not update immediately, better do it here.
3393 $USER->lastaccess
= $user->lastaccess
= $now;
3394 $SESSION->userpreviousip
= $USER->lastip
;
3395 $USER->lastip
= $user->lastip
= getremoteaddr();
3397 // Note: do not call user_update_user() here because this is part of the login process,
3398 // the login event means that these fields were updated.
3399 $DB->update_record('user', $user);
3404 * Determines if a user has completed setting up their account.
3406 * The lax mode (with $strict = false) has been introduced for special cases
3407 * only where we want to skip certain checks intentionally. This is valid in
3408 * certain mnet or ajax scenarios when the user cannot / should not be
3409 * redirected to edit their profile. In most cases, you should perform the
3412 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3413 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3416 function user_not_fully_set_up($user, $strict = true) {
3418 require_once($CFG->dirroot
.'/user/profile/lib.php');
3420 if (isguestuser($user)) {
3424 if (empty($user->firstname
) or empty($user->lastname
) or empty($user->email
) or over_bounce_threshold($user)) {
3429 if (empty($user->id
)) {
3430 // Strict mode can be used with existing accounts only.
3433 if (!profile_has_required_custom_fields_set($user->id
)) {
3442 * Check whether the user has exceeded the bounce threshold
3444 * @param stdClass $user A {@link $USER} object
3445 * @return bool true => User has exceeded bounce threshold
3447 function over_bounce_threshold($user) {
3450 if (empty($CFG->handlebounces
)) {
3454 if (empty($user->id
)) {
3455 // No real (DB) user, nothing to do here.
3459 // Set sensible defaults.
3460 if (empty($CFG->minbounces
)) {
3461 $CFG->minbounces
= 10;
3463 if (empty($CFG->bounceratio
)) {
3464 $CFG->bounceratio
= .20;
3468 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id
, 'name' => 'email_bounce_count'))) {
3469 $bouncecount = $bounce->value
;
3471 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_send_count'))) {
3472 $sendcount = $send->value
;
3474 return ($bouncecount >= $CFG->minbounces
&& $bouncecount/$sendcount >= $CFG->bounceratio
);
3478 * Used to increment or reset email sent count
3480 * @param stdClass $user object containing an id
3481 * @param bool $reset will reset the count to 0
3484 function set_send_count($user, $reset=false) {
3487 if (empty($user->id
)) {
3488 // No real (DB) user, nothing to do here.
3492 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_send_count'))) {
3493 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3494 $DB->update_record('user_preferences', $pref);
3495 } else if (!empty($reset)) {
3496 // If it's not there and we're resetting, don't bother. Make a new one.
3497 $pref = new stdClass();
3498 $pref->name
= 'email_send_count';
3500 $pref->userid
= $user->id
;
3501 $DB->insert_record('user_preferences', $pref, false);
3506 * Increment or reset user's email bounce count
3508 * @param stdClass $user object containing an id
3509 * @param bool $reset will reset the count to 0
3511 function set_bounce_count($user, $reset=false) {
3514 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_bounce_count'))) {
3515 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3516 $DB->update_record('user_preferences', $pref);
3517 } else if (!empty($reset)) {
3518 // If it's not there and we're resetting, don't bother. Make a new one.
3519 $pref = new stdClass();
3520 $pref->name
= 'email_bounce_count';
3522 $pref->userid
= $user->id
;
3523 $DB->insert_record('user_preferences', $pref, false);
3528 * Determines if the logged in user is currently moving an activity
3530 * @param int $courseid The id of the course being tested
3533 function ismoving($courseid) {
3536 if (!empty($USER->activitycopy
)) {
3537 return ($USER->activitycopycourse
== $courseid);
3543 * Returns a persons full name
3545 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3546 * The result may depend on system settings or language. 'override' will force the alternativefullnameformat to be used. In
3547 * English, fullname as well as alternativefullnameformat is set to 'firstname lastname' by default. But you could have
3548 * fullname set to 'firstname lastname' and alternativefullnameformat set to 'firstname middlename alternatename lastname'.
3550 * @param stdClass $user A {@link $USER} object to get full name of.
3551 * @param bool $override If true then the alternativefullnameformat format rather than fullnamedisplay format will be used.
3554 function fullname($user, $override=false) {
3555 global $CFG, $SESSION;
3557 if (!isset($user->firstname
) and !isset($user->lastname
)) {
3561 // Get all of the name fields.
3562 $allnames = \core_user\fields
::get_name_fields();
3563 if ($CFG->debugdeveloper
) {
3564 foreach ($allnames as $allname) {
3565 if (!property_exists($user, $allname)) {
3566 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3567 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER
);
3568 // Message has been sent, no point in sending the message multiple times.
3575 if (!empty($CFG->forcefirstname
)) {
3576 $user->firstname
= $CFG->forcefirstname
;
3578 if (!empty($CFG->forcelastname
)) {
3579 $user->lastname
= $CFG->forcelastname
;
3583 if (!empty($SESSION->fullnamedisplay
)) {
3584 $CFG->fullnamedisplay
= $SESSION->fullnamedisplay
;
3588 // If the fullnamedisplay setting is available, set the template to that.
3589 if (isset($CFG->fullnamedisplay
)) {
3590 $template = $CFG->fullnamedisplay
;
3592 // If the template is empty, or set to language, return the language string.
3593 if ((empty($template) ||
$template == 'language') && !$override) {
3594 return get_string('fullnamedisplay', null, $user);
3597 // Check to see if we are displaying according to the alternative full name format.
3599 if (empty($CFG->alternativefullnameformat
) ||
$CFG->alternativefullnameformat
== 'language') {
3600 // Default to show just the user names according to the fullnamedisplay string.
3601 return get_string('fullnamedisplay', null, $user);
3603 // If the override is true, then change the template to use the complete name.
3604 $template = $CFG->alternativefullnameformat
;
3608 $requirednames = array();
3609 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3610 foreach ($allnames as $allname) {
3611 if (strpos($template, $allname) !== false) {
3612 $requirednames[] = $allname;
3616 $displayname = $template;
3617 // Switch in the actual data into the template.
3618 foreach ($requirednames as $altname) {
3619 if (isset($user->$altname)) {
3620 // Using empty() on the below if statement causes breakages.
3621 if ((string)$user->$altname == '') {
3622 $displayname = str_replace($altname, 'EMPTY', $displayname);
3624 $displayname = str_replace($altname, $user->$altname, $displayname);
3627 $displayname = str_replace($altname, 'EMPTY', $displayname);
3630 // Tidy up any misc. characters (Not perfect, but gets most characters).
3631 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3632 // katakana and parenthesis.
3633 $patterns = array();
3634 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3635 // filled in by a user.
3636 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3637 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3638 // This regular expression is to remove any double spaces in the display name.
3639 $patterns[] = '/\s{2,}/u';
3640 foreach ($patterns as $pattern) {
3641 $displayname = preg_replace($pattern, ' ', $displayname);
3644 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3645 $displayname = trim($displayname);
3646 if (empty($displayname)) {
3647 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3648 // people in general feel is a good setting to fall back on.
3649 $displayname = $user->firstname
;
3651 return $displayname;
3655 * Reduces lines of duplicated code for getting user name fields.
3657 * See also {@link user_picture::unalias()}
3659 * @param object $addtoobject Object to add user name fields to.
3660 * @param object $secondobject Object that contains user name field information.
3661 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3662 * @param array $additionalfields Additional fields to be matched with data in the second object.
3663 * The key can be set to the user table field name.
3664 * @return object User name fields.
3666 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3668 foreach (\core_user\fields
::get_name_fields() as $field) {
3669 $fields[$field] = $prefix . $field;
3671 if ($additionalfields) {
3672 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3673 // the key is a number and then sets the key to the array value.
3674 foreach ($additionalfields as $key => $value) {
3675 if (is_numeric($key)) {
3676 $additionalfields[$value] = $prefix . $value;
3677 unset($additionalfields[$key]);
3679 $additionalfields[$key] = $prefix . $value;
3682 $fields = array_merge($fields, $additionalfields);
3684 foreach ($fields as $key => $field) {
3685 // Important that we have all of the user name fields present in the object that we are sending back.
3686 $addtoobject->$key = '';
3687 if (isset($secondobject->$field)) {
3688 $addtoobject->$key = $secondobject->$field;
3691 return $addtoobject;
3695 * Returns an array of values in order of occurance in a provided string.
3696 * The key in the result is the character postion in the string.
3698 * @param array $values Values to be found in the string format
3699 * @param string $stringformat The string which may contain values being searched for.
3700 * @return array An array of values in order according to placement in the string format.
3702 function order_in_string($values, $stringformat) {
3703 $valuearray = array();
3704 foreach ($values as $value) {
3705 $pattern = "/$value\b/";
3706 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3707 if (preg_match($pattern, $stringformat)) {
3708 $replacement = "thing";
3709 // Replace the value with something more unique to ensure we get the right position when using strpos().
3710 $newformat = preg_replace($pattern, $replacement, $stringformat);
3711 $position = strpos($newformat, $replacement);
3712 $valuearray[$position] = $value;
3720 * Returns whether a given authentication plugin exists.
3722 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3723 * @return boolean Whether the plugin is available.
3725 function exists_auth_plugin($auth) {
3728 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3729 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3735 * Checks if a given plugin is in the list of enabled authentication plugins.
3737 * @param string $auth Authentication plugin.
3738 * @return boolean Whether the plugin is enabled.
3740 function is_enabled_auth($auth) {
3745 $enabled = get_enabled_auth_plugins();
3747 return in_array($auth, $enabled);
3751 * Returns an authentication plugin instance.
3753 * @param string $auth name of authentication plugin
3754 * @return auth_plugin_base An instance of the required authentication plugin.
3756 function get_auth_plugin($auth) {
3759 // Check the plugin exists first.
3760 if (! exists_auth_plugin($auth)) {
3761 print_error('authpluginnotfound', 'debug', '', $auth);
3764 // Return auth plugin instance.
3765 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3766 $class = "auth_plugin_$auth";
3771 * Returns array of active auth plugins.
3773 * @param bool $fix fix $CFG->auth if needed. Only set if logged in as admin.
3776 function get_enabled_auth_plugins($fix=false) {
3779 $default = array('manual', 'nologin');
3781 if (empty($CFG->auth
)) {
3784 $auths = explode(',', $CFG->auth
);
3787 $auths = array_unique($auths);
3788 $oldauthconfig = implode(',', $auths);
3789 foreach ($auths as $k => $authname) {
3790 if (in_array($authname, $default)) {
3791 // The manual and nologin plugin never need to be stored.
3793 } else if (!exists_auth_plugin($authname)) {
3794 debugging(get_string('authpluginnotfound', 'debug', $authname));
3799 // Ideally only explicit interaction from a human admin should trigger a
3800 // change in auth config, see MDL-70424 for details.
3802 $newconfig = implode(',', $auths);
3803 if (!isset($CFG->auth
) or $newconfig != $CFG->auth
) {
3804 add_to_config_log('auth', $oldauthconfig, $newconfig, 'core');
3805 set_config('auth', $newconfig);
3809 return (array_merge($default, $auths));
3813 * Returns true if an internal authentication method is being used.
3814 * if method not specified then, global default is assumed
3816 * @param string $auth Form of authentication required
3819 function is_internal_auth($auth) {
3820 // Throws error if bad $auth.
3821 $authplugin = get_auth_plugin($auth);
3822 return $authplugin->is_internal();
3826 * Returns true if the user is a 'restored' one.
3828 * Used in the login process to inform the user and allow him/her to reset the password
3830 * @param string $username username to be checked
3833 function is_restored_user($username) {
3836 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'password' => 'restored'));
3840 * Returns an array of user fields
3842 * @return array User field/column names
3844 function get_user_fieldnames() {
3847 $fieldarray = $DB->get_columns('user');
3848 unset($fieldarray['id']);
3849 $fieldarray = array_keys($fieldarray);
3855 * Returns the string of the language for the new user.
3857 * @return string language for the new user
3859 function get_newuser_language() {
3860 global $CFG, $SESSION;
3861 return (!empty($CFG->autolangusercreation
) && !empty($SESSION->lang
)) ?
$SESSION->lang
: $CFG->lang
;
3865 * Creates a bare-bones user record
3867 * @todo Outline auth types and provide code example
3869 * @param string $username New user's username to add to record
3870 * @param string $password New user's password to add to record
3871 * @param string $auth Form of authentication required
3872 * @return stdClass A complete user object
3874 function create_user_record($username, $password, $auth = 'manual') {
3875 global $CFG, $DB, $SESSION;
3876 require_once($CFG->dirroot
.'/user/profile/lib.php');
3877 require_once($CFG->dirroot
.'/user/lib.php');
3879 // Just in case check text case.
3880 $username = trim(core_text
::strtolower($username));
3882 $authplugin = get_auth_plugin($auth);
3883 $customfields = $authplugin->get_custom_user_profile_fields();
3884 $newuser = new stdClass();
3885 if ($newinfo = $authplugin->get_userinfo($username)) {
3886 $newinfo = truncate_userinfo($newinfo);
3887 foreach ($newinfo as $key => $value) {
3888 if (in_array($key, $authplugin->userfields
) ||
(in_array($key, $customfields))) {
3889 $newuser->$key = $value;
3894 if (!empty($newuser->email
)) {
3895 if (email_is_not_allowed($newuser->email
)) {
3896 unset($newuser->email
);
3900 if (!isset($newuser->city
)) {
3901 $newuser->city
= '';
3904 $newuser->auth
= $auth;
3905 $newuser->username
= $username;
3908 // user CFG lang for user if $newuser->lang is empty
3909 // or $user->lang is not an installed language.
3910 if (empty($newuser->lang
) ||
!get_string_manager()->translation_exists($newuser->lang
)) {
3911 $newuser->lang
= get_newuser_language();
3913 $newuser->confirmed
= 1;
3914 $newuser->lastip
= getremoteaddr();
3915 $newuser->timecreated
= time();
3916 $newuser->timemodified
= $newuser->timecreated
;
3917 $newuser->mnethostid
= $CFG->mnet_localhost_id
;
3919 $newuser->id
= user_create_user($newuser, false, false);
3921 // Save user profile data.
3922 profile_save_data($newuser);
3924 $user = get_complete_user_data('id', $newuser->id
);
3925 if (!empty($CFG->{'auth_'.$newuser->auth
.'_forcechangepassword'})) {
3926 set_user_preference('auth_forcepasswordchange', 1, $user);
3928 // Set the password.
3929 update_internal_user_password($user, $password);
3932 \core\event\user_created
::create_from_userid($newuser->id
)->trigger();
3938 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3940 * @param string $username user's username to update the record
3941 * @return stdClass A complete user object
3943 function update_user_record($username) {
3945 // Just in case check text case.
3946 $username = trim(core_text
::strtolower($username));
3948 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
), '*', MUST_EXIST
);
3949 return update_user_record_by_id($oldinfo->id
);
3953 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3955 * @param int $id user id
3956 * @return stdClass A complete user object
3958 function update_user_record_by_id($id) {
3960 require_once($CFG->dirroot
."/user/profile/lib.php");
3961 require_once($CFG->dirroot
.'/user/lib.php');
3963 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'id' => $id, 'deleted' => 0);
3964 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST
);
3967 $userauth = get_auth_plugin($oldinfo->auth
);
3969 if ($newinfo = $userauth->get_userinfo($oldinfo->username
)) {
3970 $newinfo = truncate_userinfo($newinfo);
3971 $customfields = $userauth->get_custom_user_profile_fields();
3973 foreach ($newinfo as $key => $value) {
3974 $iscustom = in_array($key, $customfields);
3976 $key = strtolower($key);
3978 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3979 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3980 // Unknown or must not be changed.
3983 if (empty($userauth->config
->{'field_updatelocal_' . $key}) ||
empty($userauth->config
->{'field_lock_' . $key})) {
3986 $confval = $userauth->config
->{'field_updatelocal_' . $key};
3987 $lockval = $userauth->config
->{'field_lock_' . $key};
3988 if ($confval === 'onlogin') {
3989 // MDL-4207 Don't overwrite modified user profile values with
3990 // empty LDAP values when 'unlocked if empty' is set. The purpose
3991 // of the setting 'unlocked if empty' is to allow the user to fill
3992 // in a value for the selected field _if LDAP is giving
3993 // nothing_ for this field. Thus it makes sense to let this value
3994 // stand in until LDAP is giving a value for this field.
3995 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3996 if ($iscustom ||
(in_array($key, $userauth->userfields
) &&
3997 ((string)$oldinfo->$key !== (string)$value))) {
3998 $newuser[$key] = (string)$value;
4004 $newuser['id'] = $oldinfo->id
;
4005 $newuser['timemodified'] = time();
4006 user_update_user((object) $newuser, false, false);
4008 // Save user profile data.
4009 profile_save_data((object) $newuser);
4012 \core\event\user_updated
::create_from_userid($newuser['id'])->trigger();
4016 return get_complete_user_data('id', $oldinfo->id
);
4020 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4022 * @param array $info Array of user properties to truncate if needed
4023 * @return array The now truncated information that was passed in
4025 function truncate_userinfo(array $info) {
4026 // Define the limits.
4035 'institution' => 255,
4036 'department' => 255,
4042 // Apply where needed.
4043 foreach (array_keys($info) as $key) {
4044 if (!empty($limit[$key])) {
4045 $info[$key] = trim(core_text
::substr($info[$key], 0, $limit[$key]));
4053 * Marks user deleted in internal user database and notifies the auth plugin.
4054 * Also unenrols user from all roles and does other cleanup.
4056 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4058 * @param stdClass $user full user object before delete
4059 * @return boolean success
4060 * @throws coding_exception if invalid $user parameter detected
4062 function delete_user(stdClass
$user) {
4063 global $CFG, $DB, $SESSION;
4064 require_once($CFG->libdir
.'/grouplib.php');
4065 require_once($CFG->libdir
.'/gradelib.php');
4066 require_once($CFG->dirroot
.'/message/lib.php');
4067 require_once($CFG->dirroot
.'/user/lib.php');
4069 // Make sure nobody sends bogus record type as parameter.
4070 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4071 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4074 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4075 if (!$user = $DB->get_record('user', array('id' => $user->id
))) {
4076 debugging('Attempt to delete unknown user account.');
4080 // There must be always exactly one guest record, originally the guest account was identified by username only,
4081 // now we use $CFG->siteguest for performance reasons.
4082 if ($user->username
=== 'guest' or isguestuser($user)) {
4083 debugging('Guest user account can not be deleted.');
4087 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4088 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4089 if ($user->auth
=== 'manual' and is_siteadmin($user)) {
4090 debugging('Local administrator accounts can not be deleted.');
4094 // Allow plugins to use this user object before we completely delete it.
4095 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4096 foreach ($pluginsfunction as $plugintype => $plugins) {
4097 foreach ($plugins as $pluginfunction) {
4098 $pluginfunction($user);
4103 // Keep user record before updating it, as we have to pass this to user_deleted event.
4104 $olduser = clone $user;
4106 // Keep a copy of user context, we need it for event.
4107 $usercontext = context_user
::instance($user->id
);
4109 // Delete all grades - backup is kept in grade_grades_history table.
4110 grade_user_delete($user->id
);
4112 // TODO: remove from cohorts using standard API here.
4114 // Remove user tags.
4115 core_tag_tag
::remove_all_item_tags('core', 'user', $user->id
);
4117 // Unconditionally unenrol from all courses.
4118 enrol_user_delete($user);
4120 // Unenrol from all roles in all contexts.
4121 // This might be slow but it is really needed - modules might do some extra cleanup!
4122 role_unassign_all(array('userid' => $user->id
));
4124 // Notify the competency subsystem.
4125 \core_competency\api
::hook_user_deleted($user->id
);
4127 // Now do a brute force cleanup.
4129 // Delete all user events and subscription events.
4130 $DB->delete_records_select('event', 'userid = :userid AND subscriptionid IS NOT NULL', ['userid' => $user->id
]);
4132 // Now, delete all calendar subscription from the user.
4133 $DB->delete_records('event_subscriptions', ['userid' => $user->id
]);
4135 // Remove from all cohorts.
4136 $DB->delete_records('cohort_members', array('userid' => $user->id
));
4138 // Remove from all groups.
4139 $DB->delete_records('groups_members', array('userid' => $user->id
));
4141 // Brute force unenrol from all courses.
4142 $DB->delete_records('user_enrolments', array('userid' => $user->id
));
4144 // Purge user preferences.
4145 $DB->delete_records('user_preferences', array('userid' => $user->id
));
4147 // Purge user extra profile info.
4148 $DB->delete_records('user_info_data', array('userid' => $user->id
));
4150 // Purge log of previous password hashes.
4151 $DB->delete_records('user_password_history', array('userid' => $user->id
));
4153 // Last course access not necessary either.
4154 $DB->delete_records('user_lastaccess', array('userid' => $user->id
));
4155 // Remove all user tokens.
4156 $DB->delete_records('external_tokens', array('userid' => $user->id
));
4158 // Unauthorise the user for all services.
4159 $DB->delete_records('external_services_users', array('userid' => $user->id
));
4161 // Remove users private keys.
4162 $DB->delete_records('user_private_key', array('userid' => $user->id
));
4164 // Remove users customised pages.
4165 $DB->delete_records('my_pages', array('userid' => $user->id
, 'private' => 1));
4167 // Remove user's oauth2 refresh tokens, if present.
4168 $DB->delete_records('oauth2_refresh_token', array('userid' => $user->id
));
4170 // Delete user from $SESSION->bulk_users.
4171 if (isset($SESSION->bulk_users
[$user->id
])) {
4172 unset($SESSION->bulk_users
[$user->id
]);
4175 // Force logout - may fail if file based sessions used, sorry.
4176 \core\session\manager
::kill_user_sessions($user->id
);
4178 // Generate username from email address, or a fake email.
4179 $delemail = !empty($user->email
) ?
$user->email
: $user->username
. '.' . $user->id
. '@unknownemail.invalid';
4182 $deltimelength = core_text
::strlen((string) $deltime);
4184 // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
4185 $delname = clean_param($delemail, PARAM_USERNAME
);
4186 $delname = core_text
::substr($delname, 0, 100 - ($deltimelength +
1)) . ".{$deltime}";
4188 // Workaround for bulk deletes of users with the same email address.
4189 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4193 // Mark internal user record as "deleted".
4194 $updateuser = new stdClass();
4195 $updateuser->id
= $user->id
;
4196 $updateuser->deleted
= 1;
4197 $updateuser->username
= $delname; // Remember it just in case.
4198 $updateuser->email
= md5($user->username
);// Store hash of username, useful importing/restoring users.
4199 $updateuser->idnumber
= ''; // Clear this field to free it up.
4200 $updateuser->picture
= 0;
4201 $updateuser->timemodified
= $deltime;
4203 // Don't trigger update event, as user is being deleted.
4204 user_update_user($updateuser, false, false);
4206 // Delete all content associated with the user context, but not the context itself.
4207 $usercontext->delete_content();
4209 // Delete any search data.
4210 \core_search\manager
::context_deleted($usercontext);
4212 // Any plugin that needs to cleanup should register this event.
4214 $event = \core\event\user_deleted
::create(
4216 'objectid' => $user->id
,
4217 'relateduserid' => $user->id
,
4218 'context' => $usercontext,
4220 'username' => $user->username
,
4221 'email' => $user->email
,
4222 'idnumber' => $user->idnumber
,
4223 'picture' => $user->picture
,
4224 'mnethostid' => $user->mnethostid
4228 $event->add_record_snapshot('user', $olduser);
4231 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4232 // should know about this updated property persisted to the user's table.
4233 $user->timemodified
= $updateuser->timemodified
;
4235 // Notify auth plugin - do not block the delete even when plugin fails.
4236 $authplugin = get_auth_plugin($user->auth
);
4237 $authplugin->user_delete($user);
4243 * Retrieve the guest user object.
4245 * @return stdClass A {@link $USER} object
4247 function guest_user() {
4250 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest
))) {
4251 $newuser->confirmed
= 1;
4252 $newuser->lang
= get_newuser_language();
4253 $newuser->lastip
= getremoteaddr();
4260 * Authenticates a user against the chosen authentication mechanism
4262 * Given a username and password, this function looks them
4263 * up using the currently selected authentication mechanism,
4264 * and if the authentication is successful, it returns a
4265 * valid $user object from the 'user' table.
4267 * Uses auth_ functions from the currently active auth module
4269 * After authenticate_user_login() returns success, you will need to
4270 * log that the user has logged in, and call complete_user_login() to set
4273 * Note: this function works only with non-mnet accounts!
4275 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4276 * @param string $password User's password
4277 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4278 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4279 * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4280 * @return stdClass|false A {@link $USER} object or false if error
4282 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4283 global $CFG, $DB, $PAGE;
4284 require_once("$CFG->libdir/authlib.php");
4286 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id
)) {
4287 // we have found the user
4289 } else if (!empty($CFG->authloginviaemail
)) {
4290 if ($email = clean_param($username, PARAM_EMAIL
)) {
4291 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4292 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'email' => $email);
4293 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4294 if (count($users) === 1) {
4295 // Use email for login only if unique.
4296 $user = reset($users);
4297 $user = get_complete_user_data('id', $user->id
);
4298 $username = $user->username
;
4304 // Make sure this request came from the login form.
4305 if (!\core\session\manager
::validate_login_token($logintoken)) {
4306 $failurereason = AUTH_LOGIN_FAILED
;
4308 // Trigger login failed event (specifying the ID of the found user, if available).
4309 \core\event\user_login_failed
::create([
4310 'userid' => ($user->id ??
0),
4312 'username' => $username,
4313 'reason' => $failurereason,
4317 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4321 $authsenabled = get_enabled_auth_plugins();
4324 // Use manual if auth not set.
4325 $auth = empty($user->auth
) ?
'manual' : $user->auth
;
4327 if (in_array($user->auth
, $authsenabled)) {
4328 $authplugin = get_auth_plugin($user->auth
);
4329 $authplugin->pre_user_login_hook($user);
4332 if (!empty($user->suspended
)) {
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 Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4342 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4343 // Legacy way to suspend user.
4344 $failurereason = AUTH_LOGIN_SUSPENDED
;
4346 // Trigger login failed event.
4347 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4348 'other' => array('username' => $username, 'reason' => $failurereason)));
4350 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4353 $auths = array($auth);
4356 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4357 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'deleted' => 1))) {
4358 $failurereason = AUTH_LOGIN_NOUSER
;
4360 // Trigger login failed event.
4361 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4362 'reason' => $failurereason)));
4364 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4368 // User does not exist.
4369 $auths = $authsenabled;
4370 $user = new stdClass();
4374 if ($ignorelockout) {
4375 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4376 // or this function is called from a SSO script.
4377 } else if ($user->id
) {
4378 // Verify login lockout after other ways that may prevent user login.
4379 if (login_is_lockedout($user)) {
4380 $failurereason = AUTH_LOGIN_LOCKOUT
;
4382 // Trigger login failed event.
4383 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4384 'other' => array('username' => $username, 'reason' => $failurereason)));
4387 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4391 // We can not lockout non-existing accounts.
4394 foreach ($auths as $auth) {
4395 $authplugin = get_auth_plugin($auth);
4397 // On auth fail fall through to the next plugin.
4398 if (!$authplugin->user_login($username, $password)) {
4402 // Before performing login actions, check if user still passes password policy, if admin setting is enabled.
4403 if (!empty($CFG->passwordpolicycheckonlogin
)) {
4405 $passed = check_password_policy($password, $errmsg, $user);
4407 // First trigger event for failure.
4408 $failedevent = \core\event\user_password_policy_failed
::create_from_user($user);
4409 $failedevent->trigger();
4411 // If able to change password, set flag and move on.
4412 if ($authplugin->can_change_password()) {
4413 // Check if we are on internal change password page, or service is external, don't show notification.
4414 $internalchangeurl = new moodle_url('/login/change_password.php');
4415 if (!($PAGE->has_set_url() && $internalchangeurl->compare($PAGE->url
)) && $authplugin->is_internal()) {
4416 \core\notification
::error(get_string('passwordpolicynomatch', '', $errmsg));
4418 set_user_preference('auth_forcepasswordchange', 1, $user);
4419 } else if ($authplugin->can_reset_password()) {
4420 // Else force a reset if possible.
4421 \core\notification
::error(get_string('forcepasswordresetnotice', '', $errmsg));
4422 redirect(new moodle_url('/login/forgot_password.php'));
4424 $notifymsg = get_string('forcepasswordresetfailurenotice', '', $errmsg);
4425 // If support page is set, add link for help.
4426 if (!empty($CFG->supportpage
)) {
4427 $link = \html_writer
::link($CFG->supportpage
, $CFG->supportpage
);
4428 $link = \html_writer
::tag('p', $link);
4429 $notifymsg .= $link;
4432 // If no change or reset is possible, add a notification for user.
4433 \core\notification
::error($notifymsg);
4438 // Successful authentication.
4440 // User already exists in database.
4441 if (empty($user->auth
)) {
4442 // For some reason auth isn't set yet.
4443 $DB->set_field('user', 'auth', $auth, array('id' => $user->id
));
4444 $user->auth
= $auth;
4447 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4448 // the current hash algorithm while we have access to the user's password.
4449 update_internal_user_password($user, $password);
4451 if ($authplugin->is_synchronised_with_external()) {
4452 // Update user record from external DB.
4453 $user = update_user_record_by_id($user->id
);
4456 // The user is authenticated but user creation may be disabled.
4457 if (!empty($CFG->authpreventaccountcreation
)) {
4458 $failurereason = AUTH_LOGIN_UNAUTHORISED
;
4460 // Trigger login failed event.
4461 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4462 'reason' => $failurereason)));
4465 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4466 $_SERVER['HTTP_USER_AGENT']);
4469 $user = create_user_record($username, $password, $auth);
4473 $authplugin->sync_roles($user);
4475 foreach ($authsenabled as $hau) {
4476 $hauth = get_auth_plugin($hau);
4477 $hauth->user_authenticated_hook($user, $username, $password);
4480 if (empty($user->id
)) {
4481 $failurereason = AUTH_LOGIN_NOUSER
;
4482 // Trigger login failed event.
4483 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4484 'reason' => $failurereason)));
4489 if (!empty($user->suspended
)) {
4490 // Just in case some auth plugin suspended account.
4491 $failurereason = AUTH_LOGIN_SUSPENDED
;
4492 // Trigger login failed event.
4493 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4494 'other' => array('username' => $username, 'reason' => $failurereason)));
4496 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4500 login_attempt_valid($user);
4501 $failurereason = AUTH_LOGIN_OK
;
4505 // Failed if all the plugins have failed.
4506 if (debugging('', DEBUG_ALL
)) {
4507 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4511 login_attempt_failed($user);
4512 $failurereason = AUTH_LOGIN_FAILED
;
4513 // Trigger login failed event.
4514 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4515 'other' => array('username' => $username, 'reason' => $failurereason)));
4518 $failurereason = AUTH_LOGIN_NOUSER
;
4519 // Trigger login failed event.
4520 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4521 'reason' => $failurereason)));
4529 * Call to complete the user login process after authenticate_user_login()
4530 * has succeeded. It will setup the $USER variable and other required bits
4534 * - It will NOT log anything -- up to the caller to decide what to log.
4535 * - this function does not set any cookies any more!
4537 * @param stdClass $user
4538 * @return stdClass A {@link $USER} object - BC only, do not use
4540 function complete_user_login($user) {
4541 global $CFG, $DB, $USER, $SESSION;
4543 \core\session\manager
::login_user($user);
4545 // Reload preferences from DB.
4546 unset($USER->preference
);
4547 check_user_preferences_loaded($USER);
4549 // Update login times.
4550 update_user_login_times();
4552 // Extra session prefs init.
4553 set_login_session_preferences();
4555 // Trigger login event.
4556 $event = \core\event\user_loggedin
::create(
4558 'userid' => $USER->id
,
4559 'objectid' => $USER->id
,
4560 'other' => array('username' => $USER->username
),
4565 // Check if the user is using a new browser or session (a new MoodleSession cookie is set in that case).
4566 // If the user is accessing from the same IP, ignore everything (most of the time will be a new session in the same browser).
4567 // Skip Web Service requests, CLI scripts, AJAX scripts, and request from the mobile app itself.
4568 $loginip = getremoteaddr();
4569 $isnewip = isset($SESSION->userpreviousip
) && $SESSION->userpreviousip
!= $loginip;
4570 $isvalidenv = (!WS_SERVER
&& !CLI_SCRIPT
&& !NO_MOODLE_COOKIES
) || PHPUNIT_TEST
;
4572 if (!empty($SESSION->isnewsessioncookie
) && $isnewip && $isvalidenv && !\core_useragent
::is_moodle_app()) {
4574 $logintime = time();
4575 $ismoodleapp = false;
4576 $useragent = \core_useragent
::get_user_agent_string();
4578 // Schedule adhoc task to sent a login notification to the user.
4579 $task = new \core\task\
send_login_notifications();
4580 $task->set_userid($USER->id
);
4581 $task->set_custom_data(compact('ismoodleapp', 'useragent', 'loginip', 'logintime'));
4582 $task->set_component('core');
4583 \core\task\manager
::queue_adhoc_task($task);
4586 // Queue migrating the messaging data, if we need to.
4587 if (!get_user_preferences('core_message_migrate_data', false, $USER->id
)) {
4588 // Check if there are any legacy messages to migrate.
4589 if (\core_message\helper
::legacy_messages_exist($USER->id
)) {
4590 \core_message\task\migrate_message_data
::queue_task($USER->id
);
4592 set_user_preference('core_message_migrate_data', true, $USER->id
);
4596 if (isguestuser()) {
4597 // No need to continue when user is THE guest.
4602 // We can redirect to password change URL only in browser.
4606 // Select password change url.
4607 $userauth = get_auth_plugin($USER->auth
);
4609 // Check whether the user should be changing password.
4610 if (get_user_preferences('auth_forcepasswordchange', false)) {
4611 if ($userauth->can_change_password()) {
4612 if ($changeurl = $userauth->change_password_url()) {
4613 redirect($changeurl);
4615 require_once($CFG->dirroot
. '/login/lib.php');
4616 $SESSION->wantsurl
= core_login_get_return_url();
4617 redirect($CFG->wwwroot
.'/login/change_password.php');
4620 print_error('nopasswordchangeforced', 'auth');
4627 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4629 * @param string $password String to check.
4630 * @return boolean True if the $password matches the format of an md5 sum.
4632 function password_is_legacy_hash($password) {
4633 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4637 * Compare password against hash stored in user object to determine if it is valid.
4639 * If necessary it also updates the stored hash to the current format.
4641 * @param stdClass $user (Password property may be updated).
4642 * @param string $password Plain text password.
4643 * @return bool True if password is valid.
4645 function validate_internal_user_password($user, $password) {
4648 if ($user->password
=== AUTH_PASSWORD_NOT_CACHED
) {
4649 // Internal password is not used at all, it can not validate.
4653 // If hash isn't a legacy (md5) hash, validate using the library function.
4654 if (!password_is_legacy_hash($user->password
)) {
4655 return password_verify($password, $user->password
);
4658 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4659 // is valid we can then update it to the new algorithm.
4661 $sitesalt = isset($CFG->passwordsaltmain
) ?
$CFG->passwordsaltmain
: '';
4664 if ($user->password
=== md5($password.$sitesalt)
4665 or $user->password
=== md5($password)
4666 or $user->password
=== md5(addslashes($password).$sitesalt)
4667 or $user->password
=== md5(addslashes($password))) {
4668 // Note: we are intentionally using the addslashes() here because we
4669 // need to accept old password hashes of passwords with magic quotes.
4673 for ($i=1; $i<=20; $i++
) { // 20 alternative salts should be enough, right?
4674 $alt = 'passwordsaltalt'.$i;
4675 if (!empty($CFG->$alt)) {
4676 if ($user->password
=== md5($password.$CFG->$alt) or $user->password
=== md5(addslashes($password).$CFG->$alt)) {
4685 // If the password matches the existing md5 hash, update to the
4686 // current hash algorithm while we have access to the user's password.
4687 update_internal_user_password($user, $password);
4694 * Calculate hash for a plain text password.
4696 * @param string $password Plain text password to be hashed.
4697 * @param bool $fasthash If true, use a low cost factor when generating the hash
4698 * This is much faster to generate but makes the hash
4699 * less secure. It is used when lots of hashes need to
4700 * be generated quickly.
4701 * @return string The hashed password.
4703 * @throws moodle_exception If a problem occurs while generating the hash.
4705 function hash_internal_user_password($password, $fasthash = false) {
4708 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4709 $options = ($fasthash) ?
array('cost' => 4) : array();
4711 $generatedhash = password_hash($password, PASSWORD_DEFAULT
, $options);
4713 if ($generatedhash === false ||
$generatedhash === null) {
4714 throw new moodle_exception('Failed to generate password hash.');
4717 return $generatedhash;
4721 * Update password hash in user object (if necessary).
4723 * The password is updated if:
4724 * 1. The password has changed (the hash of $user->password is different
4725 * to the hash of $password).
4726 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4729 * Updating the password will modify the $user object and the database
4730 * record to use the current hashing algorithm.
4731 * It will remove Web Services user tokens too.
4733 * @param stdClass $user User object (password property may be updated).
4734 * @param string $password Plain text password.
4735 * @param bool $fasthash If true, use a low cost factor when generating the hash
4736 * This is much faster to generate but makes the hash
4737 * less secure. It is used when lots of hashes need to
4738 * be generated quickly.
4739 * @return bool Always returns true.
4741 function update_internal_user_password($user, $password, $fasthash = false) {
4744 // Figure out what the hashed password should be.
4745 if (!isset($user->auth
)) {
4746 debugging('User record in update_internal_user_password() must include field auth',
4748 $user->auth
= $DB->get_field('user', 'auth', array('id' => $user->id
));
4750 $authplugin = get_auth_plugin($user->auth
);
4751 if ($authplugin->prevent_local_passwords()) {
4752 $hashedpassword = AUTH_PASSWORD_NOT_CACHED
;
4754 $hashedpassword = hash_internal_user_password($password, $fasthash);
4757 $algorithmchanged = false;
4759 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED
) {
4760 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4761 $passwordchanged = ($user->password
!== $hashedpassword);
4763 } else if (isset($user->password
)) {
4764 // If verification fails then it means the password has changed.
4765 $passwordchanged = !password_verify($password, $user->password
);
4766 $algorithmchanged = password_needs_rehash($user->password
, PASSWORD_DEFAULT
);
4768 // While creating new user, password in unset in $user object, to avoid
4769 // saving it with user_create()
4770 $passwordchanged = true;
4773 if ($passwordchanged ||
$algorithmchanged) {
4774 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id
));
4775 $user->password
= $hashedpassword;
4778 $user = $DB->get_record('user', array('id' => $user->id
));
4779 \core\event\user_password_updated
::create_from_user($user)->trigger();
4781 // Remove WS user tokens.
4782 if (!empty($CFG->passwordchangetokendeletion
)) {
4783 require_once($CFG->dirroot
.'/webservice/lib.php');
4784 webservice
::delete_user_ws_tokens($user->id
);
4792 * Get a complete user record, which includes all the info in the user record.
4794 * Intended for setting as $USER session variable
4796 * @param string $field The user field to be checked for a given value.
4797 * @param string $value The value to match for $field.
4798 * @param int $mnethostid
4799 * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4800 * found. Otherwise, it will just return false.
4801 * @return mixed False, or A {@link $USER} object.
4803 function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4806 if (!$field ||
!$value) {
4810 // Change the field to lowercase.
4811 $field = core_text
::strtolower($field);
4813 // List of case insensitive fields.
4814 $caseinsensitivefields = ['email'];
4816 // Username input is forced to lowercase and should be case sensitive.
4817 if ($field == 'username') {
4818 $value = core_text
::strtolower($value);
4821 // Build the WHERE clause for an SQL query.
4822 $params = array('fieldval' => $value);
4824 // Do a case-insensitive query, if necessary. These are generally very expensive. The performance can be improved on some DBs
4825 // such as MySQL by pre-filtering users with accent-insensitive subselect.
4826 if (in_array($field, $caseinsensitivefields)) {
4827 $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4828 $idsubselect = $DB->sql_equal($field, ':fieldval2', false, false);
4829 $params['fieldval2'] = $value;
4831 $fieldselect = "$field = :fieldval";
4834 $constraints = "$fieldselect AND deleted <> 1";
4836 // If we are loading user data based on anything other than id,
4837 // we must also restrict our search based on mnet host.
4838 if ($field != 'id') {
4839 if (empty($mnethostid)) {
4840 // If empty, we restrict to local users.
4841 $mnethostid = $CFG->mnet_localhost_id
;
4844 if (!empty($mnethostid)) {
4845 $params['mnethostid'] = $mnethostid;
4846 $constraints .= " AND mnethostid = :mnethostid";
4850 $constraints .= " AND id IN (SELECT id FROM {user} WHERE {$idsubselect})";
4853 // Get all the basic user data.
4855 // Make sure that there's only a single record that matches our query.
4856 // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4857 // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4858 $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST
);
4859 } catch (dml_exception
$exception) {
4860 if ($throwexception) {
4863 // Return false when no records or multiple records were found.
4868 // Get various settings and preferences.
4870 // Preload preference cache.
4871 check_user_preferences_loaded($user);
4873 // Load course enrolment related stuff.
4874 $user->lastcourseaccess
= array(); // During last session.
4875 $user->currentcourseaccess
= array(); // During current session.
4876 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id
))) {
4877 foreach ($lastaccesses as $lastaccess) {
4878 $user->lastcourseaccess
[$lastaccess->courseid
] = $lastaccess->timeaccess
;
4882 $sql = "SELECT g.id, g.courseid
4883 FROM {groups} g, {groups_members} gm
4884 WHERE gm.groupid=g.id AND gm.userid=?";
4886 // This is a special hack to speedup calendar display.
4887 $user->groupmember
= array();
4888 if (!isguestuser($user)) {
4889 if ($groups = $DB->get_records_sql($sql, array($user->id
))) {
4890 foreach ($groups as $group) {
4891 if (!array_key_exists($group->courseid
, $user->groupmember
)) {
4892 $user->groupmember
[$group->courseid
] = array();
4894 $user->groupmember
[$group->courseid
][$group->id
] = $group->id
;
4899 // Add cohort theme.
4900 if (!empty($CFG->allowcohortthemes
)) {
4901 require_once($CFG->dirroot
. '/cohort/lib.php');
4902 if ($cohorttheme = cohort_get_user_cohort_theme($user->id
)) {
4903 $user->cohorttheme
= $cohorttheme;
4907 // Add the custom profile fields to the user record.
4908 $user->profile
= array();
4909 if (!isguestuser($user)) {
4910 require_once($CFG->dirroot
.'/user/profile/lib.php');
4911 profile_load_custom_fields($user);
4914 // Rewrite some variables if necessary.
4915 if (!empty($user->description
)) {
4916 // No need to cart all of it around.
4917 $user->description
= true;
4919 if (isguestuser($user)) {
4920 // Guest language always same as site.
4921 $user->lang
= get_newuser_language();
4922 // Name always in current language.
4923 $user->firstname
= get_string('guestuser');
4924 $user->lastname
= ' ';
4931 * Validate a password against the configured password policy
4933 * @param string $password the password to be checked against the password policy
4934 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4935 * @param stdClass $user the user object to perform password validation against. Defaults to null if not provided.
4937 * @return bool true if the password is valid according to the policy. false otherwise.
4939 function check_password_policy($password, &$errmsg, $user = null) {
4942 if (!empty($CFG->passwordpolicy
)) {
4944 if (core_text
::strlen($password) < $CFG->minpasswordlength
) {
4945 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength
) .'</div>';
4947 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits
) {
4948 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits
) .'</div>';
4950 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower
) {
4951 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower
) .'</div>';
4953 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper
) {
4954 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper
) .'</div>';
4956 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum
) {
4957 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
) .'</div>';
4959 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars
)) {
4960 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars
) .'</div>';
4963 // Fire any additional password policy functions from plugins.
4964 // Plugin functions should output an error message string or empty string for success.
4965 $pluginsfunction = get_plugins_with_function('check_password_policy');
4966 foreach ($pluginsfunction as $plugintype => $plugins) {
4967 foreach ($plugins as $pluginfunction) {
4968 $pluginerr = $pluginfunction($password, $user);
4970 $errmsg .= '<div>'. $pluginerr .'</div>';
4976 if ($errmsg == '') {
4985 * When logging in, this function is run to set certain preferences for the current SESSION.
4987 function set_login_session_preferences() {
4990 $SESSION->justloggedin
= true;
4992 unset($SESSION->lang
);
4993 unset($SESSION->forcelang
);
4994 unset($SESSION->load_navigation_admin
);
4999 * Delete a course, including all related data from the database, and any associated files.
5001 * @param mixed $courseorid The id of the course or course object to delete.
5002 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5003 * @return bool true if all the removals succeeded. false if there were any failures. If this
5004 * method returns false, some of the removals will probably have succeeded, and others
5005 * failed, but you have no way of knowing which.
5007 function delete_course($courseorid, $showfeedback = true) {
5010 if (is_object($courseorid)) {
5011 $courseid = $courseorid->id
;
5012 $course = $courseorid;
5014 $courseid = $courseorid;
5015 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
5019 $context = context_course
::instance($courseid);
5021 // Frontpage course can not be deleted!!
5022 if ($courseid == SITEID
) {
5026 // Allow plugins to use this course before we completely delete it.
5027 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
5028 foreach ($pluginsfunction as $plugintype => $plugins) {
5029 foreach ($plugins as $pluginfunction) {
5030 $pluginfunction($course);
5035 // Tell the search manager we are about to delete a course. This prevents us sending updates
5036 // for each individual context being deleted.
5037 \core_search\manager
::course_deleting_start($courseid);
5039 $handler = core_course\customfield\course_handler
::create();
5040 $handler->delete_instance($courseid);
5042 // Make the course completely empty.
5043 remove_course_contents($courseid, $showfeedback);
5045 // Delete the course and related context instance.
5046 context_helper
::delete_instance(CONTEXT_COURSE
, $courseid);
5048 $DB->delete_records("course", array("id" => $courseid));
5049 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5051 // Reset all course related caches here.
5052 core_courseformat\base
::reset_course_cache($courseid);
5054 // Tell search that we have deleted the course so it can delete course data from the index.
5055 \core_search\manager
::course_deleting_finish($courseid);
5057 // Trigger a course deleted event.
5058 $event = \core\event\course_deleted
::create(array(
5059 'objectid' => $course->id
,
5060 'context' => $context,
5062 'shortname' => $course->shortname
,
5063 'fullname' => $course->fullname
,
5064 'idnumber' => $course->idnumber
5067 $event->add_record_snapshot('course', $course);
5074 * Clear a course out completely, deleting all content but don't delete the course itself.
5076 * This function does not verify any permissions.
5078 * Please note this function also deletes all user enrolments,
5079 * enrolment instances and role assignments by default.
5082 * - 'keep_roles_and_enrolments' - false by default
5083 * - 'keep_groups_and_groupings' - false by default
5085 * @param int $courseid The id of the course that is being deleted
5086 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5087 * @param array $options extra options
5088 * @return bool true if all the removals succeeded. false if there were any failures. If this
5089 * method returns false, some of the removals will probably have succeeded, and others
5090 * failed, but you have no way of knowing which.
5092 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5093 global $CFG, $DB, $OUTPUT;
5095 require_once($CFG->libdir
.'/badgeslib.php');
5096 require_once($CFG->libdir
.'/completionlib.php');
5097 require_once($CFG->libdir
.'/questionlib.php');
5098 require_once($CFG->libdir
.'/gradelib.php');
5099 require_once($CFG->dirroot
.'/group/lib.php');
5100 require_once($CFG->dirroot
.'/comment/lib.php');
5101 require_once($CFG->dirroot
.'/rating/lib.php');
5102 require_once($CFG->dirroot
.'/notes/lib.php');
5104 // Handle course badges.
5105 badges_handle_course_deletion($courseid);
5107 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5108 $strdeleted = get_string('deleted').' - ';
5110 // Some crazy wishlist of stuff we should skip during purging of course content.
5111 $options = (array)$options;
5113 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST
);
5114 $coursecontext = context_course
::instance($courseid);
5115 $fs = get_file_storage();
5117 // Delete course completion information, this has to be done before grades and enrols.
5118 $cc = new completion_info($course);
5119 $cc->clear_criteria();
5120 if ($showfeedback) {
5121 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5124 // Remove all data from gradebook - this needs to be done before course modules
5125 // because while deleting this information, the system may need to reference
5126 // the course modules that own the grades.
5127 remove_course_grades($courseid, $showfeedback);
5128 remove_grade_letters($coursecontext, $showfeedback);
5130 // Delete course blocks in any all child contexts,
5131 // they may depend on modules so delete them first.
5132 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5133 foreach ($childcontexts as $childcontext) {
5134 blocks_delete_all_for_context($childcontext->id
);
5136 unset($childcontexts);
5137 blocks_delete_all_for_context($coursecontext->id
);
5138 if ($showfeedback) {
5139 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5142 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $courseid]);
5143 rebuild_course_cache($courseid, true);
5145 // Get the list of all modules that are properly installed.
5146 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5148 // Delete every instance of every module,
5149 // this has to be done before deleting of course level stuff.
5150 $locations = core_component
::get_plugin_list('mod');
5151 foreach ($locations as $modname => $moddir) {
5152 if ($modname === 'NEWMODULE') {
5155 if (array_key_exists($modname, $allmodules)) {
5156 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5157 FROM {".$modname."} m
5158 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5159 WHERE m.course = :courseid";
5160 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id
,
5161 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5163 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5164 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5167 foreach ($instances as $cm) {
5169 // Delete activity context questions and question categories.
5170 question_delete_activity($cm);
5171 // Notify the competency subsystem.
5172 \core_competency\api
::hook_course_module_deleted($cm);
5174 if (function_exists($moddelete)) {
5175 // This purges all module data in related tables, extra user prefs, settings, etc.
5176 $moddelete($cm->modinstance
);
5178 // NOTE: we should not allow installation of modules with missing delete support!
5179 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5180 $DB->delete_records($modname, array('id' => $cm->modinstance
));
5184 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5185 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
5186 $DB->delete_records('course_modules_completion', ['coursemoduleid' => $cm->id
]);
5187 $DB->delete_records('course_modules', array('id' => $cm->id
));
5188 rebuild_course_cache($cm->course
, true);
5192 if ($instances and $showfeedback) {
5193 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5196 // Ooops, this module is not properly installed, force-delete it in the next block.
5200 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5202 // Delete completion defaults.
5203 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5205 // Remove all data from availability and completion tables that is associated
5206 // with course-modules belonging to this course. Note this is done even if the
5207 // features are not enabled now, in case they were enabled previously.
5208 $DB->delete_records_subquery('course_modules_completion', 'coursemoduleid', 'id',
5209 'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
5211 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5212 $cms = $DB->get_records('course_modules', array('course' => $course->id
));
5213 $allmodulesbyid = array_flip($allmodules);
5214 foreach ($cms as $cm) {
5215 if (array_key_exists($cm->module
, $allmodulesbyid)) {
5217 $DB->delete_records($allmodulesbyid[$cm->module
], array('id' => $cm->instance
));
5218 } catch (Exception
$e) {
5219 // Ignore weird or missing table problems.
5222 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
5223 $DB->delete_records('course_modules', array('id' => $cm->id
));
5224 rebuild_course_cache($cm->course
, true);
5227 if ($showfeedback) {
5228 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5231 // Delete questions and question categories.
5232 question_delete_course($course);
5233 if ($showfeedback) {
5234 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5237 // Delete content bank contents.
5238 $cb = new \core_contentbank\
contentbank();
5239 $cbdeleted = $cb->delete_contents($coursecontext);
5240 if ($showfeedback && $cbdeleted) {
5241 echo $OUTPUT->notification($strdeleted.get_string('contentbank', 'contentbank'), 'notifysuccess');
5244 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5245 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5246 foreach ($childcontexts as $childcontext) {
5247 $childcontext->delete();
5249 unset($childcontexts);
5251 // Remove roles and enrolments by default.
5252 if (empty($options['keep_roles_and_enrolments'])) {
5253 // This hack is used in restore when deleting contents of existing course.
5254 // During restore, we should remove only enrolment related data that the user performing the restore has a
5255 // permission to remove.
5256 $userid = $options['userid'] ??
null;
5257 enrol_course_delete($course, $userid);
5258 role_unassign_all(array('contextid' => $coursecontext->id
, 'component' => ''), true);
5259 if ($showfeedback) {
5260 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5264 // Delete any groups, removing members and grouping/course links first.
5265 if (empty($options['keep_groups_and_groupings'])) {
5266 groups_delete_groupings($course->id
, $showfeedback);
5267 groups_delete_groups($course->id
, $showfeedback);
5271 filter_delete_all_for_context($coursecontext->id
);
5273 // Notes, you shall not pass!
5274 note_delete_all($course->id
);
5277 comment
::delete_comments($coursecontext->id
);
5279 // Ratings are history too.
5280 $delopt = new stdclass();
5281 $delopt->contextid
= $coursecontext->id
;
5282 $rm = new rating_manager();
5283 $rm->delete_ratings($delopt);
5285 // Delete course tags.
5286 core_tag_tag
::remove_all_item_tags('core', 'course', $course->id
);
5288 // Give the course format the opportunity to remove its obscure data.
5289 $format = course_get_format($course);
5290 $format->delete_format_data();
5292 // Notify the competency subsystem.
5293 \core_competency\api
::hook_course_deleted($course);
5295 // Delete calendar events.
5296 $DB->delete_records('event', array('courseid' => $course->id
));
5297 $fs->delete_area_files($coursecontext->id
, 'calendar');
5299 // Delete all related records in other core tables that may have a courseid
5300 // This array stores the tables that need to be cleared, as
5301 // table_name => column_name that contains the course id.
5302 $tablestoclear = array(
5303 'backup_courses' => 'courseid', // Scheduled backup stuff.
5304 'user_lastaccess' => 'courseid', // User access info.
5306 foreach ($tablestoclear as $table => $col) {
5307 $DB->delete_records($table, array($col => $course->id
));
5310 // Delete all course backup files.
5311 $fs->delete_area_files($coursecontext->id
, 'backup');
5313 // Cleanup course record - remove links to deleted stuff.
5314 $oldcourse = new stdClass();
5315 $oldcourse->id
= $course->id
;
5316 $oldcourse->summary
= '';
5317 $oldcourse->cacherev
= 0;
5318 $oldcourse->legacyfiles
= 0;
5319 if (!empty($options['keep_groups_and_groupings'])) {
5320 $oldcourse->defaultgroupingid
= 0;
5322 $DB->update_record('course', $oldcourse);
5324 // Delete course sections.
5325 $DB->delete_records('course_sections', array('course' => $course->id
));
5327 // Delete legacy, section and any other course files.
5328 $fs->delete_area_files($coursecontext->id
, 'course'); // Files from summary and section.
5330 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5331 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5332 // Easy, do not delete the context itself...
5333 $coursecontext->delete_content();
5336 // We can not drop all context stuff because it would bork enrolments and roles,
5337 // there might be also files used by enrol plugins...
5340 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5341 // also some non-standard unsupported plugins may try to store something there.
5342 fulldelete($CFG->dataroot
.'/'.$course->id
);
5344 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5345 $cachemodinfo = cache
::make('core', 'coursemodinfo');
5346 $cachemodinfo->delete($courseid);
5348 // Trigger a course content deleted event.
5349 $event = \core\event\course_content_deleted
::create(array(
5350 'objectid' => $course->id
,
5351 'context' => $coursecontext,
5352 'other' => array('shortname' => $course->shortname
,
5353 'fullname' => $course->fullname
,
5354 'options' => $options) // Passing this for legacy reasons.
5356 $event->add_record_snapshot('course', $course);
5363 * Change dates in module - used from course reset.
5365 * @param string $modname forum, assignment, etc
5366 * @param array $fields array of date fields from mod table
5367 * @param int $timeshift time difference
5368 * @param int $courseid
5369 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5370 * @return bool success
5372 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5374 include_once($CFG->dirroot
.'/mod/'.$modname.'/lib.php');
5377 $params = array($timeshift, $courseid);
5378 foreach ($fields as $field) {
5379 $updatesql = "UPDATE {".$modname."}
5380 SET $field = $field + ?
5381 WHERE course=? AND $field<>0";
5383 $updatesql .= ' AND id=?';
5386 $return = $DB->execute($updatesql, $params) && $return;
5393 * This function will empty a course of user data.
5394 * It will retain the activities and the structure of the course.
5396 * @param object $data an object containing all the settings including courseid (without magic quotes)
5397 * @return array status array of array component, item, error
5399 function reset_course_userdata($data) {
5401 require_once($CFG->libdir
.'/gradelib.php');
5402 require_once($CFG->libdir
.'/completionlib.php');
5403 require_once($CFG->dirroot
.'/completion/criteria/completion_criteria_date.php');
5404 require_once($CFG->dirroot
.'/group/lib.php');
5406 $data->courseid
= $data->id
;
5407 $context = context_course
::instance($data->courseid
);
5409 $eventparams = array(
5410 'context' => $context,
5411 'courseid' => $data->id
,
5413 'reset_options' => (array) $data
5416 $event = \core\event\course_reset_started
::create($eventparams);
5419 // Calculate the time shift of dates.
5420 if (!empty($data->reset_start_date
)) {
5421 // Time part of course startdate should be zero.
5422 $data->timeshift
= $data->reset_start_date
- usergetmidnight($data->reset_start_date_old
);
5424 $data->timeshift
= 0;
5427 // Result array: component, item, error.
5430 // Start the resetting.
5431 $componentstr = get_string('general');
5433 // Move the course start time.
5434 if (!empty($data->reset_start_date
) and $data->timeshift
) {
5435 // Change course start data.
5436 $DB->set_field('course', 'startdate', $data->reset_start_date
, array('id' => $data->courseid
));
5437 // Update all course and group events - do not move activity events.
5438 $updatesql = "UPDATE {event}
5439 SET timestart = timestart + ?
5440 WHERE courseid=? AND instance=0";
5441 $DB->execute($updatesql, array($data->timeshift
, $data->courseid
));
5443 // Update any date activity restrictions.
5444 if ($CFG->enableavailability
) {
5445 \availability_date\condition
::update_all_dates($data->courseid
, $data->timeshift
);
5448 // Update completion expected dates.
5449 if ($CFG->enablecompletion
) {
5450 $modinfo = get_fast_modinfo($data->courseid
);
5452 foreach ($modinfo->get_cms() as $cm) {
5453 if ($cm->completion
&& !empty($cm->completionexpected
)) {
5454 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected +
$data->timeshift
,
5455 array('id' => $cm->id
));
5460 // Clear course cache if changes made.
5462 rebuild_course_cache($data->courseid
, true);
5465 // Update course date completion criteria.
5466 \completion_criteria_date
::update_date($data->courseid
, $data->timeshift
);
5469 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5472 if (!empty($data->reset_end_date
)) {
5473 // If the user set a end date value respect it.
5474 $DB->set_field('course', 'enddate', $data->reset_end_date
, array('id' => $data->courseid
));
5475 } else if ($data->timeshift
> 0 && $data->reset_end_date_old
) {
5476 // If there is a time shift apply it to the end date as well.
5477 $enddate = $data->reset_end_date_old +
$data->timeshift
;
5478 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid
));
5481 if (!empty($data->reset_events
)) {
5482 $DB->delete_records('event', array('courseid' => $data->courseid
));
5483 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5486 if (!empty($data->reset_notes
)) {
5487 require_once($CFG->dirroot
.'/notes/lib.php');
5488 note_delete_all($data->courseid
);
5489 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5492 if (!empty($data->delete_blog_associations
)) {
5493 require_once($CFG->dirroot
.'/blog/lib.php');
5494 blog_remove_associations_for_course($data->courseid
);
5495 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5498 if (!empty($data->reset_completion
)) {
5499 // Delete course and activity completion information.
5500 $course = $DB->get_record('course', array('id' => $data->courseid
));
5501 $cc = new completion_info($course);
5502 $cc->delete_all_completion_data();
5503 $status[] = array('component' => $componentstr,
5504 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5507 if (!empty($data->reset_competency_ratings
)) {
5508 \core_competency\api
::hook_course_reset_competency_ratings($data->courseid
);
5509 $status[] = array('component' => $componentstr,
5510 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5513 $componentstr = get_string('roles');
5515 if (!empty($data->reset_roles_overrides
)) {
5516 $children = $context->get_child_contexts();
5517 foreach ($children as $child) {
5518 $child->delete_capabilities();
5520 $context->delete_capabilities();
5521 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5524 if (!empty($data->reset_roles_local
)) {
5525 $children = $context->get_child_contexts();
5526 foreach ($children as $child) {
5527 role_unassign_all(array('contextid' => $child->id
));
5529 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5532 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5533 $data->unenrolled
= array();
5534 if (!empty($data->unenrol_users
)) {
5535 $plugins = enrol_get_plugins(true);
5536 $instances = enrol_get_instances($data->courseid
, true);
5537 foreach ($instances as $key => $instance) {
5538 if (!isset($plugins[$instance->enrol
])) {
5539 unset($instances[$key]);
5544 $usersroles = enrol_get_course_users_roles($data->courseid
);
5545 foreach ($data->unenrol_users
as $withroleid) {
5548 FROM {user_enrolments} ue
5549 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5550 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5551 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5552 $params = array('courseid' => $data->courseid
, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE
);
5555 // Without any role assigned at course context.
5557 FROM {user_enrolments} ue
5558 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5559 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5560 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5561 WHERE ra.id IS null";
5562 $params = array('courseid' => $data->courseid
, 'courselevel' => CONTEXT_COURSE
);
5565 $rs = $DB->get_recordset_sql($sql, $params);
5566 foreach ($rs as $ue) {
5567 if (!isset($instances[$ue->enrolid
])) {
5570 $instance = $instances[$ue->enrolid
];
5571 $plugin = $plugins[$instance->enrol
];
5572 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5576 if ($withroleid && count($usersroles[$ue->userid
]) > 1) {
5577 // If we don't remove all roles and user has more than one role, just remove this role.
5578 role_unassign($withroleid, $ue->userid
, $context->id
);
5580 unset($usersroles[$ue->userid
][$withroleid]);
5582 // If we remove all roles or user has only one role, unenrol user from course.
5583 $plugin->unenrol_user($instance, $ue->userid
);
5585 $data->unenrolled
[$ue->userid
] = $ue->userid
;
5590 if (!empty($data->unenrolled
)) {
5592 'component' => $componentstr,
5593 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled
).')',
5598 $componentstr = get_string('groups');
5600 // Remove all group members.
5601 if (!empty($data->reset_groups_members
)) {
5602 groups_delete_group_members($data->courseid
);
5603 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5606 // Remove all groups.
5607 if (!empty($data->reset_groups_remove
)) {
5608 groups_delete_groups($data->courseid
, false);
5609 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5612 // Remove all grouping members.
5613 if (!empty($data->reset_groupings_members
)) {
5614 groups_delete_groupings_groups($data->courseid
, false);
5615 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5618 // Remove all groupings.
5619 if (!empty($data->reset_groupings_remove
)) {
5620 groups_delete_groupings($data->courseid
, false);
5621 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5624 // Look in every instance of every module for data to delete.
5625 $unsupportedmods = array();
5626 if ($allmods = $DB->get_records('modules') ) {
5627 foreach ($allmods as $mod) {
5628 $modname = $mod->name
;
5629 $modfile = $CFG->dirroot
.'/mod/'. $modname.'/lib.php';
5630 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5631 if (file_exists($modfile)) {
5632 if (!$DB->count_records($modname, array('course' => $data->courseid
))) {
5633 continue; // Skip mods with no instances.
5635 include_once($modfile);
5636 if (function_exists($moddeleteuserdata)) {
5637 $modstatus = $moddeleteuserdata($data);
5638 if (is_array($modstatus)) {
5639 $status = array_merge($status, $modstatus);
5641 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5644 $unsupportedmods[] = $mod;
5647 debugging('Missing lib.php in '.$modname.' module!');
5649 // Update calendar events for all modules.
5650 course_module_bulk_update_calendar_events($modname, $data->courseid
);
5654 // Mention unsupported mods.
5655 if (!empty($unsupportedmods)) {
5656 foreach ($unsupportedmods as $mod) {
5658 'component' => get_string('modulenameplural', $mod->name
),
5660 'error' => get_string('resetnotimplemented')
5665 $componentstr = get_string('gradebook', 'grades');
5666 // Reset gradebook,.
5667 if (!empty($data->reset_gradebook_items
)) {
5668 remove_course_grades($data->courseid
, false);
5669 grade_grab_course_grades($data->courseid
);
5670 grade_regrade_final_grades($data->courseid
);
5671 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5673 } else if (!empty($data->reset_gradebook_grades
)) {
5674 grade_course_reset($data->courseid
);
5675 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5678 if (!empty($data->reset_comments
)) {
5679 require_once($CFG->dirroot
.'/comment/lib.php');
5680 comment
::reset_course_page_comments($context);
5683 $event = \core\event\course_reset_ended
::create($eventparams);
5690 * Generate an email processing address.
5693 * @param string $modargs
5694 * @return string Returns email processing address
5696 function generate_email_processing_address($modid, $modargs) {
5699 $header = $CFG->mailprefix
. substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5700 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain
;
5706 * @todo Finish documenting this function
5708 * @param string $modargs
5709 * @param string $body Currently unused
5711 function moodle_process_email($modargs, $body) {
5714 // The first char should be an unencoded letter. We'll take this as an action.
5715 switch ($modargs[0]) {
5716 case 'B': { // Bounce.
5717 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5718 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5719 // Check the half md5 of their email.
5720 $md5check = substr(md5($user->email
), 0, 16);
5721 if ($md5check == substr($modargs, -16)) {
5722 set_bounce_count($user);
5724 // Else maybe they've already changed it?
5728 // Maybe more later?
5735 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5737 * @param string $action 'get', 'buffer', 'close' or 'flush'
5738 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5740 function get_mailer($action='get') {
5743 /** @var moodle_phpmailer $mailer */
5744 static $mailer = null;
5745 static $counter = 0;
5747 if (!isset($CFG->smtpmaxbulk
)) {
5748 $CFG->smtpmaxbulk
= 1;
5751 if ($action == 'get') {
5752 $prevkeepalive = false;
5754 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5755 if ($counter < $CFG->smtpmaxbulk
and !$mailer->isError()) {
5757 // Reset the mailer.
5758 $mailer->Priority
= 3;
5759 $mailer->CharSet
= 'UTF-8'; // Our default.
5760 $mailer->ContentType
= "text/plain";
5761 $mailer->Encoding
= "8bit";
5762 $mailer->From
= "root@localhost";
5763 $mailer->FromName
= "Root User";
5764 $mailer->Sender
= "";
5765 $mailer->Subject
= "";
5767 $mailer->AltBody
= "";
5768 $mailer->ConfirmReadingTo
= "";
5770 $mailer->clearAllRecipients();
5771 $mailer->clearReplyTos();
5772 $mailer->clearAttachments();
5773 $mailer->clearCustomHeaders();
5777 $prevkeepalive = $mailer->SMTPKeepAlive
;
5778 get_mailer('flush');
5781 require_once($CFG->libdir
.'/phpmailer/moodle_phpmailer.php');
5782 $mailer = new moodle_phpmailer();
5786 if ($CFG->smtphosts
== 'qmail') {
5787 // Use Qmail system.
5790 } else if (empty($CFG->smtphosts
)) {
5791 // Use PHP mail() = sendmail.
5795 // Use SMTP directly.
5797 if (!empty($CFG->debugsmtp
) && (!empty($CFG->debugdeveloper
))) {
5798 $mailer->SMTPDebug
= 3;
5800 // Specify main and backup servers.
5801 $mailer->Host
= $CFG->smtphosts
;
5802 // Specify secure connection protocol.
5803 $mailer->SMTPSecure
= $CFG->smtpsecure
;
5804 // Use previous keepalive.
5805 $mailer->SMTPKeepAlive
= $prevkeepalive;
5807 if ($CFG->smtpuser
) {
5808 // Use SMTP authentication.
5809 $mailer->SMTPAuth
= true;
5810 $mailer->Username
= $CFG->smtpuser
;
5811 $mailer->Password
= $CFG->smtppass
;
5820 // Keep smtp session open after sending.
5821 if ($action == 'buffer') {
5822 if (!empty($CFG->smtpmaxbulk
)) {
5823 get_mailer('flush');
5825 if ($m->Mailer
== 'smtp') {
5826 $m->SMTPKeepAlive
= true;
5832 // Close smtp session, but continue buffering.
5833 if ($action == 'flush') {
5834 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5835 if (!empty($mailer->SMTPDebug
)) {
5838 $mailer->SmtpClose();
5839 if (!empty($mailer->SMTPDebug
)) {
5846 // Close smtp session, do not buffer anymore.
5847 if ($action == 'close') {
5848 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5849 get_mailer('flush');
5850 $mailer->SMTPKeepAlive
= false;
5852 $mailer = null; // Better force new instance.
5858 * A helper function to test for email diversion
5860 * @param string $email
5861 * @return bool Returns true if the email should be diverted
5863 function email_should_be_diverted($email) {
5866 if (empty($CFG->divertallemailsto
)) {
5870 if (empty($CFG->divertallemailsexcept
)) {
5874 $patterns = array_map('trim', preg_split("/[\s,]+/", $CFG->divertallemailsexcept
));
5875 foreach ($patterns as $pattern) {
5876 if (preg_match("/$pattern/", $email)) {
5885 * Generate a unique email Message-ID using the moodle domain and install path
5887 * @param string $localpart An optional unique message id prefix.
5888 * @return string The formatted ID ready for appending to the email headers.
5890 function generate_email_messageid($localpart = null) {
5893 $urlinfo = parse_url($CFG->wwwroot
);
5894 $base = '@' . $urlinfo['host'];
5896 // If multiple moodles are on the same domain we want to tell them
5897 // apart so we add the install path to the local part. This means
5898 // that the id local part should never contain a / character so
5899 // we can correctly parse the id to reassemble the wwwroot.
5900 if (isset($urlinfo['path'])) {
5901 $base = $urlinfo['path'] . $base;
5904 if (empty($localpart)) {
5905 $localpart = uniqid('', true);
5908 // Because we may have an option /installpath suffix to the local part
5909 // of the id we need to escape any / chars which are in the $localpart.
5910 $localpart = str_replace('/', '%2F', $localpart);
5912 return '<' . $localpart . $base . '>';
5916 * Send an email to a specified user
5918 * @param stdClass $user A {@link $USER} object
5919 * @param stdClass $from A {@link $USER} object
5920 * @param string $subject plain text subject line of the email
5921 * @param string $messagetext plain text version of the message
5922 * @param string $messagehtml complete html version of the message (optional)
5923 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in one of
5924 * the following directories: $CFG->cachedir, $CFG->dataroot, $CFG->dirroot, $CFG->localcachedir, $CFG->tempdir
5925 * @param string $attachname the name of the file (extension indicates MIME)
5926 * @param bool $usetrueaddress determines whether $from email address should
5927 * be sent out. Will be overruled by user profile setting for maildisplay
5928 * @param string $replyto Email address to reply to
5929 * @param string $replytoname Name of reply to recipient
5930 * @param int $wordwrapwidth custom word wrap width, default 79
5931 * @return bool Returns true if mail was sent OK and false if there was an error.
5933 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5934 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5936 global $CFG, $PAGE, $SITE;
5938 if (empty($user) or empty($user->id
)) {
5939 debugging('Can not send email to null user', DEBUG_DEVELOPER
);
5943 if (empty($user->email
)) {
5944 debugging('Can not send email to user without email: '.$user->id
, DEBUG_DEVELOPER
);
5948 if (!empty($user->deleted
)) {
5949 debugging('Can not send email to deleted user: '.$user->id
, DEBUG_DEVELOPER
);
5953 if (defined('BEHAT_SITE_RUNNING')) {
5954 // Fake email sending in behat.
5958 if (!empty($CFG->noemailever
)) {
5959 // Hidden setting for development sites, set in config.php if needed.
5960 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL
);
5964 if (email_should_be_diverted($user->email
)) {
5965 $subject = "[DIVERTED {$user->email}] $subject";
5966 $user = clone($user);
5967 $user->email
= $CFG->divertallemailsto
;
5970 // Skip mail to suspended users.
5971 if ((isset($user->auth
) && $user->auth
=='nologin') or (isset($user->suspended
) && $user->suspended
)) {
5975 if (!validate_email($user->email
)) {
5976 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5977 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5981 if (over_bounce_threshold($user)) {
5982 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5986 // TLD .invalid is specifically reserved for invalid domain names.
5987 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5988 if (substr($user->email
, -8) == '.invalid') {
5989 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5990 return true; // This is not an error.
5993 // If the user is a remote mnet user, parse the email text for URL to the
5994 // wwwroot and modify the url to direct the user's browser to login at their
5995 // home site (identity provider - idp) before hitting the link itself.
5996 if (is_mnet_remote_user($user)) {
5997 require_once($CFG->dirroot
.'/mnet/lib.php');
5999 $jumpurl = mnet_get_idp_jump_url($user);
6000 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
6002 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
6005 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
6009 $mail = get_mailer();
6011 if (!empty($mail->SMTPDebug
)) {
6012 echo '<pre>' . "\n";
6015 $temprecipients = array();
6016 $tempreplyto = array();
6018 // Make sure that we fall back onto some reasonable no-reply address.
6019 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot
);
6020 $noreplyaddress = empty($CFG->noreplyaddress
) ?
$noreplyaddressdefault : $CFG->noreplyaddress
;
6022 if (!validate_email($noreplyaddress)) {
6023 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
6024 $noreplyaddress = $noreplyaddressdefault;
6027 // Make up an email address for handling bounces.
6028 if (!empty($CFG->handlebounces
)) {
6029 $modargs = 'B'.base64_encode(pack('V', $user->id
)).substr(md5($user->email
), 0, 16);
6030 $mail->Sender
= generate_email_processing_address(0, $modargs);
6032 $mail->Sender
= $noreplyaddress;
6035 // Make sure that the explicit replyto is valid, fall back to the implicit one.
6036 if (!empty($replyto) && !validate_email($replyto)) {
6037 debugging('email_to_user: Invalid replyto-email '.s($replyto));
6038 $replyto = $noreplyaddress;
6041 if (is_string($from)) { // So we can pass whatever we want if there is need.
6042 $mail->From
= $noreplyaddress;
6043 $mail->FromName
= $from;
6044 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
6045 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6046 // in a course with the sender.
6047 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
6048 if (!validate_email($from->email
)) {
6049 debugging('email_to_user: Invalid from-email '.s($from->email
).' - not sending');
6050 // Better not to use $noreplyaddress in this case.
6053 $mail->From
= $from->email
;
6054 $fromdetails = new stdClass();
6055 $fromdetails->name
= fullname($from);
6056 $fromdetails->url
= preg_replace('#^https?://#', '', $CFG->wwwroot
);
6057 $fromdetails->siteshortname
= format_string($SITE->shortname
);
6058 $fromstring = $fromdetails->name
;
6059 if ($CFG->emailfromvia
== EMAIL_VIA_ALWAYS
) {
6060 $fromstring = get_string('emailvia', 'core', $fromdetails);
6062 $mail->FromName
= $fromstring;
6063 if (empty($replyto)) {
6064 $tempreplyto[] = array($from->email
, fullname($from));
6067 $mail->From
= $noreplyaddress;
6068 $fromdetails = new stdClass();
6069 $fromdetails->name
= fullname($from);
6070 $fromdetails->url
= preg_replace('#^https?://#', '', $CFG->wwwroot
);
6071 $fromdetails->siteshortname
= format_string($SITE->shortname
);
6072 $fromstring = $fromdetails->name
;
6073 if ($CFG->emailfromvia
!= EMAIL_VIA_NEVER
) {
6074 $fromstring = get_string('emailvia', 'core', $fromdetails);
6076 $mail->FromName
= $fromstring;
6077 if (empty($replyto)) {
6078 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
6082 if (!empty($replyto)) {
6083 $tempreplyto[] = array($replyto, $replytoname);
6086 $temprecipients[] = array($user->email
, fullname($user));
6089 $mail->WordWrap
= $wordwrapwidth;
6091 if (!empty($from->customheaders
)) {
6092 // Add custom headers.
6093 if (is_array($from->customheaders
)) {
6094 foreach ($from->customheaders
as $customheader) {
6095 $mail->addCustomHeader($customheader);
6098 $mail->addCustomHeader($from->customheaders
);
6102 // If the X-PHP-Originating-Script email header is on then also add an additional
6103 // header with details of where exactly in moodle the email was triggered from,
6104 // either a call to message_send() or to email_to_user().
6105 if (ini_get('mail.add_x_header')) {
6107 $stack = debug_backtrace(false);
6108 $origin = $stack[0];
6110 foreach ($stack as $depth => $call) {
6111 if ($call['function'] == 'message_send') {
6116 $originheader = $CFG->wwwroot
. ' => ' . gethostname() . ':'
6117 . str_replace($CFG->dirroot
. '/', '', $origin['file']) . ':' . $origin['line'];
6118 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
6121 if (!empty($CFG->emailheaders
)) {
6122 $headers = array_map('trim', explode("\n", $CFG->emailheaders
));
6123 foreach ($headers as $header) {
6124 if (!empty($header)) {
6125 $mail->addCustomHeader($header);
6130 if (!empty($from->priority
)) {
6131 $mail->Priority
= $from->priority
;
6134 $renderer = $PAGE->get_renderer('core');
6136 'sitefullname' => $SITE->fullname
,
6137 'siteshortname' => $SITE->shortname
,
6138 'sitewwwroot' => $CFG->wwwroot
,
6139 'subject' => $subject,
6140 'prefix' => $CFG->emailsubjectprefix
,
6141 'to' => $user->email
,
6142 'toname' => fullname($user),
6143 'from' => $mail->From
,
6144 'fromname' => $mail->FromName
,
6146 if (!empty($tempreplyto[0])) {
6147 $context['replyto'] = $tempreplyto[0][0];
6148 $context['replytoname'] = $tempreplyto[0][1];
6150 if ($user->id
> 0) {
6151 $context['touserid'] = $user->id
;
6152 $context['tousername'] = $user->username
;
6155 if (!empty($user->mailformat
) && $user->mailformat
== 1) {
6156 // Only process html templates if the user preferences allow html email.
6158 if (!$messagehtml) {
6159 // If no html has been given, BUT there is an html wrapping template then
6160 // auto convert the text to html and then wrap it.
6161 $messagehtml = trim(text_to_html($messagetext));
6163 $context['body'] = $messagehtml;
6164 $messagehtml = $renderer->render_from_template('core/email_html', $context);
6167 $context['body'] = html_to_text(nl2br($messagetext));
6168 $mail->Subject
= $renderer->render_from_template('core/email_subject', $context);
6169 $mail->FromName
= $renderer->render_from_template('core/email_fromname', $context);
6170 $messagetext = $renderer->render_from_template('core/email_text', $context);
6172 // Autogenerate a MessageID if it's missing.
6173 if (empty($mail->MessageID
)) {
6174 $mail->MessageID
= generate_email_messageid();
6177 if ($messagehtml && !empty($user->mailformat
) && $user->mailformat
== 1) {
6178 // Don't ever send HTML to users who don't want it.
6179 $mail->isHTML(true);
6180 $mail->Encoding
= 'quoted-printable';
6181 $mail->Body
= $messagehtml;
6182 $mail->AltBody
= "\n$messagetext\n";
6184 $mail->IsHTML(false);
6185 $mail->Body
= "\n$messagetext\n";
6188 if ($attachment && $attachname) {
6189 if (preg_match( "~\\.\\.~" , $attachment )) {
6190 // Security check for ".." in dir path.
6191 $supportuser = core_user
::get_support_user();
6192 $temprecipients[] = array($supportuser->email
, fullname($supportuser, true));
6193 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6195 require_once($CFG->libdir
.'/filelib.php');
6196 $mimetype = mimeinfo('type', $attachname);
6198 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6199 // The absolute (real) path is also fetched to ensure that comparisons to allowed paths are compared equally.
6200 $attachpath = str_replace('\\', '/', realpath($attachment));
6202 // Build an array of all filepaths from which attachments can be added (normalised slashes, absolute/real path).
6203 $allowedpaths = array_map(function(string $path): string {
6204 return str_replace('\\', '/', realpath($path));
6209 $CFG->localcachedir
,
6211 $CFG->localrequestdir
,
6214 // Set addpath to true.
6217 // Check if attachment includes one of the allowed paths.
6218 foreach (array_filter($allowedpaths) as $allowedpath) {
6219 // Set addpath to false if the attachment includes one of the allowed paths.
6220 if (strpos($attachpath, $allowedpath) === 0) {
6226 // If the attachment is a full path to a file in the multiple allowed paths, use it as is,
6227 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6228 if ($addpath == true) {
6229 $attachment = $CFG->dataroot
. '/' . $attachment;
6232 $mail->addAttachment($attachment, $attachname, 'base64', $mimetype);
6236 // Check if the email should be sent in an other charset then the default UTF-8.
6237 if ((!empty($CFG->sitemailcharset
) ||
!empty($CFG->allowusermailcharset
))) {
6239 // Use the defined site mail charset or eventually the one preferred by the recipient.
6240 $charset = $CFG->sitemailcharset
;
6241 if (!empty($CFG->allowusermailcharset
)) {
6242 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id
)) {
6243 $charset = $useremailcharset;
6247 // Convert all the necessary strings if the charset is supported.
6248 $charsets = get_list_of_charsets();
6249 unset($charsets['UTF-8']);
6250 if (in_array($charset, $charsets)) {
6251 $mail->CharSet
= $charset;
6252 $mail->FromName
= core_text
::convert($mail->FromName
, 'utf-8', strtolower($charset));
6253 $mail->Subject
= core_text
::convert($mail->Subject
, 'utf-8', strtolower($charset));
6254 $mail->Body
= core_text
::convert($mail->Body
, 'utf-8', strtolower($charset));
6255 $mail->AltBody
= core_text
::convert($mail->AltBody
, 'utf-8', strtolower($charset));
6257 foreach ($temprecipients as $key => $values) {
6258 $temprecipients[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
6260 foreach ($tempreplyto as $key => $values) {
6261 $tempreplyto[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
6266 foreach ($temprecipients as $values) {
6267 $mail->addAddress($values[0], $values[1]);
6269 foreach ($tempreplyto as $values) {
6270 $mail->addReplyTo($values[0], $values[1]);
6273 if (!empty($CFG->emaildkimselector
)) {
6274 $domain = substr(strrchr($mail->From
, "@"), 1);
6275 $pempath = "{$CFG->dataroot}/dkim/{$domain}/{$CFG->emaildkimselector}.private";
6276 if (file_exists($pempath)) {
6277 $mail->DKIM_domain
= $domain;
6278 $mail->DKIM_private
= $pempath;
6279 $mail->DKIM_selector
= $CFG->emaildkimselector
;
6280 $mail->DKIM_identity
= $mail->From
;
6282 debugging("Email DKIM selector chosen due to {$mail->From} but no certificate found at $pempath", DEBUG_DEVELOPER
);
6286 if ($mail->send()) {
6287 set_send_count($user);
6288 if (!empty($mail->SMTPDebug
)) {
6293 // Trigger event for failing to send email.
6294 $event = \core\event\email_failed
::create(array(
6295 'context' => context_system
::instance(),
6296 'userid' => $from->id
,
6297 'relateduserid' => $user->id
,
6299 'subject' => $subject,
6300 'message' => $messagetext,
6301 'errorinfo' => $mail->ErrorInfo
6306 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo
);
6308 if (!empty($mail->SMTPDebug
)) {
6316 * Check to see if a user's real email address should be used for the "From" field.
6318 * @param object $from The user object for the user we are sending the email from.
6319 * @param object $user The user object that we are sending the email to.
6320 * @param array $unused No longer used.
6321 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6323 function can_send_from_real_email_address($from, $user, $unused = null) {
6325 if (!isset($CFG->allowedemaildomains
) ||
empty(trim($CFG->allowedemaildomains
))) {
6328 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains
));
6329 // Email is in the list of allowed domains for sending email,
6330 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6331 // in a course with the sender.
6332 if (\core\ip_utils
::is_domain_in_allowed_list(substr($from->email
, strpos($from->email
, '@') +
1), $alloweddomains)
6333 && ($from->maildisplay
== core_user
::MAILDISPLAY_EVERYONE
6334 ||
($from->maildisplay
== core_user
::MAILDISPLAY_COURSE_MEMBERS_ONLY
6335 && enrol_get_shared_courses($user, $from, false, true)))) {
6342 * Generate a signoff for emails based on support settings
6346 function generate_email_signoff() {
6350 if (!empty($CFG->supportname
)) {
6351 $signoff .= $CFG->supportname
."\n";
6353 if (!empty($CFG->supportemail
)) {
6354 $signoff .= $CFG->supportemail
."\n";
6356 if (!empty($CFG->supportpage
)) {
6357 $signoff .= $CFG->supportpage
."\n";
6363 * Sets specified user's password and send the new password to the user via email.
6365 * @param stdClass $user A {@link $USER} object
6366 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6367 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6369 function setnew_password_and_mail($user, $fasthash = false) {
6372 // We try to send the mail in language the user understands,
6373 // unfortunately the filter_string() does not support alternative langs yet
6374 // so multilang will not work properly for site->fullname.
6375 $lang = empty($user->lang
) ?
get_newuser_language() : $user->lang
;
6379 $supportuser = core_user
::get_support_user();
6381 $newpassword = generate_password();
6383 update_internal_user_password($user, $newpassword, $fasthash);
6385 $a = new stdClass();
6386 $a->firstname
= fullname($user, true);
6387 $a->sitename
= format_string($site->fullname
);
6388 $a->username
= $user->username
;
6389 $a->newpassword
= $newpassword;
6390 $a->link
= $CFG->wwwroot
.'/login/?lang='.$lang;
6391 $a->signoff
= generate_email_signoff();
6393 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6395 $subject = format_string($site->fullname
) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6397 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6398 return email_to_user($user, $supportuser, $subject, $message);
6403 * Resets specified user's password and send the new password to the user via email.
6405 * @param stdClass $user A {@link $USER} object
6406 * @return bool Returns true if mail was sent OK and false if there was an error.
6408 function reset_password_and_mail($user) {
6412 $supportuser = core_user
::get_support_user();
6414 $userauth = get_auth_plugin($user->auth
);
6415 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth
)) {
6416 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6420 $newpassword = generate_password();
6422 if (!$userauth->user_update_password($user, $newpassword)) {
6423 print_error("cannotsetpassword");
6426 $a = new stdClass();
6427 $a->firstname
= $user->firstname
;
6428 $a->lastname
= $user->lastname
;
6429 $a->sitename
= format_string($site->fullname
);
6430 $a->username
= $user->username
;
6431 $a->newpassword
= $newpassword;
6432 $a->link
= $CFG->wwwroot
.'/login/change_password.php';
6433 $a->signoff
= generate_email_signoff();
6435 $message = get_string('newpasswordtext', '', $a);
6437 $subject = format_string($site->fullname
) .': '. get_string('changedpassword');
6439 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6441 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6442 return email_to_user($user, $supportuser, $subject, $message);
6446 * Send email to specified user with confirmation text and activation link.
6448 * @param stdClass $user A {@link $USER} object
6449 * @param string $confirmationurl user confirmation URL
6450 * @return bool Returns true if mail was sent OK and false if there was an error.
6452 function send_confirmation_email($user, $confirmationurl = null) {
6456 $supportuser = core_user
::get_support_user();
6458 $data = new stdClass();
6459 $data->sitename
= format_string($site->fullname
);
6460 $data->admin
= generate_email_signoff();
6462 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname
));
6464 if (empty($confirmationurl)) {
6465 $confirmationurl = '/login/confirm.php';
6468 $confirmationurl = new moodle_url($confirmationurl);
6469 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6470 $confirmationurl->remove_params('data');
6471 $confirmationpath = $confirmationurl->out(false);
6473 // We need to custom encode the username to include trailing dots in the link.
6474 // Because of this custom encoding we can't use moodle_url directly.
6475 // Determine if a query string is present in the confirmation url.
6476 $hasquerystring = strpos($confirmationpath, '?') !== false;
6477 // Perform normal url encoding of the username first.
6478 $username = urlencode($user->username
);
6479 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6480 $username = str_replace('.', '%2E', $username);
6482 $data->link
= $confirmationpath . ( $hasquerystring ?
'&' : '?') . 'data='. $user->secret
.'/'. $username;
6484 $message = get_string('emailconfirmation', '', $data);
6485 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6487 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6488 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6492 * Sends a password change confirmation email.
6494 * @param stdClass $user A {@link $USER} object
6495 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6496 * @return bool Returns true if mail was sent OK and false if there was an error.
6498 function send_password_change_confirmation_email($user, $resetrecord) {
6502 $supportuser = core_user
::get_support_user();
6503 $pwresetmins = isset($CFG->pwresettime
) ?
floor($CFG->pwresettime
/ MINSECS
) : 30;
6505 $data = new stdClass();
6506 $data->firstname
= $user->firstname
;
6507 $data->lastname
= $user->lastname
;
6508 $data->username
= $user->username
;
6509 $data->sitename
= format_string($site->fullname
);
6510 $data->link
= $CFG->wwwroot
.'/login/forgot_password.php?token='. $resetrecord->token
;
6511 $data->admin
= generate_email_signoff();
6512 $data->resetminutes
= $pwresetmins;
6514 $message = get_string('emailresetconfirmation', '', $data);
6515 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname
));
6517 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6518 return email_to_user($user, $supportuser, $subject, $message);
6523 * Sends an email containing information on how to change your password.
6525 * @param stdClass $user A {@link $USER} object
6526 * @return bool Returns true if mail was sent OK and false if there was an error.
6528 function send_password_change_info($user) {
6530 $supportuser = core_user
::get_support_user();
6532 $data = new stdClass();
6533 $data->firstname
= $user->firstname
;
6534 $data->lastname
= $user->lastname
;
6535 $data->username
= $user->username
;
6536 $data->sitename
= format_string($site->fullname
);
6537 $data->admin
= generate_email_signoff();
6539 if (!is_enabled_auth($user->auth
)) {
6540 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6541 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6542 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6543 return email_to_user($user, $supportuser, $subject, $message);
6546 $userauth = get_auth_plugin($user->auth
);
6547 ['subject' => $subject, 'message' => $message] = $userauth->get_password_change_info($user);
6549 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6550 return email_to_user($user, $supportuser, $subject, $message);
6554 * Check that an email is allowed. It returns an error message if there was a problem.
6556 * @param string $email Content of email
6557 * @return string|false
6559 function email_is_not_allowed($email) {
6562 // Comparing lowercase domains.
6563 $email = strtolower($email);
6564 if (!empty($CFG->allowemailaddresses
)) {
6565 $allowed = explode(' ', strtolower($CFG->allowemailaddresses
));
6566 foreach ($allowed as $allowedpattern) {
6567 $allowedpattern = trim($allowedpattern);
6568 if (!$allowedpattern) {
6571 if (strpos($allowedpattern, '.') === 0) {
6572 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6573 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6577 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6581 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses
);
6583 } else if (!empty($CFG->denyemailaddresses
)) {
6584 $denied = explode(' ', strtolower($CFG->denyemailaddresses
));
6585 foreach ($denied as $deniedpattern) {
6586 $deniedpattern = trim($deniedpattern);
6587 if (!$deniedpattern) {
6590 if (strpos($deniedpattern, '.') === 0) {
6591 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6592 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6593 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
6596 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6597 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
6608 * Returns local file storage instance
6610 * @return file_storage
6612 function get_file_storage($reset = false) {
6626 require_once("$CFG->libdir/filelib.php");
6628 $fs = new file_storage();
6634 * Returns local file storage instance
6636 * @return file_browser
6638 function get_file_browser() {
6647 require_once("$CFG->libdir/filelib.php");
6649 $fb = new file_browser();
6655 * Returns file packer
6657 * @param string $mimetype default application/zip
6658 * @return file_packer
6660 function get_file_packer($mimetype='application/zip') {
6663 static $fp = array();
6665 if (isset($fp[$mimetype])) {
6666 return $fp[$mimetype];
6669 switch ($mimetype) {
6670 case 'application/zip':
6671 case 'application/vnd.moodle.profiling':
6672 $classname = 'zip_packer';
6675 case 'application/x-gzip' :
6676 $classname = 'tgz_packer';
6679 case 'application/vnd.moodle.backup':
6680 $classname = 'mbz_packer';
6687 require_once("$CFG->libdir/filestorage/$classname.php");
6688 $fp[$mimetype] = new $classname();
6690 return $fp[$mimetype];
6694 * Returns current name of file on disk if it exists.
6696 * @param string $newfile File to be verified
6697 * @return string Current name of file on disk if true
6699 function valid_uploaded_file($newfile) {
6700 if (empty($newfile)) {
6703 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6704 return $newfile['tmp_name'];
6711 * Returns the maximum size for uploading files.
6713 * There are seven possible upload limits:
6714 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6715 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6716 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6717 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6718 * 5. by the Moodle admin in $CFG->maxbytes
6719 * 6. by the teacher in the current course $course->maxbytes
6720 * 7. by the teacher for the current module, eg $assignment->maxbytes
6722 * These last two are passed to this function as arguments (in bytes).
6723 * Anything defined as 0 is ignored.
6724 * The smallest of all the non-zero numbers is returned.
6726 * @todo Finish documenting this function
6728 * @param int $sitebytes Set maximum size
6729 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6730 * @param int $modulebytes Current module ->maxbytes (in bytes)
6731 * @param bool $unused This parameter has been deprecated and is not used any more.
6732 * @return int The maximum size for uploading files.
6734 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6736 if (! $filesize = ini_get('upload_max_filesize')) {
6739 $minimumsize = get_real_size($filesize);
6741 if ($postsize = ini_get('post_max_size')) {
6742 $postsize = get_real_size($postsize);
6743 if ($postsize < $minimumsize) {
6744 $minimumsize = $postsize;
6748 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6749 $minimumsize = $sitebytes;
6752 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6753 $minimumsize = $coursebytes;
6756 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6757 $minimumsize = $modulebytes;
6760 return $minimumsize;
6764 * Returns the maximum size for uploading files for the current user
6766 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6768 * @param context $context The context in which to check user capabilities
6769 * @param int $sitebytes Set maximum size
6770 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6771 * @param int $modulebytes Current module ->maxbytes (in bytes)
6772 * @param stdClass $user The user
6773 * @param bool $unused This parameter has been deprecated and is not used any more.
6774 * @return int The maximum size for uploading files.
6776 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6784 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6785 return USER_CAN_IGNORE_FILE_SIZE_LIMITS
;
6788 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6792 * Returns an array of possible sizes in local language
6794 * Related to {@link get_max_upload_file_size()} - this function returns an
6795 * array of possible sizes in an array, translated to the
6798 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6800 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6801 * with the value set to 0. This option will be the first in the list.
6803 * @uses SORT_NUMERIC
6804 * @param int $sitebytes Set maximum size
6805 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6806 * @param int $modulebytes Current module ->maxbytes (in bytes)
6807 * @param int|array $custombytes custom upload size/s which will be added to list,
6808 * Only value/s smaller then maxsize will be added to list.
6811 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6814 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6818 if ($sitebytes == 0) {
6819 // Will get the minimum of upload_max_filesize or post_max_size.
6820 $sitebytes = get_max_upload_file_size();
6823 $filesize = array();
6824 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6825 5242880, 10485760, 20971520, 52428800, 104857600,
6826 262144000, 524288000, 786432000, 1073741824,
6827 2147483648, 4294967296, 8589934592);
6829 // If custombytes is given and is valid then add it to the list.
6830 if (is_number($custombytes) and $custombytes > 0) {
6831 $custombytes = (int)$custombytes;
6832 if (!in_array($custombytes, $sizelist)) {
6833 $sizelist[] = $custombytes;
6835 } else if (is_array($custombytes)) {
6836 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6839 // Allow maxbytes to be selected if it falls outside the above boundaries.
6840 if (isset($CFG->maxbytes
) && !in_array(get_real_size($CFG->maxbytes
), $sizelist)) {
6841 // Note: get_real_size() is used in order to prevent problems with invalid values.
6842 $sizelist[] = get_real_size($CFG->maxbytes
);
6845 foreach ($sizelist as $sizebytes) {
6846 if ($sizebytes < $maxsize && $sizebytes > 0) {
6847 $filesize[(string)intval($sizebytes)] = display_size($sizebytes, 0);
6854 (($modulebytes < $coursebytes ||
$coursebytes == 0) &&
6855 ($modulebytes < $sitebytes ||
$sitebytes == 0))) {
6856 $limitlevel = get_string('activity', 'core');
6857 $displaysize = display_size($modulebytes, 0);
6858 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6860 } else if ($coursebytes && ($coursebytes < $sitebytes ||
$sitebytes == 0)) {
6861 $limitlevel = get_string('course', 'core');
6862 $displaysize = display_size($coursebytes, 0);
6863 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6865 } else if ($sitebytes) {
6866 $limitlevel = get_string('site', 'core');
6867 $displaysize = display_size($sitebytes, 0);
6868 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6871 krsort($filesize, SORT_NUMERIC
);
6873 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6874 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) +
$filesize;
6881 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6883 * If excludefiles is defined, then that file/directory is ignored
6884 * If getdirs is true, then (sub)directories are included in the output
6885 * If getfiles is true, then files are included in the output
6886 * (at least one of these must be true!)
6888 * @todo Finish documenting this function. Add examples of $excludefile usage.
6890 * @param string $rootdir A given root directory to start from
6891 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6892 * @param bool $descend If true then subdirectories are recursed as well
6893 * @param bool $getdirs If true then (sub)directories are included in the output
6894 * @param bool $getfiles If true then files are included in the output
6895 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6897 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6901 if (!$getdirs and !$getfiles) { // Nothing to show.
6905 if (!is_dir($rootdir)) { // Must be a directory.
6909 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6913 if (!is_array($excludefiles)) {
6914 $excludefiles = array($excludefiles);
6917 while (false !== ($file = readdir($dir))) {
6918 $firstchar = substr($file, 0, 1);
6919 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6922 $fullfile = $rootdir .'/'. $file;
6923 if (filetype($fullfile) == 'dir') {
6928 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6929 foreach ($subdirs as $subdir) {
6930 $dirs[] = $file .'/'. $subdir;
6933 } else if ($getfiles) {
6946 * Adds up all the files in a directory and works out the size.
6948 * @param string $rootdir The directory to start from
6949 * @param string $excludefile A file to exclude when summing directory size
6950 * @return int The summed size of all files and subfiles within the root directory
6952 function get_directory_size($rootdir, $excludefile='') {
6955 // Do it this way if we can, it's much faster.
6956 if (!empty($CFG->pathtodu
) && is_executable(trim($CFG->pathtodu
))) {
6957 $command = trim($CFG->pathtodu
).' -sk '.escapeshellarg($rootdir);
6960 exec($command, $output, $return);
6961 if (is_array($output)) {
6962 // We told it to return k.
6963 return get_real_size(intval($output[0]).'k');
6967 if (!is_dir($rootdir)) {
6968 // Must be a directory.
6972 if (!$dir = @opendir
($rootdir)) {
6973 // Can't open it for some reason.
6979 while (false !== ($file = readdir($dir))) {
6980 $firstchar = substr($file, 0, 1);
6981 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6984 $fullfile = $rootdir .'/'. $file;
6985 if (filetype($fullfile) == 'dir') {
6986 $size +
= get_directory_size($fullfile, $excludefile);
6988 $size +
= filesize($fullfile);
6997 * Converts bytes into display form
6999 * @param int $size The size to convert to human readable form
7000 * @param int $decimalplaces If specified, uses fixed number of decimal places
7001 * @param string $fixedunits If specified, uses fixed units (e.g. 'KB')
7002 * @return string Display version of size
7004 function display_size($size, int $decimalplaces = 1, string $fixedunits = ''): string {
7008 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS
) {
7009 return get_string('unlimited');
7012 if (empty($units)) {
7013 $units[] = get_string('sizeb');
7014 $units[] = get_string('sizekb');
7015 $units[] = get_string('sizemb');
7016 $units[] = get_string('sizegb');
7017 $units[] = get_string('sizetb');
7018 $units[] = get_string('sizepb');
7021 switch ($fixedunits) {
7041 $magnitude = floor(log($size, 1024));
7042 $magnitude = max(0, min(5, $magnitude));
7045 throw new coding_exception('Unknown fixed units value: ' . $fixedunits);
7048 // Special case for magnitude 0 (bytes) - never use decimal places.
7050 if ($magnitude === 0) {
7051 return round($size) . $nbsp . $units[$magnitude];
7054 // Convert to specified units.
7055 $sizeinunit = $size / 1024 ** $magnitude;
7057 // Fixed decimal places.
7058 return sprintf('%.' . $decimalplaces . 'f', $sizeinunit) . $nbsp . $units[$magnitude];
7062 * Cleans a given filename by removing suspicious or troublesome characters
7064 * @see clean_param()
7065 * @param string $string file name
7066 * @return string cleaned file name
7068 function clean_filename($string) {
7069 return clean_param($string, PARAM_FILE
);
7072 // STRING TRANSLATION.
7075 * Returns the code for the current language
7080 function current_language() {
7081 global $CFG, $USER, $SESSION, $COURSE;
7083 if (!empty($SESSION->forcelang
)) {
7084 // Allows overriding course-forced language (useful for admins to check
7085 // issues in courses whose language they don't understand).
7086 // Also used by some code to temporarily get language-related information in a
7087 // specific language (see force_current_language()).
7088 $return = $SESSION->forcelang
;
7090 } else if (!empty($COURSE->id
) and $COURSE->id
!= SITEID
and !empty($COURSE->lang
)) {
7091 // Course language can override all other settings for this page.
7092 $return = $COURSE->lang
;
7094 } else if (!empty($SESSION->lang
)) {
7095 // Session language can override other settings.
7096 $return = $SESSION->lang
;
7098 } else if (!empty($USER->lang
)) {
7099 $return = $USER->lang
;
7101 } else if (isset($CFG->lang
)) {
7102 $return = $CFG->lang
;
7108 // Just in case this slipped in from somewhere by accident.
7109 $return = str_replace('_utf8', '', $return);
7115 * Returns parent language of current active language if defined
7118 * @param string $lang null means current language
7121 function get_parent_language($lang=null) {
7123 $parentlang = get_string_manager()->get_string('parentlanguage', 'langconfig', null, $lang);
7125 if ($parentlang === 'en') {
7133 * Force the current language to get strings and dates localised in the given language.
7135 * After calling this function, all strings will be provided in the given language
7136 * until this function is called again, or equivalent code is run.
7138 * @param string $language
7139 * @return string previous $SESSION->forcelang value
7141 function force_current_language($language) {
7143 $sessionforcelang = isset($SESSION->forcelang
) ?
$SESSION->forcelang
: '';
7144 if ($language !== $sessionforcelang) {
7145 // Seting forcelang to null or an empty string disables it's effect.
7146 if (empty($language) ||
get_string_manager()->translation_exists($language, false)) {
7147 $SESSION->forcelang
= $language;
7151 return $sessionforcelang;
7155 * Returns current string_manager instance.
7157 * The param $forcereload is needed for CLI installer only where the string_manager instance
7158 * must be replaced during the install.php script life time.
7161 * @param bool $forcereload shall the singleton be released and new instance created instead?
7162 * @return core_string_manager
7164 function get_string_manager($forcereload=false) {
7167 static $singleton = null;
7172 if ($singleton === null) {
7173 if (empty($CFG->early_install_lang
)) {
7175 $transaliases = array();
7176 if (empty($CFG->langlist
)) {
7177 $translist = array();
7179 $translist = explode(',', $CFG->langlist
);
7180 $translist = array_map('trim', $translist);
7181 // Each language in the $CFG->langlist can has an "alias" that would substitute the default language name.
7182 foreach ($translist as $i => $value) {
7183 $parts = preg_split('/\s*\|\s*/', $value, 2);
7184 if (count($parts) == 2) {
7185 $transaliases[$parts[0]] = $parts[1];
7186 $translist[$i] = $parts[0];
7191 if (!empty($CFG->config_php_settings
['customstringmanager'])) {
7192 $classname = $CFG->config_php_settings
['customstringmanager'];
7194 if (class_exists($classname)) {
7195 $implements = class_implements($classname);
7197 if (isset($implements['core_string_manager'])) {
7198 $singleton = new $classname($CFG->langotherroot
, $CFG->langlocalroot
, $translist, $transaliases);
7202 debugging('Unable to instantiate custom string manager: class '.$classname.
7203 ' does not implement the core_string_manager interface.');
7207 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7211 $singleton = new core_string_manager_standard($CFG->langotherroot
, $CFG->langlocalroot
, $translist, $transaliases);
7214 $singleton = new core_string_manager_install();
7222 * Returns a localized string.
7224 * Returns the translated string specified by $identifier as
7225 * for $module. Uses the same format files as STphp.
7226 * $a is an object, string or number that can be used
7227 * within translation strings
7229 * eg 'hello {$a->firstname} {$a->lastname}'
7232 * If you would like to directly echo the localized string use
7233 * the function {@link print_string()}
7235 * Example usage of this function involves finding the string you would
7236 * like a local equivalent of and using its identifier and module information
7237 * to retrieve it.<br/>
7238 * If you open moodle/lang/en/moodle.php and look near line 278
7239 * you will find a string to prompt a user for their word for 'course'
7241 * $string['course'] = 'Course';
7243 * So if you want to display the string 'Course'
7244 * in any language that supports it on your site
7245 * you just need to use the identifier 'course'
7247 * $mystring = '<strong>'. get_string('course') .'</strong>';
7250 * If the string you want is in another file you'd take a slightly
7251 * different approach. Looking in moodle/lang/en/calendar.php you find
7254 * $string['typecourse'] = 'Course event';
7256 * If you want to display the string "Course event" in any language
7257 * supported you would use the identifier 'typecourse' and the module 'calendar'
7258 * (because it is in the file calendar.php):
7260 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7263 * As a last resort, should the identifier fail to map to a string
7264 * the returned string will be [[ $identifier ]]
7266 * In Moodle 2.3 there is a new argument to this function $lazyload.
7267 * Setting $lazyload to true causes get_string to return a lang_string object
7268 * rather than the string itself. The fetching of the string is then put off until
7269 * the string object is first used. The object can be used by calling it's out
7270 * method or by casting the object to a string, either directly e.g.
7271 * (string)$stringobject
7272 * or indirectly by using the string within another string or echoing it out e.g.
7273 * echo $stringobject
7274 * return "<p>{$stringobject}</p>";
7275 * It is worth noting that using $lazyload and attempting to use the string as an
7276 * array key will cause a fatal error as objects cannot be used as array keys.
7277 * But you should never do that anyway!
7278 * For more information {@link lang_string}
7281 * @param string $identifier The key identifier for the localized string
7282 * @param string $component The module where the key identifier is stored,
7283 * usually expressed as the filename in the language pack without the
7284 * .php on the end but can also be written as mod/forum or grade/export/xls.
7285 * If none is specified then moodle.php is used.
7286 * @param string|object|array $a An object, string or number that can be used
7287 * within translation strings
7288 * @param bool $lazyload If set to true a string object is returned instead of
7289 * the string itself. The string then isn't calculated until it is first used.
7290 * @return string The localized string.
7291 * @throws coding_exception
7293 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7296 // If the lazy load argument has been supplied return a lang_string object
7298 // We need to make sure it is true (and a bool) as you will see below there
7299 // used to be a forth argument at one point.
7300 if ($lazyload === true) {
7301 return new lang_string($identifier, $component, $a);
7304 if ($CFG->debugdeveloper
&& clean_param($identifier, PARAM_STRINGID
) === '') {
7305 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER
);
7308 // There is now a forth argument again, this time it is a boolean however so
7309 // we can still check for the old extralocations parameter.
7310 if (!is_bool($lazyload) && !empty($lazyload)) {
7311 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7314 if (strpos($component, '/') !== false) {
7315 debugging('The module name you passed to get_string is the deprecated format ' .
7316 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER
);
7317 $componentpath = explode('/', $component);
7319 switch ($componentpath[0]) {
7321 $component = $componentpath[1];
7325 $component = 'block_'.$componentpath[1];
7328 $component = 'enrol_'.$componentpath[1];
7331 $component = 'format_'.$componentpath[1];
7334 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7339 $result = get_string_manager()->get_string($identifier, $component, $a);
7341 // Debugging feature lets you display string identifier and component.
7342 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
7343 $result .= ' {' . $identifier . '/' . $component . '}';
7349 * Converts an array of strings to their localized value.
7351 * @param array $array An array of strings
7352 * @param string $component The language module that these strings can be found in.
7353 * @return stdClass translated strings.
7355 function get_strings($array, $component = '') {
7356 $string = new stdClass
;
7357 foreach ($array as $item) {
7358 $string->$item = get_string($item, $component);
7364 * Prints out a translated string.
7366 * Prints out a translated string using the return value from the {@link get_string()} function.
7368 * Example usage of this function when the string is in the moodle.php file:<br/>
7371 * print_string('course');
7375 * Example usage of this function when the string is not in the moodle.php file:<br/>
7378 * print_string('typecourse', 'calendar');
7383 * @param string $identifier The key identifier for the localized string
7384 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7385 * @param string|object|array $a An object, string or number that can be used within translation strings
7387 function print_string($identifier, $component = '', $a = null) {
7388 echo get_string($identifier, $component, $a);
7392 * Returns a list of charset codes
7394 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7395 * (checking that such charset is supported by the texlib library!)
7397 * @return array And associative array with contents in the form of charset => charset
7399 function get_list_of_charsets() {
7402 'EUC-JP' => 'EUC-JP',
7403 'ISO-2022-JP'=> 'ISO-2022-JP',
7404 'ISO-8859-1' => 'ISO-8859-1',
7405 'SHIFT-JIS' => 'SHIFT-JIS',
7406 'GB2312' => 'GB2312',
7407 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7408 'UTF-8' => 'UTF-8');
7416 * Returns a list of valid and compatible themes
7420 function get_list_of_themes() {
7425 if (!empty($CFG->themelist
)) { // Use admin's list of themes.
7426 $themelist = explode(',', $CFG->themelist
);
7428 $themelist = array_keys(core_component
::get_plugin_list("theme"));
7431 foreach ($themelist as $key => $themename) {
7432 $theme = theme_config
::load($themename);
7433 $themes[$themename] = $theme;
7436 core_collator
::asort_objects_by_method($themes, 'get_theme_name');
7442 * Factory function for emoticon_manager
7444 * @return emoticon_manager singleton
7446 function get_emoticon_manager() {
7447 static $singleton = null;
7449 if (is_null($singleton)) {
7450 $singleton = new emoticon_manager();
7457 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7459 * Whenever this manager mentiones 'emoticon object', the following data
7460 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7461 * altidentifier and altcomponent
7463 * @see admin_setting_emoticons
7465 * @copyright 2010 David Mudrak
7466 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7468 class emoticon_manager
{
7471 * Returns the currently enabled emoticons
7473 * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
7474 * @return array of emoticon objects
7476 public function get_emoticons($selectable = false) {
7478 $notselectable = ['martin', 'egg'];
7480 if (empty($CFG->emoticons
)) {
7484 $emoticons = $this->decode_stored_config($CFG->emoticons
);
7486 if (!is_array($emoticons)) {
7487 // Something is wrong with the format of stored setting.
7488 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL
);
7492 foreach ($emoticons as $index => $emote) {
7493 if (in_array($emote->altidentifier
, $notselectable)) {
7495 unset($emoticons[$index]);
7504 * Converts emoticon object into renderable pix_emoticon object
7506 * @param stdClass $emoticon emoticon object
7507 * @param array $attributes explicit HTML attributes to set
7508 * @return pix_emoticon
7510 public function prepare_renderable_emoticon(stdClass
$emoticon, array $attributes = array()) {
7511 $stringmanager = get_string_manager();
7512 if ($stringmanager->string_exists($emoticon->altidentifier
, $emoticon->altcomponent
)) {
7513 $alt = get_string($emoticon->altidentifier
, $emoticon->altcomponent
);
7515 $alt = s($emoticon->text
);
7517 return new pix_emoticon($emoticon->imagename
, $alt, $emoticon->imagecomponent
, $attributes);
7521 * Encodes the array of emoticon objects into a string storable in config table
7523 * @see self::decode_stored_config()
7524 * @param array $emoticons array of emtocion objects
7527 public function encode_stored_config(array $emoticons) {
7528 return json_encode($emoticons);
7532 * Decodes the string into an array of emoticon objects
7534 * @see self::encode_stored_config()
7535 * @param string $encoded
7536 * @return string|null
7538 public function decode_stored_config($encoded) {
7539 $decoded = json_decode($encoded);
7540 if (!is_array($decoded)) {
7547 * Returns default set of emoticons supported by Moodle
7549 * @return array of sdtClasses
7551 public function default_emoticons() {
7553 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7554 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7555 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7556 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7557 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7558 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7559 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7560 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7561 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7562 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7563 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7564 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7565 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7566 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7567 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7568 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7569 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7570 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7571 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7572 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7573 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7574 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7575 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7576 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7577 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7578 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7579 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7580 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7581 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7582 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7587 * Helper method preparing the stdClass with the emoticon properties
7589 * @param string|array $text or array of strings
7590 * @param string $imagename to be used by {@link pix_emoticon}
7591 * @param string $altidentifier alternative string identifier, null for no alt
7592 * @param string $altcomponent where the alternative string is defined
7593 * @param string $imagecomponent to be used by {@link pix_emoticon}
7596 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7597 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7598 return (object)array(
7600 'imagename' => $imagename,
7601 'imagecomponent' => $imagecomponent,
7602 'altidentifier' => $altidentifier,
7603 'altcomponent' => $altcomponent,
7613 * @param string $data Data to encrypt.
7614 * @return string The now encrypted data.
7616 function rc4encrypt($data) {
7617 return endecrypt(get_site_identifier(), $data, '');
7623 * @param string $data Data to decrypt.
7624 * @return string The now decrypted data.
7626 function rc4decrypt($data) {
7627 return endecrypt(get_site_identifier(), $data, 'de');
7631 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7633 * @todo Finish documenting this function
7635 * @param string $pwd The password to use when encrypting or decrypting
7636 * @param string $data The data to be decrypted/encrypted
7637 * @param string $case Either 'de' for decrypt or '' for encrypt
7640 function endecrypt ($pwd, $data, $case) {
7642 if ($case == 'de') {
7643 $data = urldecode($data);
7648 $pwdlength = strlen($pwd);
7650 for ($i = 0; $i <= 255; $i++
) {
7651 $key[$i] = ord(substr($pwd, ($i %
$pwdlength), 1));
7657 for ($i = 0; $i <= 255; $i++
) {
7658 $x = ($x +
$box[$i] +
$key[$i]) %
256;
7659 $tempswap = $box[$i];
7660 $box[$i] = $box[$x];
7661 $box[$x] = $tempswap;
7669 for ($i = 0; $i < strlen($data); $i++
) {
7670 $a = ($a +
1) %
256;
7671 $j = ($j +
$box[$a]) %
256;
7673 $box[$a] = $box[$j];
7675 $k = $box[(($box[$a] +
$box[$j]) %
256)];
7676 $cipherby = ord(substr($data, $i, 1)) ^
$k;
7677 $cipher .= chr($cipherby);
7680 if ($case == 'de') {
7681 $cipher = urldecode(urlencode($cipher));
7683 $cipher = urlencode($cipher);
7689 // ENVIRONMENT CHECKING.
7692 * This method validates a plug name. It is much faster than calling clean_param.
7694 * @param string $name a string that might be a plugin name.
7695 * @return bool if this string is a valid plugin name.
7697 function is_valid_plugin_name($name) {
7698 // This does not work for 'mod', bad luck, use any other type.
7699 return core_component
::is_valid_plugin_name('tool', $name);
7703 * Get a list of all the plugins of a given type that define a certain API function
7704 * in a certain file. The plugin component names and function names are returned.
7706 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7707 * @param string $function the part of the name of the function after the
7708 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7709 * names like report_courselist_hook.
7710 * @param string $file the name of file within the plugin that defines the
7711 * function. Defaults to lib.php.
7712 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7713 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7715 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7718 // We don't include here as all plugin types files would be included.
7719 $plugins = get_plugins_with_function($function, $file, false);
7721 if (empty($plugins[$plugintype])) {
7725 $allplugins = core_component
::get_plugin_list($plugintype);
7727 // Reformat the array and include the files.
7728 $pluginfunctions = array();
7729 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7731 // Check that it has not been removed and the file is still available.
7732 if (!empty($allplugins[$pluginname])) {
7734 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR
. $file;
7735 if (file_exists($filepath)) {
7736 include_once($filepath);
7738 // Now that the file is loaded, we must verify the function still exists.
7739 if (function_exists($functionname)) {
7740 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7742 // Invalidate the cache for next run.
7743 \cache_helper
::invalidate_by_definition('core', 'plugin_functions');
7749 return $pluginfunctions;
7753 * Get a list of all the plugins that define a certain API function in a certain file.
7755 * @param string $function the part of the name of the function after the
7756 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7757 * names like report_courselist_hook.
7758 * @param string $file the name of file within the plugin that defines the
7759 * function. Defaults to lib.php.
7760 * @param bool $include Whether to include the files that contain the functions or not.
7761 * @return array with [plugintype][plugin] = functionname
7763 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7766 if (during_initial_install() ||
isset($CFG->upgraderunning
)) {
7767 // API functions _must not_ be called during an installation or upgrade.
7771 $cache = \cache
::make('core', 'plugin_functions');
7773 // Including both although I doubt that we will find two functions definitions with the same name.
7774 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7775 $key = $function . '_' . clean_param($file, PARAM_ALPHA
);
7776 $pluginfunctions = $cache->get($key);
7779 // Use the plugin manager to check that plugins are currently installed.
7780 $pluginmanager = \core_plugin_manager
::instance();
7782 if ($pluginfunctions !== false) {
7784 // Checking that the files are still available.
7785 foreach ($pluginfunctions as $plugintype => $plugins) {
7787 $allplugins = \core_component
::get_plugin_list($plugintype);
7788 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7789 foreach ($plugins as $plugin => $function) {
7790 if (!isset($installedplugins[$plugin])) {
7791 // Plugin code is still present on disk but it is not installed.
7796 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7797 if (empty($allplugins[$plugin])) {
7802 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR
. $file);
7803 if ($include && $fileexists) {
7804 // Include the files if it was requested.
7805 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR
. $file);
7806 } else if (!$fileexists) {
7807 // If the file is not available any more it should not be returned.
7812 // Check if the function still exists in the file.
7813 if ($include && !function_exists($function)) {
7820 // If the cache is dirty, we should fall through and let it rebuild.
7822 return $pluginfunctions;
7826 $pluginfunctions = array();
7828 // To fill the cached. Also, everything should continue working with cache disabled.
7829 $plugintypes = \core_component
::get_plugin_types();
7830 foreach ($plugintypes as $plugintype => $unused) {
7832 // We need to include files here.
7833 $pluginswithfile = \core_component
::get_plugin_list_with_file($plugintype, $file, true);
7834 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7835 foreach ($pluginswithfile as $plugin => $notused) {
7837 if (!isset($installedplugins[$plugin])) {
7841 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7843 $pluginfunction = false;
7844 if (function_exists($fullfunction)) {
7845 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7846 $pluginfunction = $fullfunction;
7848 } else if ($plugintype === 'mod') {
7849 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7850 $shortfunction = $plugin . '_' . $function;
7851 if (function_exists($shortfunction)) {
7852 $pluginfunction = $shortfunction;
7856 if ($pluginfunction) {
7857 if (empty($pluginfunctions[$plugintype])) {
7858 $pluginfunctions[$plugintype] = array();
7860 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7865 $cache->set($key, $pluginfunctions);
7867 return $pluginfunctions;
7872 * Lists plugin-like directories within specified directory
7874 * This function was originally used for standard Moodle plugins, please use
7875 * new core_component::get_plugin_list() now.
7877 * This function is used for general directory listing and backwards compatility.
7879 * @param string $directory relative directory from root
7880 * @param string $exclude dir name to exclude from the list (defaults to none)
7881 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7882 * @return array Sorted array of directory names found under the requested parameters
7884 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7889 if (empty($basedir)) {
7890 $basedir = $CFG->dirroot
.'/'. $directory;
7893 $basedir = $basedir .'/'. $directory;
7896 if ($CFG->debugdeveloper
and empty($exclude)) {
7897 // Make sure devs do not use this to list normal plugins,
7898 // this is intended for general directories that are not plugins!
7900 $subtypes = core_component
::get_plugin_types();
7901 if (in_array($basedir, $subtypes)) {
7902 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER
);
7907 $ignorelist = array_flip(array_filter([
7919 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7920 if (!$dirhandle = opendir($basedir)) {
7921 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER
);
7924 while (false !== ($dir = readdir($dirhandle))) {
7925 if (strpos($dir, '.') === 0) {
7926 // Ignore directories starting with .
7927 // These are treated as hidden directories.
7930 if (array_key_exists($dir, $ignorelist)) {
7931 // This directory features on the ignore list.
7934 if (filetype($basedir .'/'. $dir) != 'dir') {
7939 closedir($dirhandle);
7948 * Invoke plugin's callback functions
7950 * @param string $type plugin type e.g. 'mod'
7951 * @param string $name plugin name
7952 * @param string $feature feature name
7953 * @param string $action feature's action
7954 * @param array $params parameters of callback function, should be an array
7955 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7958 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7960 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7961 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7965 * Invoke component's callback functions
7967 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7968 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7969 * @param array $params parameters of callback function
7970 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7973 function component_callback($component, $function, array $params = array(), $default = null) {
7975 $functionname = component_callback_exists($component, $function);
7977 if ($params && (array_keys($params) !== range(0, count($params) - 1))) {
7978 // PHP 8 allows to have associative arrays in the call_user_func_array() parameters but
7979 // PHP 7 does not. Using associative arrays can result in different behavior in different PHP versions.
7980 // See https://php.watch/versions/8.0/named-parameters#named-params-call_user_func_array
7981 // This check can be removed when minimum PHP version for Moodle is raised to 8.
7982 debugging('Parameters array can not be an associative array while Moodle supports both PHP 7 and PHP 8.',
7984 $params = array_values($params);
7987 if ($functionname) {
7988 // Function exists, so just return function result.
7989 $ret = call_user_func_array($functionname, $params);
7990 if (is_null($ret)) {
8000 * Determine if a component callback exists and return the function name to call. Note that this
8001 * function will include the required library files so that the functioname returned can be
8004 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
8005 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
8006 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
8007 * @throws coding_exception if invalid component specfied
8009 function component_callback_exists($component, $function) {
8010 global $CFG; // This is needed for the inclusions.
8012 $cleancomponent = clean_param($component, PARAM_COMPONENT
);
8013 if (empty($cleancomponent)) {
8014 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8016 $component = $cleancomponent;
8018 list($type, $name) = core_component
::normalize_component($component);
8019 $component = $type . '_' . $name;
8021 $oldfunction = $name.'_'.$function;
8022 $function = $component.'_'.$function;
8024 $dir = core_component
::get_component_directory($component);
8026 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8029 // Load library and look for function.
8030 if (file_exists($dir.'/lib.php')) {
8031 require_once($dir.'/lib.php');
8034 if (!function_exists($function) and function_exists($oldfunction)) {
8035 if ($type !== 'mod' and $type !== 'core') {
8036 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER
);
8038 $function = $oldfunction;
8041 if (function_exists($function)) {
8048 * Call the specified callback method on the provided class.
8050 * If the callback returns null, then the default value is returned instead.
8051 * If the class does not exist, then the default value is returned.
8053 * @param string $classname The name of the class to call upon.
8054 * @param string $methodname The name of the staticically defined method on the class.
8055 * @param array $params The arguments to pass into the method.
8056 * @param mixed $default The default value.
8057 * @return mixed The return value.
8059 function component_class_callback($classname, $methodname, array $params, $default = null) {
8060 if (!class_exists($classname)) {
8064 if (!method_exists($classname, $methodname)) {
8068 $fullfunction = $classname . '::' . $methodname;
8069 $result = call_user_func_array($fullfunction, $params);
8071 if (null === $result) {
8079 * Checks whether a plugin supports a specified feature.
8081 * @param string $type Plugin type e.g. 'mod'
8082 * @param string $name Plugin name e.g. 'forum'
8083 * @param string $feature Feature code (FEATURE_xx constant)
8084 * @param mixed $default default value if feature support unknown
8085 * @return mixed Feature result (false if not supported, null if feature is unknown,
8086 * otherwise usually true but may have other feature-specific value such as array)
8087 * @throws coding_exception
8089 function plugin_supports($type, $name, $feature, $default = null) {
8092 if ($type === 'mod' and $name === 'NEWMODULE') {
8093 // Somebody forgot to rename the module template.
8097 $component = clean_param($type . '_' . $name, PARAM_COMPONENT
);
8098 if (empty($component)) {
8099 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8104 if ($type === 'mod') {
8105 // We need this special case because we support subplugins in modules,
8106 // otherwise it would end up in infinite loop.
8107 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8108 include_once("$CFG->dirroot/mod/$name/lib.php");
8109 $function = $component.'_supports';
8110 if (!function_exists($function)) {
8111 // Legacy non-frankenstyle function name.
8112 $function = $name.'_supports';
8117 if (!$path = core_component
::get_plugin_directory($type, $name)) {
8118 // Non existent plugin type.
8121 if (file_exists("$path/lib.php")) {
8122 include_once("$path/lib.php");
8123 $function = $component.'_supports';
8127 if ($function and function_exists($function)) {
8128 $supports = $function($feature);
8129 if (is_null($supports)) {
8130 // Plugin does not know - use default.
8137 // Plugin does not care, so use default.
8142 * Returns true if the current version of PHP is greater that the specified one.
8144 * @todo Check PHP version being required here is it too low?
8146 * @param string $version The version of php being tested.
8149 function check_php_version($version='5.2.4') {
8150 return (version_compare(phpversion(), $version) >= 0);
8154 * Determine if moodle installation requires update.
8156 * Checks version numbers of main code and all plugins to see
8157 * if there are any mismatches.
8161 function moodle_needs_upgrading() {
8164 if (empty($CFG->version
)) {
8168 // There is no need to purge plugininfo caches here because
8169 // these caches are not used during upgrade and they are purged after
8172 if (empty($CFG->allversionshash
)) {
8176 $hash = core_component
::get_all_versions_hash();
8178 return ($hash !== $CFG->allversionshash
);
8182 * Returns the major version of this site
8184 * Moodle version numbers consist of three numbers separated by a dot, for
8185 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
8186 * called major version. This function extracts the major version from either
8187 * $CFG->release (default) or eventually from the $release variable defined in
8188 * the main version.php.
8190 * @param bool $fromdisk should the version if source code files be used
8191 * @return string|false the major version like '2.3', false if could not be determined
8193 function moodle_major_version($fromdisk = false) {
8198 require($CFG->dirroot
.'/version.php');
8199 if (empty($release)) {
8204 if (empty($CFG->release
)) {
8207 $release = $CFG->release
;
8210 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8220 * Gets the system locale
8222 * @return string Retuns the current locale.
8224 function moodle_getlocale() {
8227 // Fetch the correct locale based on ostype.
8228 if ($CFG->ostype
== 'WINDOWS') {
8229 $stringtofetch = 'localewin';
8231 $stringtofetch = 'locale';
8234 if (!empty($CFG->locale
)) { // Override locale for all language packs.
8235 return $CFG->locale
;
8238 return get_string($stringtofetch, 'langconfig');
8242 * Sets the system locale
8245 * @param string $locale Can be used to force a locale
8247 function moodle_setlocale($locale='') {
8250 static $currentlocale = ''; // Last locale caching.
8252 $oldlocale = $currentlocale;
8254 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8255 if (!empty($locale)) {
8256 $currentlocale = $locale;
8258 $currentlocale = moodle_getlocale();
8261 // Do nothing if locale already set up.
8262 if ($oldlocale == $currentlocale) {
8266 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8267 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8268 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8270 // Get current values.
8271 $monetary= setlocale (LC_MONETARY
, 0);
8272 $numeric = setlocale (LC_NUMERIC
, 0);
8273 $ctype = setlocale (LC_CTYPE
, 0);
8274 if ($CFG->ostype
!= 'WINDOWS') {
8275 $messages= setlocale (LC_MESSAGES
, 0);
8277 // Set locale to all.
8278 $result = setlocale (LC_ALL
, $currentlocale);
8279 // If setting of locale fails try the other utf8 or utf-8 variant,
8280 // some operating systems support both (Debian), others just one (OSX).
8281 if ($result === false) {
8282 if (stripos($currentlocale, '.UTF-8') !== false) {
8283 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8284 setlocale (LC_ALL
, $newlocale);
8285 } else if (stripos($currentlocale, '.UTF8') !== false) {
8286 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8287 setlocale (LC_ALL
, $newlocale);
8291 setlocale (LC_MONETARY
, $monetary);
8292 setlocale (LC_NUMERIC
, $numeric);
8293 if ($CFG->ostype
!= 'WINDOWS') {
8294 setlocale (LC_MESSAGES
, $messages);
8296 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8297 // To workaround a well-known PHP problem with Turkish letter Ii.
8298 setlocale (LC_CTYPE
, $ctype);
8303 * Count words in a string.
8305 * Words are defined as things between whitespace.
8308 * @param string $string The text to be searched for words. May be HTML.
8309 * @return int The count of words in the specified string
8311 function count_words($string) {
8312 // Before stripping tags, add a space after the close tag of anything that is not obviously inline.
8313 // Also, br is a special case because it definitely delimits a word, but has no close tag.
8314 $string = preg_replace('~
8315 ( # Capture the tag we match.
8316 </ # Start of close tag.
8317 (?! # Do not match any of these specific close tag names.
8318 a> | b> | del> | em> | i> |
8319 ins> | s> | small> |
8320 strong> | sub> | sup> | u>
8322 \w+ # But, apart from those execptions, match any tag name.
8323 > # End of close tag.
8325 <br> | <br\s*/> # Special cases that are not close tags.
8327 ~x', '$1 ', $string); // Add a space after the close tag.
8328 // Now remove HTML tags.
8329 $string = strip_tags($string);
8330 // Decode HTML entities.
8331 $string = html_entity_decode($string);
8333 // Now, the word count is the number of blocks of characters separated
8334 // by any sort of space. That seems to be the definition used by all other systems.
8335 // To be precise about what is considered to separate words:
8336 // * Anything that Unicode considers a 'Separator'
8337 // * Anything that Unicode considers a 'Control character'
8338 // * An em- or en- dash.
8339 return count(preg_split('~[\p{Z}\p{Cc}—–]+~u', $string, -1, PREG_SPLIT_NO_EMPTY
));
8343 * Count letters in a string.
8345 * Letters are defined as chars not in tags and different from whitespace.
8348 * @param string $string The text to be searched for letters. May be HTML.
8349 * @return int The count of letters in the specified text.
8351 function count_letters($string) {
8352 $string = strip_tags($string); // Tags are out now.
8353 $string = html_entity_decode($string);
8354 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8356 return core_text
::strlen($string);
8360 * Generate and return a random string of the specified length.
8362 * @param int $length The length of the string to be created.
8365 function random_string($length=15) {
8366 $randombytes = random_bytes_emulate($length);
8367 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8368 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8369 $pool .= '0123456789';
8370 $poollen = strlen($pool);
8372 for ($i = 0; $i < $length; $i++
) {
8373 $rand = ord($randombytes[$i]);
8374 $string .= substr($pool, ($rand%
($poollen)), 1);
8380 * Generate a complex random string (useful for md5 salts)
8382 * This function is based on the above {@link random_string()} however it uses a
8383 * larger pool of characters and generates a string between 24 and 32 characters
8385 * @param int $length Optional if set generates a string to exactly this length
8388 function complex_random_string($length=null) {
8389 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8390 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8391 $poollen = strlen($pool);
8392 if ($length===null) {
8393 $length = floor(rand(24, 32));
8395 $randombytes = random_bytes_emulate($length);
8397 for ($i = 0; $i < $length; $i++
) {
8398 $rand = ord($randombytes[$i]);
8399 $string .= $pool[($rand%
$poollen)];
8405 * Try to generates cryptographically secure pseudo-random bytes.
8407 * Note this is achieved by fallbacking between:
8408 * - PHP 7 random_bytes().
8409 * - OpenSSL openssl_random_pseudo_bytes().
8410 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8412 * @param int $length requested length in bytes
8413 * @return string binary data
8415 function random_bytes_emulate($length) {
8418 debugging('Invalid random bytes length', DEBUG_DEVELOPER
);
8421 if (function_exists('random_bytes')) {
8422 // Use PHP 7 goodness.
8423 $hash = @random_bytes
($length);
8424 if ($hash !== false) {
8428 if (function_exists('openssl_random_pseudo_bytes')) {
8429 // If you have the openssl extension enabled.
8430 $hash = openssl_random_pseudo_bytes($length);
8431 if ($hash !== false) {
8436 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8437 $staticdata = serialize($CFG) . serialize($_SERVER);
8440 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8441 } while (strlen($hash) < $length);
8443 return substr($hash, 0, $length);
8447 * Given some text (which may contain HTML) and an ideal length,
8448 * this function truncates the text neatly on a word boundary if possible
8451 * @param string $text text to be shortened
8452 * @param int $ideal ideal string length
8453 * @param boolean $exact if false, $text will not be cut mid-word
8454 * @param string $ending The string to append if the passed string is truncated
8455 * @return string $truncate shortened string
8457 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8458 // If the plain text is shorter than the maximum length, return the whole text.
8459 if (core_text
::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8463 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8464 // and only tag in its 'line'.
8465 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER
);
8467 $totallength = core_text
::strlen($ending);
8470 // This array stores information about open and close tags and their position
8471 // in the truncated string. Each item in the array is an object with fields
8472 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8473 // (byte position in truncated text).
8474 $tagdetails = array();
8476 foreach ($lines as $linematchings) {
8477 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8478 if (!empty($linematchings[1])) {
8479 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8480 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8481 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8482 // Record closing tag.
8483 $tagdetails[] = (object) array(
8485 'tag' => core_text
::strtolower($tagmatchings[1]),
8486 'pos' => core_text
::strlen($truncate),
8489 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8490 // Record opening tag.
8491 $tagdetails[] = (object) array(
8493 'tag' => core_text
::strtolower($tagmatchings[1]),
8494 'pos' => core_text
::strlen($truncate),
8496 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8497 $tagdetails[] = (object) array(
8499 'tag' => core_text
::strtolower('if'),
8500 'pos' => core_text
::strlen($truncate),
8502 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8503 $tagdetails[] = (object) array(
8505 'tag' => core_text
::strtolower('if'),
8506 'pos' => core_text
::strlen($truncate),
8510 // Add html-tag to $truncate'd text.
8511 $truncate .= $linematchings[1];
8514 // Calculate the length of the plain text part of the line; handle entities as one character.
8515 $contentlength = core_text
::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8516 if ($totallength +
$contentlength > $ideal) {
8517 // The number of characters which are left.
8518 $left = $ideal - $totallength;
8519 $entitieslength = 0;
8520 // Search for html entities.
8521 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
)) {
8522 // Calculate the real length of all entities in the legal range.
8523 foreach ($entities[0] as $entity) {
8524 if ($entity[1]+
1-$entitieslength <= $left) {
8526 $entitieslength +
= core_text
::strlen($entity[0]);
8528 // No more characters left.
8533 $breakpos = $left +
$entitieslength;
8535 // If the words shouldn't be cut in the middle...
8537 // Search the last occurence of a space.
8538 for (; $breakpos > 0; $breakpos--) {
8539 if ($char = core_text
::substr($linematchings[2], $breakpos, 1)) {
8540 if ($char === '.' or $char === ' ') {
8543 } else if (strlen($char) > 2) {
8544 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8551 if ($breakpos == 0) {
8552 // This deals with the test_shorten_text_no_spaces case.
8553 $breakpos = $left +
$entitieslength;
8554 } else if ($breakpos > $left +
$entitieslength) {
8555 // This deals with the previous for loop breaking on the first char.
8556 $breakpos = $left +
$entitieslength;
8559 $truncate .= core_text
::substr($linematchings[2], 0, $breakpos);
8560 // Maximum length is reached, so get off the loop.
8563 $truncate .= $linematchings[2];
8564 $totallength +
= $contentlength;
8567 // If the maximum length is reached, get off the loop.
8568 if ($totallength >= $ideal) {
8573 // Add the defined ending to the text.
8574 $truncate .= $ending;
8576 // Now calculate the list of open html tags based on the truncate position.
8577 $opentags = array();
8578 foreach ($tagdetails as $taginfo) {
8579 if ($taginfo->open
) {
8580 // Add tag to the beginning of $opentags list.
8581 array_unshift($opentags, $taginfo->tag
);
8583 // Can have multiple exact same open tags, close the last one.
8584 $pos = array_search($taginfo->tag
, array_reverse($opentags, true));
8585 if ($pos !== false) {
8586 unset($opentags[$pos]);
8591 // Close all unclosed html-tags.
8592 foreach ($opentags as $tag) {
8593 if ($tag === 'if') {
8594 $truncate .= '<!--<![endif]-->';
8596 $truncate .= '</' . $tag . '>';
8604 * Shortens a given filename by removing characters positioned after the ideal string length.
8605 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8606 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8608 * @param string $filename file name
8609 * @param int $length ideal string length
8610 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8611 * @return string $shortened shortened file name
8613 function shorten_filename($filename, $length = MAX_FILENAME_SIZE
, $includehash = false) {
8614 $shortened = $filename;
8615 // Extract a part of the filename if it's char size exceeds the ideal string length.
8616 if (core_text
::strlen($filename) > $length) {
8617 // Exclude extension if present in filename.
8618 $mimetypes = get_mimetypes_array();
8619 $extension = pathinfo($filename, PATHINFO_EXTENSION
);
8620 if ($extension && !empty($mimetypes[$extension])) {
8621 $basename = pathinfo($filename, PATHINFO_FILENAME
);
8622 $hash = empty($includehash) ?
'' : ' - ' . substr(sha1($basename), 0, 10);
8623 $shortened = core_text
::substr($basename, 0, $length - strlen($hash)) . $hash;
8624 $shortened .= '.' . $extension;
8626 $hash = empty($includehash) ?
'' : ' - ' . substr(sha1($filename), 0, 10);
8627 $shortened = core_text
::substr($filename, 0, $length - strlen($hash)) . $hash;
8634 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8636 * @param array $path The paths to reduce the length.
8637 * @param int $length Ideal string length
8638 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8639 * @return array $result Shortened paths in array.
8641 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE
, $includehash = false) {
8644 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8645 $carry[] = shorten_filename($singlepath, $length, $includehash);
8653 * Given dates in seconds, how many weeks is the date from startdate
8654 * The first week is 1, the second 2 etc ...
8656 * @param int $startdate Timestamp for the start date
8657 * @param int $thedate Timestamp for the end date
8660 function getweek ($startdate, $thedate) {
8661 if ($thedate < $startdate) {
8665 return floor(($thedate - $startdate) / WEEKSECS
) +
1;
8669 * Returns a randomly generated password of length $maxlen. inspired by
8671 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8672 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8674 * @param int $maxlen The maximum size of the password being generated.
8677 function generate_password($maxlen=10) {
8680 if (empty($CFG->passwordpolicy
)) {
8681 $fillers = PASSWORD_DIGITS
;
8682 $wordlist = file($CFG->wordlist
);
8683 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8684 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8685 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8686 $password = $word1 . $filler1 . $word2;
8688 $minlen = !empty($CFG->minpasswordlength
) ?
$CFG->minpasswordlength
: 0;
8689 $digits = $CFG->minpassworddigits
;
8690 $lower = $CFG->minpasswordlower
;
8691 $upper = $CFG->minpasswordupper
;
8692 $nonalphanum = $CFG->minpasswordnonalphanum
;
8693 $total = $lower +
$upper +
$digits +
$nonalphanum;
8694 // Var minlength should be the greater one of the two ( $minlen and $total ).
8695 $minlen = $minlen < $total ?
$total : $minlen;
8696 // Var maxlen can never be smaller than minlen.
8697 $maxlen = $minlen > $maxlen ?
$minlen : $maxlen;
8698 $additional = $maxlen - $total;
8700 // Make sure we have enough characters to fulfill
8701 // complexity requirements.
8702 $passworddigits = PASSWORD_DIGITS
;
8703 while ($digits > strlen($passworddigits)) {
8704 $passworddigits .= PASSWORD_DIGITS
;
8706 $passwordlower = PASSWORD_LOWER
;
8707 while ($lower > strlen($passwordlower)) {
8708 $passwordlower .= PASSWORD_LOWER
;
8710 $passwordupper = PASSWORD_UPPER
;
8711 while ($upper > strlen($passwordupper)) {
8712 $passwordupper .= PASSWORD_UPPER
;
8714 $passwordnonalphanum = PASSWORD_NONALPHANUM
;
8715 while ($nonalphanum > strlen($passwordnonalphanum)) {
8716 $passwordnonalphanum .= PASSWORD_NONALPHANUM
;
8719 // Now mix and shuffle it all.
8720 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8721 substr(str_shuffle ($passwordupper), 0, $upper) .
8722 substr(str_shuffle ($passworddigits), 0, $digits) .
8723 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8724 substr(str_shuffle ($passwordlower .
8727 $passwordnonalphanum), 0 , $additional));
8730 return substr ($password, 0, $maxlen);
8734 * Given a float, prints it nicely.
8735 * Localized floats must not be used in calculations!
8737 * The stripzeros feature is intended for making numbers look nicer in small
8738 * areas where it is not necessary to indicate the degree of accuracy by showing
8739 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8740 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8742 * @param float $float The float to print
8743 * @param int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision).
8744 * @param bool $localized use localized decimal separator
8745 * @param bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after
8746 * the decimal point are always striped if $decimalpoints is -1.
8747 * @return string locale float
8749 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8750 if (is_null($float)) {
8754 $separator = get_string('decsep', 'langconfig');
8758 if ($decimalpoints == -1) {
8759 // The following counts the number of decimals.
8760 // It is safe as both floatval() and round() functions have same behaviour when non-numeric values are provided.
8761 $floatval = floatval($float);
8762 for ($decimalpoints = 0; $floatval != round($float, $decimalpoints); $decimalpoints++
);
8765 $result = number_format($float, $decimalpoints, $separator, '');
8767 // Remove zeros and final dot if not needed.
8768 $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
8774 * Converts locale specific floating point/comma number back to standard PHP float value
8775 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8777 * @param string $localefloat locale aware float representation
8778 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8779 * @return mixed float|bool - false or the parsed float.
8781 function unformat_float($localefloat, $strict = false) {
8782 $localefloat = trim($localefloat);
8784 if ($localefloat == '') {
8788 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8789 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8791 if ($strict && !is_numeric($localefloat)) {
8795 return (float)$localefloat;
8799 * Given a simple array, this shuffles it up just like shuffle()
8800 * Unlike PHP's shuffle() this function works on any machine.
8802 * @param array $array The array to be rearranged
8805 function swapshuffle($array) {
8807 $last = count($array) - 1;
8808 for ($i = 0; $i <= $last; $i++
) {
8809 $from = rand(0, $last);
8811 $array[$i] = $array[$from];
8812 $array[$from] = $curr;
8818 * Like {@link swapshuffle()}, but works on associative arrays
8820 * @param array $array The associative array to be rearranged
8823 function swapshuffle_assoc($array) {
8825 $newarray = array();
8826 $newkeys = swapshuffle(array_keys($array));
8828 foreach ($newkeys as $newkey) {
8829 $newarray[$newkey] = $array[$newkey];
8835 * Given an arbitrary array, and a number of draws,
8836 * this function returns an array with that amount
8837 * of items. The indexes are retained.
8839 * @todo Finish documenting this function
8841 * @param array $array
8845 function draw_rand_array($array, $draws) {
8849 $last = count($array);
8851 if ($draws > $last) {
8855 while ($draws > 0) {
8858 $keys = array_keys($array);
8859 $rand = rand(0, $last);
8861 $return[$keys[$rand]] = $array[$keys[$rand]];
8862 unset($array[$keys[$rand]]);
8871 * Calculate the difference between two microtimes
8873 * @param string $a The first Microtime
8874 * @param string $b The second Microtime
8877 function microtime_diff($a, $b) {
8878 list($adec, $asec) = explode(' ', $a);
8879 list($bdec, $bsec) = explode(' ', $b);
8880 return $bsec - $asec +
$bdec - $adec;
8884 * Given a list (eg a,b,c,d,e) this function returns
8885 * an array of 1->a, 2->b, 3->c etc
8887 * @param string $list The string to explode into array bits
8888 * @param string $separator The separator used within the list string
8889 * @return array The now assembled array
8891 function make_menu_from_list($list, $separator=',') {
8893 $array = array_reverse(explode($separator, $list), true);
8894 foreach ($array as $key => $item) {
8895 $outarray[$key+
1] = trim($item);
8901 * Creates an array that represents all the current grades that
8902 * can be chosen using the given grading type.
8905 * are scales, zero is no grade, and positive numbers are maximum
8908 * @todo Finish documenting this function or better deprecated this completely!
8910 * @param int $gradingtype
8913 function make_grades_menu($gradingtype) {
8917 if ($gradingtype < 0) {
8918 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8919 return make_menu_from_list($scale->scale
);
8921 } else if ($gradingtype > 0) {
8922 for ($i=$gradingtype; $i>=0; $i--) {
8923 $grades[$i] = $i .' / '. $gradingtype;
8931 * make_unique_id_code
8933 * @todo Finish documenting this function
8936 * @param string $extra Extra string to append to the end of the code
8939 function make_unique_id_code($extra = '') {
8941 $hostname = 'unknownhost';
8942 if (!empty($_SERVER['HTTP_HOST'])) {
8943 $hostname = $_SERVER['HTTP_HOST'];
8944 } else if (!empty($_ENV['HTTP_HOST'])) {
8945 $hostname = $_ENV['HTTP_HOST'];
8946 } else if (!empty($_SERVER['SERVER_NAME'])) {
8947 $hostname = $_SERVER['SERVER_NAME'];
8948 } else if (!empty($_ENV['SERVER_NAME'])) {
8949 $hostname = $_ENV['SERVER_NAME'];
8952 $date = gmdate("ymdHis");
8954 $random = random_string(6);
8957 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8959 return $hostname .'+'. $date .'+'. $random;
8965 * Function to check the passed address is within the passed subnet
8967 * The parameter is a comma separated string of subnet definitions.
8968 * Subnet strings can be in one of three formats:
8969 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8970 * 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)
8971 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8972 * Code for type 1 modified from user posted comments by mediator at
8973 * {@link http://au.php.net/manual/en/function.ip2long.php}
8975 * @param string $addr The address you are checking
8976 * @param string $subnetstr The string of subnet addresses
8979 function address_in_subnet($addr, $subnetstr) {
8981 if ($addr == '0.0.0.0') {
8984 $subnets = explode(',', $subnetstr);
8986 $addr = trim($addr);
8987 $addr = cleanremoteaddr($addr, false); // Normalise.
8988 if ($addr === null) {
8991 $addrparts = explode(':', $addr);
8993 $ipv6 = strpos($addr, ':');
8995 foreach ($subnets as $subnet) {
8996 $subnet = trim($subnet);
8997 if ($subnet === '') {
9001 if (strpos($subnet, '/') !== false) {
9002 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
9003 list($ip, $mask) = explode('/', $subnet);
9004 $mask = trim($mask);
9005 if (!is_number($mask)) {
9006 continue; // Incorect mask number, eh?
9008 $ip = cleanremoteaddr($ip, false); // Normalise.
9012 if (strpos($ip, ':') !== false) {
9017 if ($mask > 128 or $mask < 0) {
9018 continue; // Nonsense.
9021 return true; // Any address.
9024 if ($ip === $addr) {
9029 $ipparts = explode(':', $ip);
9030 $modulo = $mask %
16;
9031 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
9032 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
9033 if (implode(':', $ipnet) === implode(':', $addrnet)) {
9037 $pos = ($mask-$modulo)/16;
9038 $ipnet = hexdec($ipparts[$pos]);
9039 $addrnet = hexdec($addrparts[$pos]);
9040 $mask = 0xffff << (16 - $modulo);
9041 if (($addrnet & $mask) == ($ipnet & $mask)) {
9051 if ($mask > 32 or $mask < 0) {
9052 continue; // Nonsense.
9058 if ($ip === $addr) {
9063 $mask = 0xffffffff << (32 - $mask);
9064 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
9069 } else if (strpos($subnet, '-') !== false) {
9070 // 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.
9071 $parts = explode('-', $subnet);
9072 if (count($parts) != 2) {
9076 if (strpos($subnet, ':') !== false) {
9081 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9082 if ($ipstart === null) {
9085 $ipparts = explode(':', $ipstart);
9086 $start = hexdec(array_pop($ipparts));
9087 $ipparts[] = trim($parts[1]);
9088 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
9089 if ($ipend === null) {
9093 $ipnet = implode(':', $ipparts);
9094 if (strpos($addr, $ipnet) !== 0) {
9097 $ipparts = explode(':', $ipend);
9098 $end = hexdec($ipparts[7]);
9100 $addrend = hexdec($addrparts[7]);
9102 if (($addrend >= $start) and ($addrend <= $end)) {
9111 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9112 if ($ipstart === null) {
9115 $ipparts = explode('.', $ipstart);
9116 $ipparts[3] = trim($parts[1]);
9117 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
9118 if ($ipend === null) {
9122 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9128 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9129 if (strpos($subnet, ':') !== false) {
9134 $parts = explode(':', $subnet);
9135 $count = count($parts);
9136 if ($parts[$count-1] === '') {
9137 unset($parts[$count-1]); // Trim trailing :'s.
9139 $subnet = implode('.', $parts);
9141 $isip = cleanremoteaddr($subnet, false); // Normalise.
9142 if ($isip !== null) {
9143 if ($isip === $addr) {
9147 } else if ($count > 8) {
9150 $zeros = array_fill(0, 8-$count, '0');
9151 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9152 if (address_in_subnet($addr, $subnet)) {
9161 $parts = explode('.', $subnet);
9162 $count = count($parts);
9163 if ($parts[$count-1] === '') {
9164 unset($parts[$count-1]); // Trim trailing .
9166 $subnet = implode('.', $parts);
9169 $subnet = cleanremoteaddr($subnet, false); // Normalise.
9170 if ($subnet === $addr) {
9174 } else if ($count > 4) {
9177 $zeros = array_fill(0, 4-$count, '0');
9178 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9179 if (address_in_subnet($addr, $subnet)) {
9190 * For outputting debugging info
9192 * @param string $string The string to write
9193 * @param string $eol The end of line char(s) to use
9194 * @param string $sleep Period to make the application sleep
9195 * This ensures any messages have time to display before redirect
9197 function mtrace($string, $eol="\n", $sleep=0) {
9200 if (isset($CFG->mtrace_wrapper
) && function_exists($CFG->mtrace_wrapper
)) {
9201 $fn = $CFG->mtrace_wrapper
;
9204 } else if (defined('STDOUT') && !PHPUNIT_TEST
&& !defined('BEHAT_TEST')) {
9205 // We must explicitly call the add_line function here.
9206 // Uses of fwrite to STDOUT are not picked up by ob_start.
9207 if ($output = \core\task\logmanager
::add_line("{$string}{$eol}")) {
9208 fwrite(STDOUT
, $output);
9211 echo $string . $eol;
9217 // Delay to keep message on user's screen in case of subsequent redirect.
9224 * Replace 1 or more slashes or backslashes to 1 slash
9226 * @param string $path The path to strip
9227 * @return string the path with double slashes removed
9229 function cleardoubleslashes ($path) {
9230 return preg_replace('/(\/|\\\){1,}/', '/', $path);
9234 * Is the current ip in a given list?
9236 * @param string $list
9239 function remoteip_in_list($list) {
9240 $clientip = getremoteaddr(null);
9243 // Ensure access on cli.
9246 return \core\ip_utils
::is_ip_in_subnet_list($clientip, $list);
9250 * Returns most reliable client address
9252 * @param string $default If an address can't be determined, then return this
9253 * @return string The remote IP address
9255 function getremoteaddr($default='0.0.0.0') {
9258 if (!isset($CFG->getremoteaddrconf
)) {
9259 // This will happen, for example, before just after the upgrade, as the
9260 // user is redirected to the admin screen.
9261 $variablestoskip = GETREMOTEADDR_SKIP_DEFAULT
;
9263 $variablestoskip = $CFG->getremoteaddrconf
;
9265 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP
)) {
9266 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9267 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9268 return $address ?
$address : $default;
9271 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR
)) {
9272 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9273 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9275 $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
9277 return !\core\ip_utils
::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore ??
'', ',');
9280 // Multiple proxies can append values to this header including an
9281 // untrusted original request header so we must only trust the last ip.
9282 $address = end($forwardedaddresses);
9284 if (substr_count($address, ":") > 1) {
9285 // Remove port and brackets from IPv6.
9286 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9287 $address = $matches[1];
9290 // Remove port from IPv4.
9291 if (substr_count($address, ":") == 1) {
9292 $parts = explode(":", $address);
9293 $address = $parts[0];
9297 $address = cleanremoteaddr($address);
9298 return $address ?
$address : $default;
9301 if (!empty($_SERVER['REMOTE_ADDR'])) {
9302 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9303 return $address ?
$address : $default;
9310 * Cleans an ip address. Internal addresses are now allowed.
9311 * (Originally local addresses were not allowed.)
9313 * @param string $addr IPv4 or IPv6 address
9314 * @param bool $compress use IPv6 address compression
9315 * @return string normalised ip address string, null if error
9317 function cleanremoteaddr($addr, $compress=false) {
9318 $addr = trim($addr);
9320 if (strpos($addr, ':') !== false) {
9321 // Can be only IPv6.
9322 $parts = explode(':', $addr);
9323 $count = count($parts);
9325 if (strpos($parts[$count-1], '.') !== false) {
9326 // Legacy ipv4 notation.
9327 $last = array_pop($parts);
9328 $ipv4 = cleanremoteaddr($last, true);
9329 if ($ipv4 === null) {
9332 $bits = explode('.', $ipv4);
9333 $parts[] = dechex($bits[0]).dechex($bits[1]);
9334 $parts[] = dechex($bits[2]).dechex($bits[3]);
9335 $count = count($parts);
9336 $addr = implode(':', $parts);
9339 if ($count < 3 or $count > 8) {
9340 return null; // Severly malformed.
9344 if (strpos($addr, '::') === false) {
9345 return null; // Malformed.
9348 $insertat = array_search('', $parts, true);
9349 $missing = array_fill(0, 1 +
8 - $count, '0');
9350 array_splice($parts, $insertat, 1, $missing);
9351 foreach ($parts as $key => $part) {
9358 $adr = implode(':', $parts);
9359 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9360 return null; // Incorrect format - sorry.
9363 // Normalise 0s and case.
9364 $parts = array_map('hexdec', $parts);
9365 $parts = array_map('dechex', $parts);
9367 $result = implode(':', $parts);
9373 if ($result === '0:0:0:0:0:0:0:0') {
9374 return '::'; // All addresses.
9377 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9378 if ($compressed !== $result) {
9382 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9383 if ($compressed !== $result) {
9387 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9388 if ($compressed !== $result) {
9395 // First get all things that look like IPv4 addresses.
9397 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9402 foreach ($parts as $key => $match) {
9406 $parts[$key] = (int)$match; // Normalise 0s.
9409 return implode('.', $parts);
9414 * Is IP address a public address?
9416 * @param string $ip The ip to check
9417 * @return bool true if the ip is public
9419 function ip_is_public($ip) {
9420 return (bool) filter_var($ip, FILTER_VALIDATE_IP
, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
));
9424 * This function will make a complete copy of anything it's given,
9425 * regardless of whether it's an object or not.
9427 * @param mixed $thing Something you want cloned
9428 * @return mixed What ever it is you passed it
9430 function fullclone($thing) {
9431 return unserialize(serialize($thing));
9435 * Used to make sure that $min <= $value <= $max
9437 * Make sure that value is between min, and max
9439 * @param int $min The minimum value
9440 * @param int $value The value to check
9441 * @param int $max The maximum value
9444 function bounded_number($min, $value, $max) {
9445 if ($value < $min) {
9448 if ($value > $max) {
9455 * Check if there is a nested array within the passed array
9457 * @param array $array
9458 * @return bool true if there is a nested array false otherwise
9460 function array_is_nested($array) {
9461 foreach ($array as $value) {
9462 if (is_array($value)) {
9470 * get_performance_info() pairs up with init_performance_info()
9471 * loaded in setup.php. Returns an array with 'html' and 'txt'
9472 * values ready for use, and each of the individual stats provided
9473 * separately as well.
9477 function get_performance_info() {
9478 global $CFG, $PERF, $DB, $PAGE;
9481 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9484 if (!empty($CFG->themedesignermode
)) {
9485 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9486 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9488 $info['html'] .= '<ul class="list-unstyled row mx-md-0">'; // Holds userfriendly HTML representation.
9490 $info['realtime'] = microtime_diff($PERF->starttime
, microtime());
9492 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9493 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9495 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9496 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ??
"NULL") . ' ';
9498 if (function_exists('memory_get_usage')) {
9499 $info['memory_total'] = memory_get_usage();
9500 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory
;
9501 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9502 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9503 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9506 if (function_exists('memory_get_peak_usage')) {
9507 $info['memory_peak'] = memory_get_peak_usage();
9508 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9509 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9512 $info['html'] .= '</ul><ul class="list-unstyled row mx-md-0">';
9513 $inc = get_included_files();
9514 $info['includecount'] = count($inc);
9515 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9516 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9518 if (!empty($CFG->early_install_lang
) or empty($PAGE)) {
9519 // We can not track more performance before installation or before PAGE init, sorry.
9523 $filtermanager = filter_manager
::instance();
9524 if (method_exists($filtermanager, 'get_performance_summary')) {
9525 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9526 $info = array_merge($filterinfo, $info);
9527 foreach ($filterinfo as $key => $value) {
9528 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9529 $info['txt'] .= "$key: $value ";
9533 $stringmanager = get_string_manager();
9534 if (method_exists($stringmanager, 'get_performance_summary')) {
9535 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9536 $info = array_merge($filterinfo, $info);
9537 foreach ($filterinfo as $key => $value) {
9538 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9539 $info['txt'] .= "$key: $value ";
9543 if (!empty($PERF->logwrites
)) {
9544 $info['logwrites'] = $PERF->logwrites
;
9545 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9546 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9549 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites
);
9550 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9551 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9553 if ($DB->want_read_slave()) {
9554 $info['dbreads_slave'] = $DB->perf_get_reads_slave();
9555 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads from slave: '.$info['dbreads_slave'].'</li> ';
9556 $info['txt'] .= 'db reads from slave: '.$info['dbreads_slave'].' ';
9559 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9560 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9561 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9563 if (function_exists('posix_times')) {
9564 $ptimes = posix_times();
9565 if (is_array($ptimes)) {
9566 foreach ($ptimes as $key => $val) {
9567 $info[$key] = $ptimes[$key] - $PERF->startposixtimes
[$key];
9569 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9570 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9571 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9575 // Grab the load average for the last minute.
9576 // /proc will only work under some linux configurations
9577 // while uptime is there under MacOSX/Darwin and other unices.
9578 if (is_readable('/proc/loadavg') && $loadavg = @file
('/proc/loadavg')) {
9579 list($serverload) = explode(' ', $loadavg[0]);
9581 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `
/usr
/bin
/uptime`
) {
9582 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9583 $serverload = $matches[1];
9585 trigger_error('Could not parse uptime output!');
9588 if (!empty($serverload)) {
9589 $info['serverload'] = $serverload;
9590 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9591 $info['txt'] .= "serverload: {$info['serverload']} ";
9594 // Display size of session if session started.
9595 if ($si = \core\session\manager
::get_performance_info()) {
9596 $info['sessionsize'] = $si['size'];
9597 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9598 $info['txt'] .= $si['txt'];
9601 $info['html'] .= '</ul>';
9603 if ($stats = cache_helper
::get_stats()) {
9605 $table = new html_table();
9606 $table->attributes
['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9607 $table->head
= ['Mode', 'Cache item', 'Static', 'H', 'M', get_string('mappingprimary', 'cache'), 'H', 'M', 'S', 'I/O'];
9609 $table->align
= ['left', 'left', 'left', 'right', 'right', 'left', 'right', 'right', 'right', 'right'];
9611 $text = 'Caches used (hits/misses/sets): ';
9617 // We want to align static caches into their own column.
9619 foreach ($stats as $definition => $details) {
9620 $numstores = count($details['stores']);
9621 $first = key($details['stores']);
9622 if ($first !== cache_store
::STATIC_ACCEL
) {
9623 $numstores++
; // Add a blank space for the missing static store.
9625 $maxstores = max($maxstores, $numstores);
9630 while ($storec++
< ($maxstores - 2)) {
9631 if ($storec == ($maxstores - 2)) {
9632 $table->head
[] = get_string('mappingfinal', 'cache');
9634 $table->head
[] = "Store $storec";
9636 $table->align
[] = 'left';
9637 $table->align
[] = 'right';
9638 $table->align
[] = 'right';
9639 $table->align
[] = 'right';
9640 $table->align
[] = 'right';
9641 $table->head
[] = 'H';
9642 $table->head
[] = 'M';
9643 $table->head
[] = 'S';
9644 $table->head
[] = 'I/O';
9649 foreach ($stats as $definition => $details) {
9650 switch ($details['mode']) {
9651 case cache_store
::MODE_APPLICATION
:
9652 $modeclass = 'application';
9653 $mode = ' <span title="application cache">App</span>';
9655 case cache_store
::MODE_SESSION
:
9656 $modeclass = 'session';
9657 $mode = ' <span title="session cache">Ses</span>';
9659 case cache_store
::MODE_REQUEST
:
9660 $modeclass = 'request';
9661 $mode = ' <span title="request cache">Req</span>';
9664 $row = [$mode, $definition];
9666 $text .= "$definition {";
9669 foreach ($details['stores'] as $store => $data) {
9671 if ($storec == 0 && $store !== cache_store
::STATIC_ACCEL
) {
9678 $hits +
= $data['hits'];
9679 $misses +
= $data['misses'];
9680 $sets +
= $data['sets'];
9681 if ($data['hits'] == 0 and $data['misses'] > 0) {
9682 $cachestoreclass = 'nohits bg-danger';
9683 } else if ($data['hits'] < $data['misses']) {
9684 $cachestoreclass = 'lowhits bg-warning text-dark';
9686 $cachestoreclass = 'hihits';
9688 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9689 $cell = new html_table_cell($store);
9690 $cell->attributes
= ['class' => $cachestoreclass];
9692 $cell = new html_table_cell($data['hits']);
9693 $cell->attributes
= ['class' => $cachestoreclass];
9695 $cell = new html_table_cell($data['misses']);
9696 $cell->attributes
= ['class' => $cachestoreclass];
9699 if ($store !== cache_store
::STATIC_ACCEL
) {
9700 // The static cache is never set.
9701 $cell = new html_table_cell($data['sets']);
9702 $cell->attributes
= ['class' => $cachestoreclass];
9705 if ($data['hits'] ||
$data['sets']) {
9706 if ($data['iobytes'] === cache_store
::IO_BYTES_NOT_SUPPORTED
) {
9709 $size = display_size($data['iobytes'], 1, 'KB');
9710 if ($data['iobytes'] >= 10 * 1024) {
9711 $cachestoreclass = ' bg-warning text-dark';
9717 $cell = new html_table_cell($size);
9718 $cell->attributes
= ['class' => $cachestoreclass];
9723 while ($storec++
< $maxstores) {
9732 $table->data
[] = $row;
9735 $html .= html_writer
::table($table);
9737 // Now lets also show sub totals for each cache store.
9739 $storetotal = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9740 foreach ($stats as $definition => $details) {
9741 foreach ($details['stores'] as $store => $data) {
9742 if (!array_key_exists($store, $storetotals)) {
9743 $storetotals[$store] = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9745 $storetotals[$store]['class'] = $data['class'];
9746 $storetotals[$store]['hits'] +
= $data['hits'];
9747 $storetotals[$store]['misses'] +
= $data['misses'];
9748 $storetotals[$store]['sets'] +
= $data['sets'];
9749 $storetotal['hits'] +
= $data['hits'];
9750 $storetotal['misses'] +
= $data['misses'];
9751 $storetotal['sets'] +
= $data['sets'];
9752 if ($data['iobytes'] !== cache_store
::IO_BYTES_NOT_SUPPORTED
) {
9753 $storetotals[$store]['iobytes'] +
= $data['iobytes'];
9754 $storetotal['iobytes'] +
= $data['iobytes'];
9759 $table = new html_table();
9760 $table->attributes
['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9761 $table->head
= [get_string('storename', 'cache'), get_string('type_cachestore', 'plugin'), 'H', 'M', 'S', 'I/O'];
9763 $table->align
= ['left', 'left', 'right', 'right', 'right', 'right'];
9765 ksort($storetotals);
9767 foreach ($storetotals as $store => $data) {
9769 if ($data['hits'] == 0 and $data['misses'] > 0) {
9770 $cachestoreclass = 'nohits bg-danger';
9771 } else if ($data['hits'] < $data['misses']) {
9772 $cachestoreclass = 'lowhits bg-warning text-dark';
9774 $cachestoreclass = 'hihits';
9776 $cell = new html_table_cell($store);
9777 $cell->attributes
= ['class' => $cachestoreclass];
9779 $cell = new html_table_cell($data['class']);
9780 $cell->attributes
= ['class' => $cachestoreclass];
9782 $cell = new html_table_cell($data['hits']);
9783 $cell->attributes
= ['class' => $cachestoreclass];
9785 $cell = new html_table_cell($data['misses']);
9786 $cell->attributes
= ['class' => $cachestoreclass];
9788 $cell = new html_table_cell($data['sets']);
9789 $cell->attributes
= ['class' => $cachestoreclass];
9791 if ($data['hits'] ||
$data['sets']) {
9792 if ($data['iobytes']) {
9793 $size = display_size($data['iobytes'], 1, 'KB');
9800 $cell = new html_table_cell($size);
9801 $cell->attributes
= ['class' => $cachestoreclass];
9803 $table->data
[] = $row;
9805 if (!empty($storetotal['iobytes'])) {
9806 $size = display_size($storetotal['iobytes'], 1, 'KB');
9807 } else if (!empty($storetotal['hits']) ||
!empty($storetotal['sets'])) {
9813 get_string('total'),
9815 $storetotal['hits'],
9816 $storetotal['misses'],
9817 $storetotal['sets'],
9820 $table->data
[] = $row;
9822 $html .= html_writer
::table($table);
9824 $info['cachesused'] = "$hits / $misses / $sets";
9825 $info['html'] .= $html;
9826 $info['txt'] .= $text.'. ';
9828 $info['cachesused'] = '0 / 0 / 0';
9829 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9830 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9833 $info['html'] = '<div class="performanceinfo siteinfo container-fluid px-md-0 overflow-auto mt-3">'.$info['html'].'</div>';
9838 * Renames a file or directory to a unique name within the same directory.
9840 * This function is designed to avoid any potential race conditions, and select an unused name.
9842 * @param string $filepath Original filepath
9843 * @param string $prefix Prefix to use for the temporary name
9844 * @return string|bool New file path or false if failed
9845 * @since Moodle 3.10
9847 function rename_to_unused_name(string $filepath, string $prefix = '_temp_') {
9848 $dir = dirname($filepath);
9849 $basename = $dir . '/' . $prefix;
9851 while ($limit < 100) {
9852 // Select a new name based on a random number.
9853 $newfilepath = $basename . md5(mt_rand());
9855 // Attempt a rename to that new name.
9856 if (@rename
($filepath, $newfilepath)) {
9857 return $newfilepath;
9860 // The first time, do some sanity checks, maybe it is failing for a good reason and there
9861 // is no point trying 100 times if so.
9862 if ($limit === 0 && (!file_exists($filepath) ||
!is_writable($dir))) {
9871 * Delete directory or only its content
9873 * @param string $dir directory path
9874 * @param bool $contentonly
9875 * @return bool success, true also if dir does not exist
9877 function remove_dir($dir, $contentonly=false) {
9878 if (!is_dir($dir)) {
9883 if (!$contentonly) {
9884 // Start by renaming the directory; this will guarantee that other processes don't write to it
9885 // while it is in the process of being deleted.
9886 $tempdir = rename_to_unused_name($dir);
9888 // If the rename was successful then delete the $tempdir instead.
9891 // If the rename fails, we will continue through and attempt to delete the directory
9892 // without renaming it since that is likely to at least delete most of the files.
9895 if (!$handle = opendir($dir)) {
9899 while (false!==($item = readdir($handle))) {
9900 if ($item != '.' && $item != '..') {
9901 if (is_dir($dir.'/'.$item)) {
9902 $result = remove_dir($dir.'/'.$item) && $result;
9904 $result = unlink($dir.'/'.$item) && $result;
9910 clearstatcache(); // Make sure file stat cache is properly invalidated.
9913 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9914 clearstatcache(); // Make sure file stat cache is properly invalidated.
9919 * Detect if an object or a class contains a given property
9920 * will take an actual object or the name of a class
9922 * @param mix $obj Name of class or real object to test
9923 * @param string $property name of property to find
9924 * @return bool true if property exists
9926 function object_property_exists( $obj, $property ) {
9927 if (is_string( $obj )) {
9928 $properties = get_class_vars( $obj );
9930 $properties = get_object_vars( $obj );
9932 return array_key_exists( $property, $properties );
9936 * Converts an object into an associative array
9938 * This function converts an object into an associative array by iterating
9939 * over its public properties. Because this function uses the foreach
9940 * construct, Iterators are respected. It works recursively on arrays of objects.
9941 * Arrays and simple values are returned as is.
9943 * If class has magic properties, it can implement IteratorAggregate
9944 * and return all available properties in getIterator()
9949 function convert_to_array($var) {
9952 // Loop over elements/properties.
9953 foreach ($var as $key => $value) {
9954 // Recursively convert objects.
9955 if (is_object($value) ||
is_array($value)) {
9956 $result[$key] = convert_to_array($value);
9958 // Simple values are untouched.
9959 $result[$key] = $value;
9966 * Detect a custom script replacement in the data directory that will
9967 * replace an existing moodle script
9969 * @return string|bool full path name if a custom script exists, false if no custom script exists
9971 function custom_script_path() {
9972 global $CFG, $SCRIPT;
9974 if ($SCRIPT === null) {
9975 // Probably some weird external script.
9979 $scriptpath = $CFG->customscripts
. $SCRIPT;
9981 // Check the custom script exists.
9982 if (file_exists($scriptpath) and is_file($scriptpath)) {
9990 * Returns whether or not the user object is a remote MNET user. This function
9991 * is in moodlelib because it does not rely on loading any of the MNET code.
9993 * @param object $user A valid user object
9994 * @return bool True if the user is from a remote Moodle.
9996 function is_mnet_remote_user($user) {
9999 if (!isset($CFG->mnet_localhost_id
)) {
10000 include_once($CFG->dirroot
. '/mnet/lib.php');
10001 $env = new mnet_environment();
10006 return (!empty($user->mnethostid
) && $user->mnethostid
!= $CFG->mnet_localhost_id
);
10010 * This function will search for browser prefereed languages, setting Moodle
10011 * to use the best one available if $SESSION->lang is undefined
10013 function setup_lang_from_browser() {
10014 global $CFG, $SESSION, $USER;
10016 if (!empty($SESSION->lang
) or !empty($USER->lang
) or empty($CFG->autolang
)) {
10017 // Lang is defined in session or user profile, nothing to do.
10021 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
10025 // Extract and clean langs from headers.
10026 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
10027 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
10028 $rawlangs = explode(',', $rawlangs); // Convert to array.
10032 foreach ($rawlangs as $lang) {
10033 if (strpos($lang, ';') === false) {
10034 $langs[(string)$order] = $lang;
10035 $order = $order-0.01;
10037 $parts = explode(';', $lang);
10038 $pos = strpos($parts[1], '=');
10039 $langs[substr($parts[1], $pos+
1)] = $parts[0];
10042 krsort($langs, SORT_NUMERIC
);
10044 // Look for such langs under standard locations.
10045 foreach ($langs as $lang) {
10046 // Clean it properly for include.
10047 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR
));
10048 if (get_string_manager()->translation_exists($lang, false)) {
10049 // Lang exists, set it in session.
10050 $SESSION->lang
= $lang;
10051 // We have finished. Go out.
10059 * Check if $url matches anything in proxybypass list
10061 * Any errors just result in the proxy being used (least bad)
10063 * @param string $url url to check
10064 * @return boolean true if we should bypass the proxy
10066 function is_proxybypass( $url ) {
10070 if (empty($CFG->proxyhost
) or empty($CFG->proxybypass
)) {
10074 // Get the host part out of the url.
10075 if (!$host = parse_url( $url, PHP_URL_HOST
)) {
10079 // Get the possible bypass hosts into an array.
10080 $matches = explode( ',', $CFG->proxybypass
);
10082 // Check for a match.
10083 // (IPs need to match the left hand side and hosts the right of the url,
10084 // but we can recklessly check both as there can't be a false +ve).
10085 foreach ($matches as $match) {
10086 $match = trim($match);
10088 // Try for IP match (Left side).
10089 $lhs = substr($host, 0, strlen($match));
10090 if (strcasecmp($match, $lhs)==0) {
10094 // Try for host match (Right side).
10095 $rhs = substr($host, -strlen($match));
10096 if (strcasecmp($match, $rhs)==0) {
10101 // Nothing matched.
10106 * Check if the passed navigation is of the new style
10108 * @param mixed $navigation
10109 * @return bool true for yes false for no
10111 function is_newnav($navigation) {
10112 if (is_array($navigation) && !empty($navigation['newnav'])) {
10120 * Checks whether the given variable name is defined as a variable within the given object.
10122 * This will NOT work with stdClass objects, which have no class variables.
10124 * @param string $var The variable name
10125 * @param object $object The object to check
10128 function in_object_vars($var, $object) {
10129 $classvars = get_class_vars(get_class($object));
10130 $classvars = array_keys($classvars);
10131 return in_array($var, $classvars);
10135 * Returns an array without repeated objects.
10136 * This function is similar to array_unique, but for arrays that have objects as values
10138 * @param array $array
10139 * @param bool $keepkeyassoc
10142 function object_array_unique($array, $keepkeyassoc = true) {
10143 $duplicatekeys = array();
10146 foreach ($array as $key => $val) {
10147 // Convert objects to arrays, in_array() does not support objects.
10148 if (is_object($val)) {
10149 $val = (array)$val;
10152 if (!in_array($val, $tmp)) {
10155 $duplicatekeys[] = $key;
10159 foreach ($duplicatekeys as $key) {
10160 unset($array[$key]);
10163 return $keepkeyassoc ?
$array : array_values($array);
10167 * Is a userid the primary administrator?
10169 * @param int $userid int id of user to check
10172 function is_primary_admin($userid) {
10173 $primaryadmin = get_admin();
10175 if ($userid == $primaryadmin->id
) {
10183 * Returns the site identifier
10185 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
10187 function get_site_identifier() {
10189 // Check to see if it is missing. If so, initialise it.
10190 if (empty($CFG->siteidentifier
)) {
10191 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
10194 return $CFG->siteidentifier
;
10198 * Check whether the given password has no more than the specified
10199 * number of consecutive identical characters.
10201 * @param string $password password to be checked against the password policy
10202 * @param integer $maxchars maximum number of consecutive identical characters
10205 function check_consecutive_identical_characters($password, $maxchars) {
10207 if ($maxchars < 1) {
10208 return true; // Zero 0 is to disable this check.
10210 if (strlen($password) <= $maxchars) {
10211 return true; // Too short to fail this test.
10214 $previouschar = '';
10215 $consecutivecount = 1;
10216 foreach (str_split($password) as $char) {
10217 if ($char != $previouschar) {
10218 $consecutivecount = 1;
10220 $consecutivecount++
;
10221 if ($consecutivecount > $maxchars) {
10222 return false; // Check failed already.
10226 $previouschar = $char;
10233 * Helper function to do partial function binding.
10234 * so we can use it for preg_replace_callback, for example
10235 * this works with php functions, user functions, static methods and class methods
10236 * it returns you a callback that you can pass on like so:
10238 * $callback = partial('somefunction', $arg1, $arg2);
10240 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
10242 * $obj = new someclass();
10243 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
10245 * and then the arguments that are passed through at calltime are appended to the argument list.
10247 * @param mixed $function a php callback
10248 * @param mixed $arg1,... $argv arguments to partially bind with
10249 * @return array Array callback
10251 function partial() {
10252 if (!class_exists('partial')) {
10254 * Used to manage function binding.
10255 * @copyright 2009 Penny Leach
10256 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10260 public $values = array();
10261 /** @var string The function to call as a callback. */
10265 * @param string $func
10266 * @param array $args
10268 public function __construct($func, $args) {
10269 $this->values
= $args;
10270 $this->func
= $func;
10273 * Calls the callback function.
10276 public function method() {
10277 $args = func_get_args();
10278 return call_user_func_array($this->func
, array_merge($this->values
, $args));
10282 $args = func_get_args();
10283 $func = array_shift($args);
10284 $p = new partial($func, $args);
10285 return array($p, 'method');
10289 * helper function to load up and initialise the mnet environment
10290 * this must be called before you use mnet functions.
10292 * @return mnet_environment the equivalent of old $MNET global
10294 function get_mnet_environment() {
10296 require_once($CFG->dirroot
. '/mnet/lib.php');
10297 static $instance = null;
10298 if (empty($instance)) {
10299 $instance = new mnet_environment();
10306 * during xmlrpc server code execution, any code wishing to access
10307 * information about the remote peer must use this to get it.
10309 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
10311 function get_mnet_remote_client() {
10312 if (!defined('MNET_SERVER')) {
10313 debugging(get_string('notinxmlrpcserver', 'mnet'));
10316 global $MNET_REMOTE_CLIENT;
10317 if (isset($MNET_REMOTE_CLIENT)) {
10318 return $MNET_REMOTE_CLIENT;
10324 * during the xmlrpc server code execution, this will be called
10325 * to setup the object returned by {@link get_mnet_remote_client}
10327 * @param mnet_remote_client $client the client to set up
10328 * @throws moodle_exception
10330 function set_mnet_remote_client($client) {
10331 if (!defined('MNET_SERVER')) {
10332 throw new moodle_exception('notinxmlrpcserver', 'mnet');
10334 global $MNET_REMOTE_CLIENT;
10335 $MNET_REMOTE_CLIENT = $client;
10339 * return the jump url for a given remote user
10340 * this is used for rewriting forum post links in emails, etc
10342 * @param stdclass $user the user to get the idp url for
10344 function mnet_get_idp_jump_url($user) {
10347 static $mnetjumps = array();
10348 if (!array_key_exists($user->mnethostid
, $mnetjumps)) {
10349 $idp = mnet_get_peer_host($user->mnethostid
);
10350 $idpjumppath = mnet_get_app_jumppath($idp->applicationid
);
10351 $mnetjumps[$user->mnethostid
] = $idp->wwwroot
. $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot
. '&wantsurl=';
10353 return $mnetjumps[$user->mnethostid
];
10357 * Gets the homepage to use for the current user
10359 * @return int One of HOMEPAGE_*
10361 function get_home_page() {
10364 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage
)) {
10365 if ($CFG->defaulthomepage
== HOMEPAGE_MY
) {
10366 return HOMEPAGE_MY
;
10367 } else if ($CFG->defaulthomepage
== HOMEPAGE_MYCOURSES
) {
10368 return HOMEPAGE_MYCOURSES
;
10370 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY
);
10373 return HOMEPAGE_SITE
;
10377 * Gets the name of a course to be displayed when showing a list of courses.
10378 * By default this is just $course->fullname but user can configure it. The
10379 * result of this function should be passed through print_string.
10380 * @param stdClass|core_course_list_element $course Moodle course object
10381 * @return string Display name of course (either fullname or short + fullname)
10383 function get_course_display_name_for_list($course) {
10385 if (!empty($CFG->courselistshortnames
)) {
10386 if (!($course instanceof stdClass
)) {
10387 $course = (object)convert_to_array($course);
10389 return get_string('courseextendednamedisplay', '', $course);
10391 return $course->fullname
;
10396 * Safe analogue of unserialize() that can only parse arrays
10398 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
10399 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
10400 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
10402 * @param string $expression
10403 * @return array|bool either parsed array or false if parsing was impossible.
10405 function unserialize_array($expression) {
10407 // Find nested arrays, parse them and store in $subs , substitute with special string.
10408 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
10409 $key = '--SUB' . count($subs) . '--';
10410 $subs[$key] = unserialize_array($matches[2]);
10411 if ($subs[$key] === false) {
10414 $expression = str_replace($matches[2], $key . ';', $expression);
10417 // Check the expression is an array.
10418 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
10421 // Get the size and elements of an array (key;value;key;value;....).
10422 $parts = explode(';', $matches1[2]);
10423 $size = intval($matches1[1]);
10424 if (count($parts) < $size * 2 +
1) {
10427 // Analyze each part and make sure it is an integer or string or a substitute.
10429 for ($i = 0; $i < $size * 2; $i++
) {
10430 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
10431 $parts[$i] = (int)$matches2[1];
10432 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
10433 $parts[$i] = $matches3[2];
10434 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
10435 $parts[$i] = $subs[$parts[$i]];
10440 // Combine keys and values.
10441 for ($i = 0; $i < $size * 2; $i +
= 2) {
10442 $value[$parts[$i]] = $parts[$i+
1];
10448 * Safe method for unserializing given input that is expected to contain only a serialized instance of an stdClass object
10450 * If any class type other than stdClass is included in the input string, it will not be instantiated and will be cast to an
10451 * stdClass object. The initial cast to array, then back to object is to ensure we are always returning the correct type,
10452 * otherwise we would return an instances of {@see __PHP_Incomplete_class} for malformed strings
10454 * @param string $input
10457 function unserialize_object(string $input): stdClass
{
10458 $instance = (array) unserialize($input, ['allowed_classes' => [stdClass
::class]]);
10459 return (object) $instance;
10463 * The lang_string class
10465 * This special class is used to create an object representation of a string request.
10466 * It is special because processing doesn't occur until the object is first used.
10467 * The class was created especially to aid performance in areas where strings were
10468 * required to be generated but were not necessarily used.
10469 * As an example the admin tree when generated uses over 1500 strings, of which
10470 * normally only 1/3 are ever actually printed at any time.
10471 * The performance advantage is achieved by not actually processing strings that
10472 * arn't being used, as such reducing the processing required for the page.
10474 * How to use the lang_string class?
10475 * There are two methods of using the lang_string class, first through the
10476 * forth argument of the get_string function, and secondly directly.
10477 * The following are examples of both.
10478 * 1. Through get_string calls e.g.
10479 * $string = get_string($identifier, $component, $a, true);
10480 * $string = get_string('yes', 'moodle', null, true);
10481 * 2. Direct instantiation
10482 * $string = new lang_string($identifier, $component, $a, $lang);
10483 * $string = new lang_string('yes');
10485 * How do I use a lang_string object?
10486 * The lang_string object makes use of a magic __toString method so that you
10487 * are able to use the object exactly as you would use a string in most cases.
10488 * This means you are able to collect it into a variable and then directly
10489 * echo it, or concatenate it into another string, or similar.
10490 * The other thing you can do is manually get the string by calling the
10491 * lang_strings out method e.g.
10492 * $string = new lang_string('yes');
10494 * Also worth noting is that the out method can take one argument, $lang which
10495 * allows the developer to change the language on the fly.
10497 * When should I use a lang_string object?
10498 * The lang_string object is designed to be used in any situation where a
10499 * string may not be needed, but needs to be generated.
10500 * The admin tree is a good example of where lang_string objects should be
10502 * A more practical example would be any class that requries strings that may
10503 * not be printed (after all classes get renderer by renderers and who knows
10504 * what they will do ;))
10506 * When should I not use a lang_string object?
10507 * Don't use lang_strings when you are going to use a string immediately.
10508 * There is no need as it will be processed immediately and there will be no
10509 * advantage, and in fact perhaps a negative hit as a class has to be
10510 * instantiated for a lang_string object, however get_string won't require
10514 * 1. You cannot use a lang_string object as an array offset. Doing so will
10515 * result in PHP throwing an error. (You can use it as an object property!)
10519 * @copyright 2011 Sam Hemelryk
10520 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10522 class lang_string
{
10524 /** @var string The strings identifier */
10525 protected $identifier;
10526 /** @var string The strings component. Default '' */
10527 protected $component = '';
10528 /** @var array|stdClass Any arguments required for the string. Default null */
10529 protected $a = null;
10530 /** @var string The language to use when processing the string. Default null */
10531 protected $lang = null;
10533 /** @var string The processed string (once processed) */
10534 protected $string = null;
10537 * A special boolean. If set to true then the object has been woken up and
10538 * cannot be regenerated. If this is set then $this->string MUST be used.
10541 protected $forcedstring = false;
10544 * Constructs a lang_string object
10546 * This function should do as little processing as possible to ensure the best
10547 * performance for strings that won't be used.
10549 * @param string $identifier The strings identifier
10550 * @param string $component The strings component
10551 * @param stdClass|array $a Any arguments the string requires
10552 * @param string $lang The language to use when processing the string.
10553 * @throws coding_exception
10555 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10556 if (empty($component)) {
10557 $component = 'moodle';
10560 $this->identifier
= $identifier;
10561 $this->component
= $component;
10562 $this->lang
= $lang;
10564 // We MUST duplicate $a to ensure that it if it changes by reference those
10565 // changes are not carried across.
10566 // To do this we always ensure $a or its properties/values are strings
10567 // and that any properties/values that arn't convertable are forgotten.
10569 if (is_scalar($a)) {
10571 } else if ($a instanceof lang_string
) {
10572 $this->a
= $a->out();
10573 } else if (is_object($a) or is_array($a)) {
10575 $this->a
= array();
10576 foreach ($a as $key => $value) {
10577 // Make sure conversion errors don't get displayed (results in '').
10578 if (is_array($value)) {
10579 $this->a
[$key] = '';
10580 } else if (is_object($value)) {
10581 if (method_exists($value, '__toString')) {
10582 $this->a
[$key] = $value->__toString();
10584 $this->a
[$key] = '';
10587 $this->a
[$key] = (string)$value;
10593 if (debugging(false, DEBUG_DEVELOPER
)) {
10594 if (clean_param($this->identifier
, PARAM_STRINGID
) == '') {
10595 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10597 if (!empty($this->component
) && clean_param($this->component
, PARAM_COMPONENT
) == '') {
10598 throw new coding_exception('Invalid string compontent. Please check your string definition');
10600 if (!get_string_manager()->string_exists($this->identifier
, $this->component
)) {
10601 debugging('String does not exist. Please check your string definition for '.$this->identifier
.'/'.$this->component
, DEBUG_DEVELOPER
);
10607 * Processes the string.
10609 * This function actually processes the string, stores it in the string property
10610 * and then returns it.
10611 * You will notice that this function is VERY similar to the get_string method.
10612 * That is because it is pretty much doing the same thing.
10613 * However as this function is an upgrade it isn't as tolerant to backwards
10617 * @throws coding_exception
10619 protected function get_string() {
10622 // Check if we need to process the string.
10623 if ($this->string === null) {
10624 // Check the quality of the identifier.
10625 if ($CFG->debugdeveloper
&& clean_param($this->identifier
, PARAM_STRINGID
) === '') {
10626 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
);
10629 // Process the string.
10630 $this->string = get_string_manager()->get_string($this->identifier
, $this->component
, $this->a
, $this->lang
);
10631 // Debugging feature lets you display string identifier and component.
10632 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
10633 $this->string .= ' {' . $this->identifier
. '/' . $this->component
. '}';
10636 // Return the string.
10637 return $this->string;
10641 * Returns the string
10643 * @param string $lang The langauge to use when processing the string
10646 public function out($lang = null) {
10647 if ($lang !== null && $lang != $this->lang
&& ($this->lang
== null && $lang != current_language())) {
10648 if ($this->forcedstring
) {
10649 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang
.' used)', DEBUG_DEVELOPER
);
10650 return $this->get_string();
10652 $translatedstring = new lang_string($this->identifier
, $this->component
, $this->a
, $lang);
10653 return $translatedstring->out();
10655 return $this->get_string();
10659 * Magic __toString method for printing a string
10663 public function __toString() {
10664 return $this->get_string();
10668 * Magic __set_state method used for var_export
10670 * @param array $array
10673 public static function __set_state(array $array): self
{
10674 $tmp = new lang_string($array['identifier'], $array['component'], $array['a'], $array['lang']);
10675 $tmp->string = $array['string'];
10676 $tmp->forcedstring
= $array['forcedstring'];
10681 * Prepares the lang_string for sleep and stores only the forcedstring and
10682 * string properties... the string cannot be regenerated so we need to ensure
10683 * it is generated for this.
10687 public function __sleep() {
10688 $this->get_string();
10689 $this->forcedstring
= true;
10690 return array('forcedstring', 'string', 'lang');
10694 * Returns the identifier.
10698 public function get_identifier() {
10699 return $this->identifier
;
10703 * Returns the component.
10707 public function get_component() {
10708 return $this->component
;
10713 * Get human readable name describing the given callable.
10715 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10716 * It does not check if the callable actually exists.
10718 * @param callable|string|array $callable
10719 * @return string|bool Human readable name of callable, or false if not a valid callable.
10721 function get_callable_name($callable) {
10723 if (!is_callable($callable, true, $name)) {
10732 * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10733 * Never put your faith on this function and rely on its accuracy as there might be false positives.
10734 * It just performs some simple checks, and mainly is used for places where we want to hide some options
10735 * such as site registration when $CFG->wwwroot is not publicly accessible.
10736 * Good thing is there is no false negative.
10737 * Note that it's possible to force the result of this check by specifying $CFG->site_is_public in config.php
10741 function site_is_public() {
10744 // Return early if site admin has forced this setting.
10745 if (isset($CFG->site_is_public
)) {
10746 return (bool)$CFG->site_is_public
;
10749 $host = parse_url($CFG->wwwroot
, PHP_URL_HOST
);
10751 if ($host === 'localhost' ||
preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10753 } else if (\core\ip_utils
::is_ip_address($host) && !ip_is_public($host)) {
10755 } else if (($address = \core\ip_utils
::get_ip_address($host)) && !ip_is_public($address)) {