Merge branch 'MDL-73990-master' of https://github.com/sharidas/moodle
[moodle.git] / lib / moodlelib.php
blobee60a46c6e363dd233adb7d2066ae67bb483d132
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * moodlelib.php - Moodle main library
20 * Main library file of miscellaneous general-purpose Moodle functions.
21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - datalib.php - functions that access the database
25 * @package core
26 * @subpackage lib
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') || die();
33 // CONSTANTS (Encased in phpdoc proper comments).
35 // Date and time constants.
36 /**
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
41 /**
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
46 /**
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
51 /**
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
56 /**
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
61 /**
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
66 /**
67 * Time constant - the number of minutes in an hour
69 define('HOURMINS', 60);
71 // Parameter constants - every call to optional_param(), required_param()
72 // or clean_param() should have a specified type of parameter.
74 /**
75 * PARAM_ALPHA - contains only English ascii letters [a-zA-Z].
77 define('PARAM_ALPHA', 'alpha');
79 /**
80 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA (English ascii letters [a-zA-Z]) plus the chars in quotes: "_-" allowed
81 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
83 define('PARAM_ALPHAEXT', 'alphaext');
85 /**
86 * PARAM_ALPHANUM - expected numbers 0-9 and English ascii letters [a-zA-Z] only.
88 define('PARAM_ALPHANUM', 'alphanum');
90 /**
91 * PARAM_ALPHANUMEXT - expected numbers 0-9, letters (English ascii letters [a-zA-Z]) and _- only.
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
95 /**
96 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
98 define('PARAM_AUTH', 'auth');
101 * PARAM_BASE64 - Base 64 encoded format
103 define('PARAM_BASE64', 'base64');
106 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
108 define('PARAM_BOOL', 'bool');
111 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
112 * checked against the list of capabilities in the database.
114 define('PARAM_CAPABILITY', 'capability');
117 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118 * to use this. The normal mode of operation is to use PARAM_RAW when receiving
119 * the input (required/optional_param or formslib) and then sanitise the HTML
120 * using format_text on output. This is for the rare cases when you want to
121 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
123 define('PARAM_CLEANHTML', 'cleanhtml');
126 * PARAM_EMAIL - an email address following the RFC
128 define('PARAM_EMAIL', 'email');
131 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
133 define('PARAM_FILE', 'file');
136 * PARAM_FLOAT - a real/floating point number.
138 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
139 * It does not work for languages that use , as a decimal separator.
140 * Use PARAM_LOCALISEDFLOAT instead.
142 define('PARAM_FLOAT', 'float');
145 * PARAM_LOCALISEDFLOAT - a localised real/floating point number.
146 * This is preferred over PARAM_FLOAT for numbers typed in by the user.
147 * Cleans localised numbers to computer readable numbers; false for invalid numbers.
149 define('PARAM_LOCALISEDFLOAT', 'localisedfloat');
152 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
154 define('PARAM_HOST', 'host');
157 * PARAM_INT - integers only, use when expecting only numbers.
159 define('PARAM_INT', 'int');
162 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
164 define('PARAM_LANG', 'lang');
167 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
168 * others! Implies PARAM_URL!)
170 define('PARAM_LOCALURL', 'localurl');
173 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
175 define('PARAM_NOTAGS', 'notags');
178 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
179 * traversals note: the leading slash is not removed, window drive letter is not allowed
181 define('PARAM_PATH', 'path');
184 * PARAM_PEM - Privacy Enhanced Mail format
186 define('PARAM_PEM', 'pem');
189 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
191 define('PARAM_PERMISSION', 'permission');
194 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
196 define('PARAM_RAW', 'raw');
199 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
201 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
204 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
206 define('PARAM_SAFEDIR', 'safedir');
209 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, 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');
330 // Web Services.
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);
357 // Page types.
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);
381 // Tag constants.
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 * URL of the statistic server public key.
522 defined('HUB_STATSPUBLICKEY') || define('HUB_STATSPUBLICKEY', 'https://moodle.org/static/statspubkey.pem');
525 * Moodle mobile app service name
527 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
530 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
532 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
535 * Course display settings: display all sections on one page.
537 define('COURSE_DISPLAY_SINGLEPAGE', 0);
539 * Course display settings: split pages into a page per section.
541 define('COURSE_DISPLAY_MULTIPAGE', 1);
544 * Authentication constant: String used in password field when password is not stored.
546 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
549 * Email from header to never include via information.
551 define('EMAIL_VIA_NEVER', 0);
554 * Email from header to always include via information.
556 define('EMAIL_VIA_ALWAYS', 1);
559 * Email from header to only include via information if the address is no-reply.
561 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
563 // PARAMETER HANDLING.
566 * Returns a particular value for the named variable, taken from
567 * POST or GET. If the parameter doesn't exist then an error is
568 * thrown because we require this variable.
570 * This function should be used to initialise all required values
571 * in a script that are based on parameters. Usually it will be
572 * used like this:
573 * $id = required_param('id', PARAM_INT);
575 * Please note the $type parameter is now required and the value can not be array.
577 * @param string $parname the name of the page parameter we want
578 * @param string $type expected type of parameter
579 * @return mixed
580 * @throws coding_exception
582 function required_param($parname, $type) {
583 if (func_num_args() != 2 or empty($parname) or empty($type)) {
584 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
586 // POST has precedence.
587 if (isset($_POST[$parname])) {
588 $param = $_POST[$parname];
589 } else if (isset($_GET[$parname])) {
590 $param = $_GET[$parname];
591 } else {
592 print_error('missingparam', '', '', $parname);
595 if (is_array($param)) {
596 debugging('Invalid array parameter detected in required_param(): '.$parname);
597 // TODO: switch to fatal error in Moodle 2.3.
598 return required_param_array($parname, $type);
601 return clean_param($param, $type);
605 * Returns a particular array value for the named variable, taken from
606 * POST or GET. If the parameter doesn't exist then an error is
607 * thrown because we require this variable.
609 * This function should be used to initialise all required values
610 * in a script that are based on parameters. Usually it will be
611 * used like this:
612 * $ids = required_param_array('ids', PARAM_INT);
614 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
616 * @param string $parname the name of the page parameter we want
617 * @param string $type expected type of parameter
618 * @return array
619 * @throws coding_exception
621 function required_param_array($parname, $type) {
622 if (func_num_args() != 2 or empty($parname) or empty($type)) {
623 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
625 // POST has precedence.
626 if (isset($_POST[$parname])) {
627 $param = $_POST[$parname];
628 } else if (isset($_GET[$parname])) {
629 $param = $_GET[$parname];
630 } else {
631 print_error('missingparam', '', '', $parname);
633 if (!is_array($param)) {
634 print_error('missingparam', '', '', $parname);
637 $result = array();
638 foreach ($param as $key => $value) {
639 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
640 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
641 continue;
643 $result[$key] = clean_param($value, $type);
646 return $result;
650 * Returns a particular value for the named variable, taken from
651 * POST or GET, otherwise returning a given default.
653 * This function should be used to initialise all optional values
654 * in a script that are based on parameters. Usually it will be
655 * used like this:
656 * $name = optional_param('name', 'Fred', PARAM_TEXT);
658 * Please note the $type parameter is now required and the value can not be array.
660 * @param string $parname the name of the page parameter we want
661 * @param mixed $default the default value to return if nothing is found
662 * @param string $type expected type of parameter
663 * @return mixed
664 * @throws coding_exception
666 function optional_param($parname, $default, $type) {
667 if (func_num_args() != 3 or empty($parname) or empty($type)) {
668 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
671 // POST has precedence.
672 if (isset($_POST[$parname])) {
673 $param = $_POST[$parname];
674 } else if (isset($_GET[$parname])) {
675 $param = $_GET[$parname];
676 } else {
677 return $default;
680 if (is_array($param)) {
681 debugging('Invalid array parameter detected in required_param(): '.$parname);
682 // TODO: switch to $default in Moodle 2.3.
683 return optional_param_array($parname, $default, $type);
686 return clean_param($param, $type);
690 * Returns a particular array value for the named variable, taken from
691 * POST or GET, otherwise returning a given default.
693 * This function should be used to initialise all optional values
694 * in a script that are based on parameters. Usually it will be
695 * used like this:
696 * $ids = optional_param('id', array(), PARAM_INT);
698 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
700 * @param string $parname the name of the page parameter we want
701 * @param mixed $default the default value to return if nothing is found
702 * @param string $type expected type of parameter
703 * @return array
704 * @throws coding_exception
706 function optional_param_array($parname, $default, $type) {
707 if (func_num_args() != 3 or empty($parname) or empty($type)) {
708 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
711 // POST has precedence.
712 if (isset($_POST[$parname])) {
713 $param = $_POST[$parname];
714 } else if (isset($_GET[$parname])) {
715 $param = $_GET[$parname];
716 } else {
717 return $default;
719 if (!is_array($param)) {
720 debugging('optional_param_array() expects array parameters only: '.$parname);
721 return $default;
724 $result = array();
725 foreach ($param as $key => $value) {
726 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
727 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
728 continue;
730 $result[$key] = clean_param($value, $type);
733 return $result;
737 * Strict validation of parameter values, the values are only converted
738 * to requested PHP type. Internally it is using clean_param, the values
739 * before and after cleaning must be equal - otherwise
740 * an invalid_parameter_exception is thrown.
741 * Objects and classes are not accepted.
743 * @param mixed $param
744 * @param string $type PARAM_ constant
745 * @param bool $allownull are nulls valid value?
746 * @param string $debuginfo optional debug information
747 * @return mixed the $param value converted to PHP type
748 * @throws invalid_parameter_exception if $param is not of given type
750 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
751 if (is_null($param)) {
752 if ($allownull == NULL_ALLOWED) {
753 return null;
754 } else {
755 throw new invalid_parameter_exception($debuginfo);
758 if (is_array($param) or is_object($param)) {
759 throw new invalid_parameter_exception($debuginfo);
762 $cleaned = clean_param($param, $type);
764 if ($type == PARAM_FLOAT) {
765 // Do not detect precision loss here.
766 if (is_float($param) or is_int($param)) {
767 // These always fit.
768 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
769 throw new invalid_parameter_exception($debuginfo);
771 } else if ((string)$param !== (string)$cleaned) {
772 // Conversion to string is usually lossless.
773 throw new invalid_parameter_exception($debuginfo);
776 return $cleaned;
780 * Makes sure array contains only the allowed types, this function does not validate array key names!
782 * <code>
783 * $options = clean_param($options, PARAM_INT);
784 * </code>
786 * @param array $param the variable array we are cleaning
787 * @param string $type expected format of param after cleaning.
788 * @param bool $recursive clean recursive arrays
789 * @return array
790 * @throws coding_exception
792 function clean_param_array(array $param = null, $type, $recursive = false) {
793 // Convert null to empty array.
794 $param = (array)$param;
795 foreach ($param as $key => $value) {
796 if (is_array($value)) {
797 if ($recursive) {
798 $param[$key] = clean_param_array($value, $type, true);
799 } else {
800 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
802 } else {
803 $param[$key] = clean_param($value, $type);
806 return $param;
810 * Used by {@link optional_param()} and {@link required_param()} to
811 * clean the variables and/or cast to specific types, based on
812 * an options field.
813 * <code>
814 * $course->format = clean_param($course->format, PARAM_ALPHA);
815 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
816 * </code>
818 * @param mixed $param the variable we are cleaning
819 * @param string $type expected format of param after cleaning.
820 * @return mixed
821 * @throws coding_exception
823 function clean_param($param, $type) {
824 global $CFG;
826 if (is_array($param)) {
827 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
828 } else if (is_object($param)) {
829 if (method_exists($param, '__toString')) {
830 $param = $param->__toString();
831 } else {
832 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
836 switch ($type) {
837 case PARAM_RAW:
838 // No cleaning at all.
839 $param = fix_utf8($param);
840 return $param;
842 case PARAM_RAW_TRIMMED:
843 // No cleaning, but strip leading and trailing whitespace.
844 $param = fix_utf8($param);
845 return trim($param);
847 case PARAM_CLEAN:
848 // General HTML cleaning, try to use more specific type if possible this is deprecated!
849 // Please use more specific type instead.
850 if (is_numeric($param)) {
851 return $param;
853 $param = fix_utf8($param);
854 // Sweep for scripts, etc.
855 return clean_text($param);
857 case PARAM_CLEANHTML:
858 // Clean html fragment.
859 $param = fix_utf8($param);
860 // Sweep for scripts, etc.
861 $param = clean_text($param, FORMAT_HTML);
862 return trim($param);
864 case PARAM_INT:
865 // Convert to integer.
866 return (int)$param;
868 case PARAM_FLOAT:
869 // Convert to float.
870 return (float)$param;
872 case PARAM_LOCALISEDFLOAT:
873 // Convert to float.
874 return unformat_float($param, true);
876 case PARAM_ALPHA:
877 // Remove everything not `a-z`.
878 return preg_replace('/[^a-zA-Z]/i', '', $param);
880 case PARAM_ALPHAEXT:
881 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
882 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
884 case PARAM_ALPHANUM:
885 // Remove everything not `a-zA-Z0-9`.
886 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
888 case PARAM_ALPHANUMEXT:
889 // Remove everything not `a-zA-Z0-9_-`.
890 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
892 case PARAM_SEQUENCE:
893 // Remove everything not `0-9,`.
894 return preg_replace('/[^0-9,]/i', '', $param);
896 case PARAM_BOOL:
897 // Convert to 1 or 0.
898 $tempstr = strtolower($param);
899 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
900 $param = 1;
901 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
902 $param = 0;
903 } else {
904 $param = empty($param) ? 0 : 1;
906 return $param;
908 case PARAM_NOTAGS:
909 // Strip all tags.
910 $param = fix_utf8($param);
911 return strip_tags($param);
913 case PARAM_TEXT:
914 // Leave only tags needed for multilang.
915 $param = fix_utf8($param);
916 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
917 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
918 do {
919 if (strpos($param, '</lang>') !== false) {
920 // Old and future mutilang syntax.
921 $param = strip_tags($param, '<lang>');
922 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
923 break;
925 $open = false;
926 foreach ($matches[0] as $match) {
927 if ($match === '</lang>') {
928 if ($open) {
929 $open = false;
930 continue;
931 } else {
932 break 2;
935 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
936 break 2;
937 } else {
938 $open = true;
941 if ($open) {
942 break;
944 return $param;
946 } else if (strpos($param, '</span>') !== false) {
947 // Current problematic multilang syntax.
948 $param = strip_tags($param, '<span>');
949 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
950 break;
952 $open = false;
953 foreach ($matches[0] as $match) {
954 if ($match === '</span>') {
955 if ($open) {
956 $open = false;
957 continue;
958 } else {
959 break 2;
962 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
963 break 2;
964 } else {
965 $open = true;
968 if ($open) {
969 break;
971 return $param;
973 } while (false);
974 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
975 return strip_tags($param);
977 case PARAM_COMPONENT:
978 // We do not want any guessing here, either the name is correct or not
979 // please note only normalised component names are accepted.
980 if (!preg_match('/^[a-z][a-z0-9]*(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
981 return '';
983 if (strpos($param, '__') !== false) {
984 return '';
986 if (strpos($param, 'mod_') === 0) {
987 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
988 if (substr_count($param, '_') != 1) {
989 return '';
992 return $param;
994 case PARAM_PLUGIN:
995 case PARAM_AREA:
996 // We do not want any guessing here, either the name is correct or not.
997 if (!is_valid_plugin_name($param)) {
998 return '';
1000 return $param;
1002 case PARAM_SAFEDIR:
1003 // Remove everything not a-zA-Z0-9_- .
1004 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
1006 case PARAM_SAFEPATH:
1007 // Remove everything not a-zA-Z0-9/_- .
1008 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
1010 case PARAM_FILE:
1011 // Strip all suspicious characters from filename.
1012 $param = fix_utf8($param);
1013 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
1014 if ($param === '.' || $param === '..') {
1015 $param = '';
1017 return $param;
1019 case PARAM_PATH:
1020 // Strip all suspicious characters from file path.
1021 $param = fix_utf8($param);
1022 $param = str_replace('\\', '/', $param);
1024 // Explode the path and clean each element using the PARAM_FILE rules.
1025 $breadcrumb = explode('/', $param);
1026 foreach ($breadcrumb as $key => $crumb) {
1027 if ($crumb === '.' && $key === 0) {
1028 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1029 } else {
1030 $crumb = clean_param($crumb, PARAM_FILE);
1032 $breadcrumb[$key] = $crumb;
1034 $param = implode('/', $breadcrumb);
1036 // Remove multiple current path (./././) and multiple slashes (///).
1037 $param = preg_replace('~//+~', '/', $param);
1038 $param = preg_replace('~/(\./)+~', '/', $param);
1039 return $param;
1041 case PARAM_HOST:
1042 // Allow FQDN or IPv4 dotted quad.
1043 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1044 // Match ipv4 dotted quad.
1045 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1046 // Confirm values are ok.
1047 if ( $match[0] > 255
1048 || $match[1] > 255
1049 || $match[3] > 255
1050 || $match[4] > 255 ) {
1051 // Hmmm, what kind of dotted quad is this?
1052 $param = '';
1054 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1055 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1056 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1058 // All is ok - $param is respected.
1059 } else {
1060 // All is not ok...
1061 $param='';
1063 return $param;
1065 case PARAM_URL:
1066 // Allow safe urls.
1067 $param = fix_utf8($param);
1068 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1069 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1070 // All is ok, param is respected.
1071 } else {
1072 // Not really ok.
1073 $param ='';
1075 return $param;
1077 case PARAM_LOCALURL:
1078 // Allow http absolute, root relative and relative URLs within wwwroot.
1079 $param = clean_param($param, PARAM_URL);
1080 if (!empty($param)) {
1082 if ($param === $CFG->wwwroot) {
1083 // Exact match;
1084 } else if (preg_match(':^/:', $param)) {
1085 // Root-relative, ok!
1086 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1087 // Absolute, and matches our wwwroot.
1088 } else {
1089 // Relative - let's make sure there are no tricks.
1090 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1091 // Looks ok.
1092 } else {
1093 $param = '';
1097 return $param;
1099 case PARAM_PEM:
1100 $param = trim($param);
1101 // PEM formatted strings may contain letters/numbers and the symbols:
1102 // forward slash: /
1103 // plus sign: +
1104 // equal sign: =
1105 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1106 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1107 list($wholething, $body) = $matches;
1108 unset($wholething, $matches);
1109 $b64 = clean_param($body, PARAM_BASE64);
1110 if (!empty($b64)) {
1111 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1112 } else {
1113 return '';
1116 return '';
1118 case PARAM_BASE64:
1119 if (!empty($param)) {
1120 // PEM formatted strings may contain letters/numbers and the symbols
1121 // forward slash: /
1122 // plus sign: +
1123 // equal sign: =.
1124 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1125 return '';
1127 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1128 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1129 // than (or equal to) 64 characters long.
1130 for ($i=0, $j=count($lines); $i < $j; $i++) {
1131 if ($i + 1 == $j) {
1132 if (64 < strlen($lines[$i])) {
1133 return '';
1135 continue;
1138 if (64 != strlen($lines[$i])) {
1139 return '';
1142 return implode("\n", $lines);
1143 } else {
1144 return '';
1147 case PARAM_TAG:
1148 $param = fix_utf8($param);
1149 // Please note it is not safe to use the tag name directly anywhere,
1150 // it must be processed with s(), urlencode() before embedding anywhere.
1151 // Remove some nasties.
1152 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1153 // Convert many whitespace chars into one.
1154 $param = preg_replace('/\s+/u', ' ', $param);
1155 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1156 return $param;
1158 case PARAM_TAGLIST:
1159 $param = fix_utf8($param);
1160 $tags = explode(',', $param);
1161 $result = array();
1162 foreach ($tags as $tag) {
1163 $res = clean_param($tag, PARAM_TAG);
1164 if ($res !== '') {
1165 $result[] = $res;
1168 if ($result) {
1169 return implode(',', $result);
1170 } else {
1171 return '';
1174 case PARAM_CAPABILITY:
1175 if (get_capability_info($param)) {
1176 return $param;
1177 } else {
1178 return '';
1181 case PARAM_PERMISSION:
1182 $param = (int)$param;
1183 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1184 return $param;
1185 } else {
1186 return CAP_INHERIT;
1189 case PARAM_AUTH:
1190 $param = clean_param($param, PARAM_PLUGIN);
1191 if (empty($param)) {
1192 return '';
1193 } else if (exists_auth_plugin($param)) {
1194 return $param;
1195 } else {
1196 return '';
1199 case PARAM_LANG:
1200 $param = clean_param($param, PARAM_SAFEDIR);
1201 if (get_string_manager()->translation_exists($param)) {
1202 return $param;
1203 } else {
1204 // Specified language is not installed or param malformed.
1205 return '';
1208 case PARAM_THEME:
1209 $param = clean_param($param, PARAM_PLUGIN);
1210 if (empty($param)) {
1211 return '';
1212 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1213 return $param;
1214 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1215 return $param;
1216 } else {
1217 // Specified theme is not installed.
1218 return '';
1221 case PARAM_USERNAME:
1222 $param = fix_utf8($param);
1223 $param = trim($param);
1224 // Convert uppercase to lowercase MDL-16919.
1225 $param = core_text::strtolower($param);
1226 if (empty($CFG->extendedusernamechars)) {
1227 $param = str_replace(" " , "", $param);
1228 // Regular expression, eliminate all chars EXCEPT:
1229 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1230 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1232 return $param;
1234 case PARAM_EMAIL:
1235 $param = fix_utf8($param);
1236 if (validate_email($param)) {
1237 return $param;
1238 } else {
1239 return '';
1242 case PARAM_STRINGID:
1243 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1244 return $param;
1245 } else {
1246 return '';
1249 case PARAM_TIMEZONE:
1250 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1251 $param = fix_utf8($param);
1252 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1253 if (preg_match($timezonepattern, $param)) {
1254 return $param;
1255 } else {
1256 return '';
1259 default:
1260 // Doh! throw error, switched parameters in optional_param or another serious problem.
1261 print_error("unknownparamtype", '', '', $type);
1266 * Whether the PARAM_* type is compatible in RTL.
1268 * Being compatible with RTL means that the data they contain can flow
1269 * from right-to-left or left-to-right without compromising the user experience.
1271 * Take URLs for example, they are not RTL compatible as they should always
1272 * flow from the left to the right. This also applies to numbers, email addresses,
1273 * configuration snippets, base64 strings, etc...
1275 * This function tries to best guess which parameters can contain localised strings.
1277 * @param string $paramtype Constant PARAM_*.
1278 * @return bool
1280 function is_rtl_compatible($paramtype) {
1281 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1285 * Makes sure the data is using valid utf8, invalid characters are discarded.
1287 * Note: this function is not intended for full objects with methods and private properties.
1289 * @param mixed $value
1290 * @return mixed with proper utf-8 encoding
1292 function fix_utf8($value) {
1293 if (is_null($value) or $value === '') {
1294 return $value;
1296 } else if (is_string($value)) {
1297 if ((string)(int)$value === $value) {
1298 // Shortcut.
1299 return $value;
1301 // No null bytes expected in our data, so let's remove it.
1302 $value = str_replace("\0", '', $value);
1304 // Note: this duplicates min_fix_utf8() intentionally.
1305 static $buggyiconv = null;
1306 if ($buggyiconv === null) {
1307 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1310 if ($buggyiconv) {
1311 if (function_exists('mb_convert_encoding')) {
1312 $subst = mb_substitute_character();
1313 mb_substitute_character('none');
1314 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1315 mb_substitute_character($subst);
1317 } else {
1318 // Warn admins on admin/index.php page.
1319 $result = $value;
1322 } else {
1323 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1326 return $result;
1328 } else if (is_array($value)) {
1329 foreach ($value as $k => $v) {
1330 $value[$k] = fix_utf8($v);
1332 return $value;
1334 } else if (is_object($value)) {
1335 // Do not modify original.
1336 $value = clone($value);
1337 foreach ($value as $k => $v) {
1338 $value->$k = fix_utf8($v);
1340 return $value;
1342 } else {
1343 // This is some other type, no utf-8 here.
1344 return $value;
1349 * Return true if given value is integer or string with integer value
1351 * @param mixed $value String or Int
1352 * @return bool true if number, false if not
1354 function is_number($value) {
1355 if (is_int($value)) {
1356 return true;
1357 } else if (is_string($value)) {
1358 return ((string)(int)$value) === $value;
1359 } else {
1360 return false;
1365 * Returns host part from url.
1367 * @param string $url full url
1368 * @return string host, null if not found
1370 function get_host_from_url($url) {
1371 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1372 if ($matches) {
1373 return $matches[1];
1375 return null;
1379 * Tests whether anything was returned by text editor
1381 * This function is useful for testing whether something you got back from
1382 * the HTML editor actually contains anything. Sometimes the HTML editor
1383 * appear to be empty, but actually you get back a <br> tag or something.
1385 * @param string $string a string containing HTML.
1386 * @return boolean does the string contain any actual content - that is text,
1387 * images, objects, etc.
1389 function html_is_blank($string) {
1390 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1394 * Set a key in global configuration
1396 * Set a key/value pair in both this session's {@link $CFG} global variable
1397 * and in the 'config' database table for future sessions.
1399 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1400 * In that case it doesn't affect $CFG.
1402 * A NULL value will delete the entry.
1404 * NOTE: this function is called from lib/db/upgrade.php
1406 * @param string $name the key to set
1407 * @param string $value the value to set (without magic quotes)
1408 * @param string $plugin (optional) the plugin scope, default null
1409 * @return bool true or exception
1411 function set_config($name, $value, $plugin=null) {
1412 global $CFG, $DB;
1414 if (empty($plugin)) {
1415 if (!array_key_exists($name, $CFG->config_php_settings)) {
1416 // So it's defined for this invocation at least.
1417 if (is_null($value)) {
1418 unset($CFG->$name);
1419 } else {
1420 // Settings from db are always strings.
1421 $CFG->$name = (string)$value;
1425 if ($DB->get_field('config', 'name', array('name' => $name))) {
1426 if ($value === null) {
1427 $DB->delete_records('config', array('name' => $name));
1428 } else {
1429 $DB->set_field('config', 'value', $value, array('name' => $name));
1431 } else {
1432 if ($value !== null) {
1433 $config = new stdClass();
1434 $config->name = $name;
1435 $config->value = $value;
1436 $DB->insert_record('config', $config, false);
1438 // When setting config during a Behat test (in the CLI script, not in the web browser
1439 // requests), remember which ones are set so that we can clear them later.
1440 if (defined('BEHAT_TEST')) {
1441 if (!property_exists($CFG, 'behat_cli_added_config')) {
1442 $CFG->behat_cli_added_config = [];
1444 $CFG->behat_cli_added_config[$name] = true;
1447 if ($name === 'siteidentifier') {
1448 cache_helper::update_site_identifier($value);
1450 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1451 } else {
1452 // Plugin scope.
1453 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1454 if ($value===null) {
1455 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1456 } else {
1457 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1459 } else {
1460 if ($value !== null) {
1461 $config = new stdClass();
1462 $config->plugin = $plugin;
1463 $config->name = $name;
1464 $config->value = $value;
1465 $DB->insert_record('config_plugins', $config, false);
1468 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1471 return true;
1475 * Get configuration values from the global config table
1476 * or the config_plugins table.
1478 * If called with one parameter, it will load all the config
1479 * variables for one plugin, and return them as an object.
1481 * If called with 2 parameters it will return a string single
1482 * value or false if the value is not found.
1484 * NOTE: this function is called from lib/db/upgrade.php
1486 * @param string $plugin full component name
1487 * @param string $name default null
1488 * @return mixed hash-like object or single value, return false no config found
1489 * @throws dml_exception
1491 function get_config($plugin, $name = null) {
1492 global $CFG, $DB;
1494 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1495 $forced =& $CFG->config_php_settings;
1496 $iscore = true;
1497 $plugin = 'core';
1498 } else {
1499 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1500 $forced =& $CFG->forced_plugin_settings[$plugin];
1501 } else {
1502 $forced = array();
1504 $iscore = false;
1507 if (!isset($CFG->siteidentifier)) {
1508 try {
1509 // This may throw an exception during installation, which is how we detect the
1510 // need to install the database. For more details see {@see initialise_cfg()}.
1511 $CFG->siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1512 } catch (dml_exception $ex) {
1513 // Set siteidentifier to false. We don't want to trip this continually.
1514 $siteidentifier = false;
1515 throw $ex;
1519 if (!empty($name)) {
1520 if (array_key_exists($name, $forced)) {
1521 return (string)$forced[$name];
1522 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1523 return $CFG->siteidentifier;
1527 $cache = cache::make('core', 'config');
1528 $result = $cache->get($plugin);
1529 if ($result === false) {
1530 // The user is after a recordset.
1531 if (!$iscore) {
1532 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1533 } else {
1534 // This part is not really used any more, but anyway...
1535 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1537 $cache->set($plugin, $result);
1540 if (!empty($name)) {
1541 if (array_key_exists($name, $result)) {
1542 return $result[$name];
1544 return false;
1547 if ($plugin === 'core') {
1548 $result['siteidentifier'] = $CFG->siteidentifier;
1551 foreach ($forced as $key => $value) {
1552 if (is_null($value) or is_array($value) or is_object($value)) {
1553 // We do not want any extra mess here, just real settings that could be saved in db.
1554 unset($result[$key]);
1555 } else {
1556 // Convert to string as if it went through the DB.
1557 $result[$key] = (string)$value;
1561 return (object)$result;
1565 * Removes a key from global configuration.
1567 * NOTE: this function is called from lib/db/upgrade.php
1569 * @param string $name the key to set
1570 * @param string $plugin (optional) the plugin scope
1571 * @return boolean whether the operation succeeded.
1573 function unset_config($name, $plugin=null) {
1574 global $CFG, $DB;
1576 if (empty($plugin)) {
1577 unset($CFG->$name);
1578 $DB->delete_records('config', array('name' => $name));
1579 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1580 } else {
1581 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1582 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1585 return true;
1589 * Remove all the config variables for a given plugin.
1591 * NOTE: this function is called from lib/db/upgrade.php
1593 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1594 * @return boolean whether the operation succeeded.
1596 function unset_all_config_for_plugin($plugin) {
1597 global $DB;
1598 // Delete from the obvious config_plugins first.
1599 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1600 // Next delete any suspect settings from config.
1601 $like = $DB->sql_like('name', '?', true, true, false, '|');
1602 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1603 $DB->delete_records_select('config', $like, $params);
1604 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1605 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1607 return true;
1611 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1613 * All users are verified if they still have the necessary capability.
1615 * @param string $value the value of the config setting.
1616 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1617 * @param bool $includeadmins include administrators.
1618 * @return array of user objects.
1620 function get_users_from_config($value, $capability, $includeadmins = true) {
1621 if (empty($value) or $value === '$@NONE@$') {
1622 return array();
1625 // We have to make sure that users still have the necessary capability,
1626 // it should be faster to fetch them all first and then test if they are present
1627 // instead of validating them one-by-one.
1628 $users = get_users_by_capability(context_system::instance(), $capability);
1629 if ($includeadmins) {
1630 $admins = get_admins();
1631 foreach ($admins as $admin) {
1632 $users[$admin->id] = $admin;
1636 if ($value === '$@ALL@$') {
1637 return $users;
1640 $result = array(); // Result in correct order.
1641 $allowed = explode(',', $value);
1642 foreach ($allowed as $uid) {
1643 if (isset($users[$uid])) {
1644 $user = $users[$uid];
1645 $result[$user->id] = $user;
1649 return $result;
1654 * Invalidates browser caches and cached data in temp.
1656 * @return void
1658 function purge_all_caches() {
1659 purge_caches();
1663 * Selectively invalidate different types of cache.
1665 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1666 * areas alone or in combination.
1668 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1669 * 'muc' Purge MUC caches?
1670 * 'theme' Purge theme cache?
1671 * 'lang' Purge language string cache?
1672 * 'js' Purge javascript cache?
1673 * 'filter' Purge text filter cache?
1674 * 'other' Purge all other caches?
1676 function purge_caches($options = []) {
1677 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1678 if (empty(array_filter($options))) {
1679 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1680 } else {
1681 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1683 if ($options['muc']) {
1684 cache_helper::purge_all();
1686 if ($options['theme']) {
1687 theme_reset_all_caches();
1689 if ($options['lang']) {
1690 get_string_manager()->reset_caches();
1692 if ($options['js']) {
1693 js_reset_all_caches();
1695 if ($options['template']) {
1696 template_reset_all_caches();
1698 if ($options['filter']) {
1699 reset_text_filters_cache();
1701 if ($options['other']) {
1702 purge_other_caches();
1707 * Purge all non-MUC caches not otherwise purged in purge_caches.
1709 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1710 * {@link phpunit_util::reset_dataroot()}
1712 function purge_other_caches() {
1713 global $DB, $CFG;
1714 if (class_exists('core_plugin_manager')) {
1715 core_plugin_manager::reset_caches();
1718 // Bump up cacherev field for all courses.
1719 try {
1720 increment_revision_number('course', 'cacherev', '');
1721 } catch (moodle_exception $e) {
1722 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1725 $DB->reset_caches();
1727 // Purge all other caches: rss, simplepie, etc.
1728 clearstatcache();
1729 remove_dir($CFG->cachedir.'', true);
1731 // Make sure cache dir is writable, throws exception if not.
1732 make_cache_directory('');
1734 // This is the only place where we purge local caches, we are only adding files there.
1735 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1736 remove_dir($CFG->localcachedir, true);
1737 set_config('localcachedirpurged', time());
1738 make_localcache_directory('', true);
1739 \core\task\manager::clear_static_caches();
1743 * Get volatile flags
1745 * @param string $type
1746 * @param int $changedsince default null
1747 * @return array records array
1749 function get_cache_flags($type, $changedsince = null) {
1750 global $DB;
1752 $params = array('type' => $type, 'expiry' => time());
1753 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1754 if ($changedsince !== null) {
1755 $params['changedsince'] = $changedsince;
1756 $sqlwhere .= " AND timemodified > :changedsince";
1758 $cf = array();
1759 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1760 foreach ($flags as $flag) {
1761 $cf[$flag->name] = $flag->value;
1764 return $cf;
1768 * Get volatile flags
1770 * @param string $type
1771 * @param string $name
1772 * @param int $changedsince default null
1773 * @return string|false The cache flag value or false
1775 function get_cache_flag($type, $name, $changedsince=null) {
1776 global $DB;
1778 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1780 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1781 if ($changedsince !== null) {
1782 $params['changedsince'] = $changedsince;
1783 $sqlwhere .= " AND timemodified > :changedsince";
1786 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1790 * Set a volatile flag
1792 * @param string $type the "type" namespace for the key
1793 * @param string $name the key to set
1794 * @param string $value the value to set (without magic quotes) - null will remove the flag
1795 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1796 * @return bool Always returns true
1798 function set_cache_flag($type, $name, $value, $expiry = null) {
1799 global $DB;
1801 $timemodified = time();
1802 if ($expiry === null || $expiry < $timemodified) {
1803 $expiry = $timemodified + 24 * 60 * 60;
1804 } else {
1805 $expiry = (int)$expiry;
1808 if ($value === null) {
1809 unset_cache_flag($type, $name);
1810 return true;
1813 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1814 // This is a potential problem in DEBUG_DEVELOPER.
1815 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1816 return true; // No need to update.
1818 $f->value = $value;
1819 $f->expiry = $expiry;
1820 $f->timemodified = $timemodified;
1821 $DB->update_record('cache_flags', $f);
1822 } else {
1823 $f = new stdClass();
1824 $f->flagtype = $type;
1825 $f->name = $name;
1826 $f->value = $value;
1827 $f->expiry = $expiry;
1828 $f->timemodified = $timemodified;
1829 $DB->insert_record('cache_flags', $f);
1831 return true;
1835 * Removes a single volatile flag
1837 * @param string $type the "type" namespace for the key
1838 * @param string $name the key to set
1839 * @return bool
1841 function unset_cache_flag($type, $name) {
1842 global $DB;
1843 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1844 return true;
1848 * Garbage-collect volatile flags
1850 * @return bool Always returns true
1852 function gc_cache_flags() {
1853 global $DB;
1854 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1855 return true;
1858 // USER PREFERENCE API.
1861 * Refresh user preference cache. This is used most often for $USER
1862 * object that is stored in session, but it also helps with performance in cron script.
1864 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1866 * @package core
1867 * @category preference
1868 * @access public
1869 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1870 * @param int $cachelifetime Cache life time on the current page (in seconds)
1871 * @throws coding_exception
1872 * @return null
1874 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1875 global $DB;
1876 // Static cache, we need to check on each page load, not only every 2 minutes.
1877 static $loadedusers = array();
1879 if (!isset($user->id)) {
1880 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1883 if (empty($user->id) or isguestuser($user->id)) {
1884 // No permanent storage for not-logged-in users and guest.
1885 if (!isset($user->preference)) {
1886 $user->preference = array();
1888 return;
1891 $timenow = time();
1893 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1894 // Already loaded at least once on this page. Are we up to date?
1895 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1896 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1897 return;
1899 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1900 // No change since the lastcheck on this page.
1901 $user->preference['_lastloaded'] = $timenow;
1902 return;
1906 // OK, so we have to reload all preferences.
1907 $loadedusers[$user->id] = true;
1908 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1909 $user->preference['_lastloaded'] = $timenow;
1913 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1915 * NOTE: internal function, do not call from other code.
1917 * @package core
1918 * @access private
1919 * @param integer $userid the user whose prefs were changed.
1921 function mark_user_preferences_changed($userid) {
1922 global $CFG;
1924 if (empty($userid) or isguestuser($userid)) {
1925 // No cache flags for guest and not-logged-in users.
1926 return;
1929 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1933 * Sets a preference for the specified user.
1935 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1937 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1939 * @package core
1940 * @category preference
1941 * @access public
1942 * @param string $name The key to set as preference for the specified user
1943 * @param string $value The value to set for the $name key in the specified user's
1944 * record, null means delete current value.
1945 * @param stdClass|int|null $user A moodle user object or id, null means current user
1946 * @throws coding_exception
1947 * @return bool Always true or exception
1949 function set_user_preference($name, $value, $user = null) {
1950 global $USER, $DB;
1952 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1953 throw new coding_exception('Invalid preference name in set_user_preference() call');
1956 if (is_null($value)) {
1957 // Null means delete current.
1958 return unset_user_preference($name, $user);
1959 } else if (is_object($value)) {
1960 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1961 } else if (is_array($value)) {
1962 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1964 // Value column maximum length is 1333 characters.
1965 $value = (string)$value;
1966 if (core_text::strlen($value) > 1333) {
1967 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1970 if (is_null($user)) {
1971 $user = $USER;
1972 } else if (isset($user->id)) {
1973 // It is a valid object.
1974 } else if (is_numeric($user)) {
1975 $user = (object)array('id' => (int)$user);
1976 } else {
1977 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1980 check_user_preferences_loaded($user);
1982 if (empty($user->id) or isguestuser($user->id)) {
1983 // No permanent storage for not-logged-in users and guest.
1984 $user->preference[$name] = $value;
1985 return true;
1988 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1989 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1990 // Preference already set to this value.
1991 return true;
1993 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1995 } else {
1996 $preference = new stdClass();
1997 $preference->userid = $user->id;
1998 $preference->name = $name;
1999 $preference->value = $value;
2000 $DB->insert_record('user_preferences', $preference);
2003 // Update value in cache.
2004 $user->preference[$name] = $value;
2005 // Update the $USER in case where we've not a direct reference to $USER.
2006 if ($user !== $USER && $user->id == $USER->id) {
2007 $USER->preference[$name] = $value;
2010 // Set reload flag for other sessions.
2011 mark_user_preferences_changed($user->id);
2013 return true;
2017 * Sets a whole array of preferences for the current user
2019 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2021 * @package core
2022 * @category preference
2023 * @access public
2024 * @param array $prefarray An array of key/value pairs to be set
2025 * @param stdClass|int|null $user A moodle user object or id, null means current user
2026 * @return bool Always true or exception
2028 function set_user_preferences(array $prefarray, $user = null) {
2029 foreach ($prefarray as $name => $value) {
2030 set_user_preference($name, $value, $user);
2032 return true;
2036 * Unsets a preference completely by deleting it from the database
2038 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2040 * @package core
2041 * @category preference
2042 * @access public
2043 * @param string $name The key to unset as preference for the specified user
2044 * @param stdClass|int|null $user A moodle user object or id, null means current user
2045 * @throws coding_exception
2046 * @return bool Always true or exception
2048 function unset_user_preference($name, $user = null) {
2049 global $USER, $DB;
2051 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2052 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2055 if (is_null($user)) {
2056 $user = $USER;
2057 } else if (isset($user->id)) {
2058 // It is a valid object.
2059 } else if (is_numeric($user)) {
2060 $user = (object)array('id' => (int)$user);
2061 } else {
2062 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2065 check_user_preferences_loaded($user);
2067 if (empty($user->id) or isguestuser($user->id)) {
2068 // No permanent storage for not-logged-in user and guest.
2069 unset($user->preference[$name]);
2070 return true;
2073 // Delete from DB.
2074 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2076 // Delete the preference from cache.
2077 unset($user->preference[$name]);
2078 // Update the $USER in case where we've not a direct reference to $USER.
2079 if ($user !== $USER && $user->id == $USER->id) {
2080 unset($USER->preference[$name]);
2083 // Set reload flag for other sessions.
2084 mark_user_preferences_changed($user->id);
2086 return true;
2090 * Used to fetch user preference(s)
2092 * If no arguments are supplied this function will return
2093 * all of the current user preferences as an array.
2095 * If a name is specified then this function
2096 * attempts to return that particular preference value. If
2097 * none is found, then the optional value $default is returned,
2098 * otherwise null.
2100 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2102 * @package core
2103 * @category preference
2104 * @access public
2105 * @param string $name Name of the key to use in finding a preference value
2106 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2107 * @param stdClass|int|null $user A moodle user object or id, null means current user
2108 * @throws coding_exception
2109 * @return string|mixed|null A string containing the value of a single preference. An
2110 * array with all of the preferences or null
2112 function get_user_preferences($name = null, $default = null, $user = null) {
2113 global $USER;
2115 if (is_null($name)) {
2116 // All prefs.
2117 } else if (is_numeric($name) or $name === '_lastloaded') {
2118 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2121 if (is_null($user)) {
2122 $user = $USER;
2123 } else if (isset($user->id)) {
2124 // Is a valid object.
2125 } else if (is_numeric($user)) {
2126 if ($USER->id == $user) {
2127 $user = $USER;
2128 } else {
2129 $user = (object)array('id' => (int)$user);
2131 } else {
2132 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2135 check_user_preferences_loaded($user);
2137 if (empty($name)) {
2138 // All values.
2139 return $user->preference;
2140 } else if (isset($user->preference[$name])) {
2141 // The single string value.
2142 return $user->preference[$name];
2143 } else {
2144 // Default value (null if not specified).
2145 return $default;
2149 // FUNCTIONS FOR HANDLING TIME.
2152 * Given Gregorian date parts in user time produce a GMT timestamp.
2154 * @package core
2155 * @category time
2156 * @param int $year The year part to create timestamp of
2157 * @param int $month The month part to create timestamp of
2158 * @param int $day The day part to create timestamp of
2159 * @param int $hour The hour part to create timestamp of
2160 * @param int $minute The minute part to create timestamp of
2161 * @param int $second The second part to create timestamp of
2162 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2163 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2164 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2165 * applied only if timezone is 99 or string.
2166 * @return int GMT timestamp
2168 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2169 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2170 $date->setDate((int)$year, (int)$month, (int)$day);
2171 $date->setTime((int)$hour, (int)$minute, (int)$second);
2173 $time = $date->getTimestamp();
2175 if ($time === false) {
2176 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2177 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2180 // Moodle BC DST stuff.
2181 if (!$applydst) {
2182 $time += dst_offset_on($time, $timezone);
2185 return $time;
2190 * Format a date/time (seconds) as weeks, days, hours etc as needed
2192 * Given an amount of time in seconds, returns string
2193 * formatted nicely as years, days, hours etc as needed
2195 * @package core
2196 * @category time
2197 * @uses MINSECS
2198 * @uses HOURSECS
2199 * @uses DAYSECS
2200 * @uses YEARSECS
2201 * @param int $totalsecs Time in seconds
2202 * @param stdClass $str Should be a time object
2203 * @return string A nicely formatted date/time string
2205 function format_time($totalsecs, $str = null) {
2207 $totalsecs = abs($totalsecs);
2209 if (!$str) {
2210 // Create the str structure the slow way.
2211 $str = new stdClass();
2212 $str->day = get_string('day');
2213 $str->days = get_string('days');
2214 $str->hour = get_string('hour');
2215 $str->hours = get_string('hours');
2216 $str->min = get_string('min');
2217 $str->mins = get_string('mins');
2218 $str->sec = get_string('sec');
2219 $str->secs = get_string('secs');
2220 $str->year = get_string('year');
2221 $str->years = get_string('years');
2224 $years = floor($totalsecs/YEARSECS);
2225 $remainder = $totalsecs - ($years*YEARSECS);
2226 $days = floor($remainder/DAYSECS);
2227 $remainder = $totalsecs - ($days*DAYSECS);
2228 $hours = floor($remainder/HOURSECS);
2229 $remainder = $remainder - ($hours*HOURSECS);
2230 $mins = floor($remainder/MINSECS);
2231 $secs = $remainder - ($mins*MINSECS);
2233 $ss = ($secs == 1) ? $str->sec : $str->secs;
2234 $sm = ($mins == 1) ? $str->min : $str->mins;
2235 $sh = ($hours == 1) ? $str->hour : $str->hours;
2236 $sd = ($days == 1) ? $str->day : $str->days;
2237 $sy = ($years == 1) ? $str->year : $str->years;
2239 $oyears = '';
2240 $odays = '';
2241 $ohours = '';
2242 $omins = '';
2243 $osecs = '';
2245 if ($years) {
2246 $oyears = $years .' '. $sy;
2248 if ($days) {
2249 $odays = $days .' '. $sd;
2251 if ($hours) {
2252 $ohours = $hours .' '. $sh;
2254 if ($mins) {
2255 $omins = $mins .' '. $sm;
2257 if ($secs) {
2258 $osecs = $secs .' '. $ss;
2261 if ($years) {
2262 return trim($oyears .' '. $odays);
2264 if ($days) {
2265 return trim($odays .' '. $ohours);
2267 if ($hours) {
2268 return trim($ohours .' '. $omins);
2270 if ($mins) {
2271 return trim($omins .' '. $osecs);
2273 if ($secs) {
2274 return $osecs;
2276 return get_string('now');
2280 * Returns a formatted string that represents a date in user time.
2282 * @package core
2283 * @category time
2284 * @param int $date the timestamp in UTC, as obtained from the database.
2285 * @param string $format strftime format. You should probably get this using
2286 * get_string('strftime...', 'langconfig');
2287 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2288 * not 99 then daylight saving will not be added.
2289 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2290 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2291 * If false then the leading zero is maintained.
2292 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2293 * @return string the formatted date/time.
2295 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2296 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2297 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2301 * Returns a html "time" tag with both the exact user date with timezone information
2302 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2304 * @package core
2305 * @category time
2306 * @param int $date the timestamp in UTC, as obtained from the database.
2307 * @param string $format strftime format. You should probably get this using
2308 * get_string('strftime...', 'langconfig');
2309 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2310 * not 99 then daylight saving will not be added.
2311 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2312 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2313 * If false then the leading zero is maintained.
2314 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2315 * @return string the formatted date/time.
2317 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2318 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2319 if (CLI_SCRIPT && !PHPUNIT_TEST) {
2320 return $userdatestr;
2322 $machinedate = new DateTime();
2323 $machinedate->setTimestamp(intval($date));
2324 $machinedate->setTimezone(core_date::get_user_timezone_object());
2326 return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2330 * Returns a formatted date ensuring it is UTF-8.
2332 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2333 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2335 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2336 * @param string $format strftime format.
2337 * @param int|float|string $tz the user timezone
2338 * @return string the formatted date/time.
2339 * @since Moodle 2.3.3
2341 function date_format_string($date, $format, $tz = 99) {
2342 global $CFG;
2344 $localewincharset = null;
2345 // Get the calendar type user is using.
2346 if ($CFG->ostype == 'WINDOWS') {
2347 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2348 $localewincharset = $calendartype->locale_win_charset();
2351 if ($localewincharset) {
2352 $format = core_text::convert($format, 'utf-8', $localewincharset);
2355 date_default_timezone_set(core_date::get_user_timezone($tz));
2356 $datestring = strftime($format, $date);
2357 core_date::set_default_server_timezone();
2359 if ($localewincharset) {
2360 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2363 return $datestring;
2367 * Given a $time timestamp in GMT (seconds since epoch),
2368 * returns an array that represents the Gregorian date in user time
2370 * @package core
2371 * @category time
2372 * @param int $time Timestamp in GMT
2373 * @param float|int|string $timezone user timezone
2374 * @return array An array that represents the date in user time
2376 function usergetdate($time, $timezone=99) {
2377 if ($time === null) {
2378 // PHP8 and PHP7 return different results when getdate(null) is called.
2379 // Display warning and cast to 0 to make sure the usergetdate() behaves consistently on all versions of PHP.
2380 // In the future versions of Moodle we may consider adding a strict typehint.
2381 debugging('usergetdate() expects parameter $time to be int, null given', DEBUG_DEVELOPER);
2382 $time = 0;
2385 date_default_timezone_set(core_date::get_user_timezone($timezone));
2386 $result = getdate($time);
2387 core_date::set_default_server_timezone();
2389 return $result;
2393 * Given a GMT timestamp (seconds since epoch), offsets it by
2394 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2396 * NOTE: this function does not include DST properly,
2397 * you should use the PHP date stuff instead!
2399 * @package core
2400 * @category time
2401 * @param int $date Timestamp in GMT
2402 * @param float|int|string $timezone user timezone
2403 * @return int
2405 function usertime($date, $timezone=99) {
2406 $userdate = new DateTime('@' . $date);
2407 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2408 $dst = dst_offset_on($date, $timezone);
2410 return $date - $userdate->getOffset() + $dst;
2414 * Get a formatted string representation of an interval between two unix timestamps.
2416 * E.g.
2417 * $intervalstring = get_time_interval_string(12345600, 12345660);
2418 * Will produce the string:
2419 * '0d 0h 1m'
2421 * @param int $time1 unix timestamp
2422 * @param int $time2 unix timestamp
2423 * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2424 * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2426 function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
2427 $dtdate = new DateTime();
2428 $dtdate->setTimeStamp($time1);
2429 $dtdate2 = new DateTime();
2430 $dtdate2->setTimeStamp($time2);
2431 $interval = $dtdate2->diff($dtdate);
2432 $format = empty($format) ? get_string('dateintervaldayshoursmins', 'langconfig') : $format;
2433 return $interval->format($format);
2437 * Given a time, return the GMT timestamp of the most recent midnight
2438 * for the current user.
2440 * @package core
2441 * @category time
2442 * @param int $date Timestamp in GMT
2443 * @param float|int|string $timezone user timezone
2444 * @return int Returns a GMT timestamp
2446 function usergetmidnight($date, $timezone=99) {
2448 $userdate = usergetdate($date, $timezone);
2450 // Time of midnight of this user's day, in GMT.
2451 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2456 * Returns a string that prints the user's timezone
2458 * @package core
2459 * @category time
2460 * @param float|int|string $timezone user timezone
2461 * @return string
2463 function usertimezone($timezone=99) {
2464 $tz = core_date::get_user_timezone($timezone);
2465 return core_date::get_localised_timezone($tz);
2469 * Returns a float or a string which denotes the user's timezone
2470 * 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)
2471 * means that for this timezone there are also DST rules to be taken into account
2472 * Checks various settings and picks the most dominant of those which have a value
2474 * @package core
2475 * @category time
2476 * @param float|int|string $tz timezone to calculate GMT time offset before
2477 * calculating user timezone, 99 is default user timezone
2478 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2479 * @return float|string
2481 function get_user_timezone($tz = 99) {
2482 global $USER, $CFG;
2484 $timezones = array(
2485 $tz,
2486 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2487 isset($USER->timezone) ? $USER->timezone : 99,
2488 isset($CFG->timezone) ? $CFG->timezone : 99,
2491 $tz = 99;
2493 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2494 foreach ($timezones as $nextvalue) {
2495 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2496 $tz = $nextvalue;
2499 return is_numeric($tz) ? (float) $tz : $tz;
2503 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2504 * - Note: Daylight saving only works for string timezones and not for float.
2506 * @package core
2507 * @category time
2508 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2509 * @param int|float|string $strtimezone user timezone
2510 * @return int
2512 function dst_offset_on($time, $strtimezone = null) {
2513 $tz = core_date::get_user_timezone($strtimezone);
2514 $date = new DateTime('@' . $time);
2515 $date->setTimezone(new DateTimeZone($tz));
2516 if ($date->format('I') == '1') {
2517 if ($tz === 'Australia/Lord_Howe') {
2518 return 1800;
2520 return 3600;
2522 return 0;
2526 * Calculates when the day appears in specific month
2528 * @package core
2529 * @category time
2530 * @param int $startday starting day of the month
2531 * @param int $weekday The day when week starts (normally taken from user preferences)
2532 * @param int $month The month whose day is sought
2533 * @param int $year The year of the month whose day is sought
2534 * @return int
2536 function find_day_in_month($startday, $weekday, $month, $year) {
2537 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2539 $daysinmonth = days_in_month($month, $year);
2540 $daysinweek = count($calendartype->get_weekdays());
2542 if ($weekday == -1) {
2543 // Don't care about weekday, so return:
2544 // abs($startday) if $startday != -1
2545 // $daysinmonth otherwise.
2546 return ($startday == -1) ? $daysinmonth : abs($startday);
2549 // From now on we 're looking for a specific weekday.
2550 // Give "end of month" its actual value, since we know it.
2551 if ($startday == -1) {
2552 $startday = -1 * $daysinmonth;
2555 // Starting from day $startday, the sign is the direction.
2556 if ($startday < 1) {
2557 $startday = abs($startday);
2558 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2560 // This is the last such weekday of the month.
2561 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2562 if ($lastinmonth > $daysinmonth) {
2563 $lastinmonth -= $daysinweek;
2566 // Find the first such weekday <= $startday.
2567 while ($lastinmonth > $startday) {
2568 $lastinmonth -= $daysinweek;
2571 return $lastinmonth;
2572 } else {
2573 $indexweekday = dayofweek($startday, $month, $year);
2575 $diff = $weekday - $indexweekday;
2576 if ($diff < 0) {
2577 $diff += $daysinweek;
2580 // This is the first such weekday of the month equal to or after $startday.
2581 $firstfromindex = $startday + $diff;
2583 return $firstfromindex;
2588 * Calculate the number of days in a given month
2590 * @package core
2591 * @category time
2592 * @param int $month The month whose day count is sought
2593 * @param int $year The year of the month whose day count is sought
2594 * @return int
2596 function days_in_month($month, $year) {
2597 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2598 return $calendartype->get_num_days_in_month($year, $month);
2602 * Calculate the position in the week of a specific calendar day
2604 * @package core
2605 * @category time
2606 * @param int $day The day of the date whose position in the week is sought
2607 * @param int $month The month of the date whose position in the week is sought
2608 * @param int $year The year of the date whose position in the week is sought
2609 * @return int
2611 function dayofweek($day, $month, $year) {
2612 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2613 return $calendartype->get_weekday($year, $month, $day);
2616 // USER AUTHENTICATION AND LOGIN.
2619 * Returns full login url.
2621 * Any form submissions for authentication to this URL must include username,
2622 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2624 * @return string login url
2626 function get_login_url() {
2627 global $CFG;
2629 return "$CFG->wwwroot/login/index.php";
2633 * This function checks that the current user is logged in and has the
2634 * required privileges
2636 * This function checks that the current user is logged in, and optionally
2637 * whether they are allowed to be in a particular course and view a particular
2638 * course module.
2639 * If they are not logged in, then it redirects them to the site login unless
2640 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2641 * case they are automatically logged in as guests.
2642 * If $courseid is given and the user is not enrolled in that course then the
2643 * user is redirected to the course enrolment page.
2644 * If $cm is given and the course module is hidden and the user is not a teacher
2645 * in the course then the user is redirected to the course home page.
2647 * When $cm parameter specified, this function sets page layout to 'module'.
2648 * You need to change it manually later if some other layout needed.
2650 * @package core_access
2651 * @category access
2653 * @param mixed $courseorid id of the course or course object
2654 * @param bool $autologinguest default true
2655 * @param object $cm course module object
2656 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2657 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2658 * in order to keep redirects working properly. MDL-14495
2659 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2660 * @return mixed Void, exit, and die depending on path
2661 * @throws coding_exception
2662 * @throws require_login_exception
2663 * @throws moodle_exception
2665 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2666 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2668 // Must not redirect when byteserving already started.
2669 if (!empty($_SERVER['HTTP_RANGE'])) {
2670 $preventredirect = true;
2673 if (AJAX_SCRIPT) {
2674 // We cannot redirect for AJAX scripts either.
2675 $preventredirect = true;
2678 // Setup global $COURSE, themes, language and locale.
2679 if (!empty($courseorid)) {
2680 if (is_object($courseorid)) {
2681 $course = $courseorid;
2682 } else if ($courseorid == SITEID) {
2683 $course = clone($SITE);
2684 } else {
2685 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2687 if ($cm) {
2688 if ($cm->course != $course->id) {
2689 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2691 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2692 if (!($cm instanceof cm_info)) {
2693 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2694 // db queries so this is not really a performance concern, however it is obviously
2695 // better if you use get_fast_modinfo to get the cm before calling this.
2696 $modinfo = get_fast_modinfo($course);
2697 $cm = $modinfo->get_cm($cm->id);
2700 } else {
2701 // Do not touch global $COURSE via $PAGE->set_course(),
2702 // the reasons is we need to be able to call require_login() at any time!!
2703 $course = $SITE;
2704 if ($cm) {
2705 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2709 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2710 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2711 // risk leading the user back to the AJAX request URL.
2712 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2713 $setwantsurltome = false;
2716 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2717 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2718 if ($preventredirect) {
2719 throw new require_login_session_timeout_exception();
2720 } else {
2721 if ($setwantsurltome) {
2722 $SESSION->wantsurl = qualified_me();
2724 redirect(get_login_url());
2728 // If the user is not even logged in yet then make sure they are.
2729 if (!isloggedin()) {
2730 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2731 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2732 // Misconfigured site guest, just redirect to login page.
2733 redirect(get_login_url());
2734 exit; // Never reached.
2736 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2737 complete_user_login($guest);
2738 $USER->autologinguest = true;
2739 $SESSION->lang = $lang;
2740 } else {
2741 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2742 if ($preventredirect) {
2743 throw new require_login_exception('You are not logged in');
2746 if ($setwantsurltome) {
2747 $SESSION->wantsurl = qualified_me();
2750 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2751 $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
2752 foreach($authsequence as $authname) {
2753 $authplugin = get_auth_plugin($authname);
2754 $authplugin->pre_loginpage_hook();
2755 if (isloggedin()) {
2756 if ($cm) {
2757 $modinfo = get_fast_modinfo($course);
2758 $cm = $modinfo->get_cm($cm->id);
2760 set_access_log_user();
2761 break;
2765 // If we're still not logged in then go to the login page
2766 if (!isloggedin()) {
2767 redirect(get_login_url());
2768 exit; // Never reached.
2773 // Loginas as redirection if needed.
2774 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2775 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2776 if ($USER->loginascontext->instanceid != $course->id) {
2777 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2782 // Check whether the user should be changing password (but only if it is REALLY them).
2783 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2784 $userauth = get_auth_plugin($USER->auth);
2785 if ($userauth->can_change_password() and !$preventredirect) {
2786 if ($setwantsurltome) {
2787 $SESSION->wantsurl = qualified_me();
2789 if ($changeurl = $userauth->change_password_url()) {
2790 // Use plugin custom url.
2791 redirect($changeurl);
2792 } else {
2793 // Use moodle internal method.
2794 redirect($CFG->wwwroot .'/login/change_password.php');
2796 } else if ($userauth->can_change_password()) {
2797 throw new moodle_exception('forcepasswordchangenotice');
2798 } else {
2799 throw new moodle_exception('nopasswordchangeforced', 'auth');
2803 // Check that the user account is properly set up. If we can't redirect to
2804 // edit their profile and this is not a WS request, perform just the lax check.
2805 // It will allow them to use filepicker on the profile edit page.
2807 if ($preventredirect && !WS_SERVER) {
2808 $usernotfullysetup = user_not_fully_set_up($USER, false);
2809 } else {
2810 $usernotfullysetup = user_not_fully_set_up($USER, true);
2813 if ($usernotfullysetup) {
2814 if ($preventredirect) {
2815 throw new moodle_exception('usernotfullysetup');
2817 if ($setwantsurltome) {
2818 $SESSION->wantsurl = qualified_me();
2820 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2823 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2824 sesskey();
2826 if (\core\session\manager::is_loggedinas()) {
2827 // During a "logged in as" session we should force all content to be cleaned because the
2828 // logged in user will be viewing potentially malicious user generated content.
2829 // See MDL-63786 for more details.
2830 $CFG->forceclean = true;
2833 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2835 // Do not bother admins with any formalities, except for activities pending deletion.
2836 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2837 // Set the global $COURSE.
2838 if ($cm) {
2839 $PAGE->set_cm($cm, $course);
2840 $PAGE->set_pagelayout('incourse');
2841 } else if (!empty($courseorid)) {
2842 $PAGE->set_course($course);
2844 // Set accesstime or the user will appear offline which messes up messaging.
2845 // Do not update access time for webservice or ajax requests.
2846 if (!WS_SERVER && !AJAX_SCRIPT) {
2847 user_accesstime_log($course->id);
2850 foreach ($afterlogins as $plugintype => $plugins) {
2851 foreach ($plugins as $pluginfunction) {
2852 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2855 return;
2858 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2859 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2860 if (!defined('NO_SITEPOLICY_CHECK')) {
2861 define('NO_SITEPOLICY_CHECK', false);
2864 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2865 // Do not test if the script explicitly asked for skipping the site policies check.
2866 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2867 $manager = new \core_privacy\local\sitepolicy\manager();
2868 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2869 if ($preventredirect) {
2870 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2872 if ($setwantsurltome) {
2873 $SESSION->wantsurl = qualified_me();
2875 redirect($policyurl);
2879 // Fetch the system context, the course context, and prefetch its child contexts.
2880 $sysctx = context_system::instance();
2881 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2882 if ($cm) {
2883 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2884 } else {
2885 $cmcontext = null;
2888 // If the site is currently under maintenance, then print a message.
2889 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2890 if ($preventredirect) {
2891 throw new require_login_exception('Maintenance in progress');
2893 $PAGE->set_context(null);
2894 print_maintenance_message();
2897 // Make sure the course itself is not hidden.
2898 if ($course->id == SITEID) {
2899 // Frontpage can not be hidden.
2900 } else {
2901 if (is_role_switched($course->id)) {
2902 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2903 } else {
2904 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2905 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2906 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2907 if ($preventredirect) {
2908 throw new require_login_exception('Course is hidden');
2910 $PAGE->set_context(null);
2911 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2912 // the navigation will mess up when trying to find it.
2913 navigation_node::override_active_url(new moodle_url('/'));
2914 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2919 // Is the user enrolled?
2920 if ($course->id == SITEID) {
2921 // Everybody is enrolled on the frontpage.
2922 } else {
2923 if (\core\session\manager::is_loggedinas()) {
2924 // Make sure the REAL person can access this course first.
2925 $realuser = \core\session\manager::get_realuser();
2926 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2927 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2928 if ($preventredirect) {
2929 throw new require_login_exception('Invalid course login-as access');
2931 $PAGE->set_context(null);
2932 echo $OUTPUT->header();
2933 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2937 $access = false;
2939 if (is_role_switched($course->id)) {
2940 // Ok, user had to be inside this course before the switch.
2941 $access = true;
2943 } else if (is_viewing($coursecontext, $USER)) {
2944 // Ok, no need to mess with enrol.
2945 $access = true;
2947 } else {
2948 if (isset($USER->enrol['enrolled'][$course->id])) {
2949 if ($USER->enrol['enrolled'][$course->id] > time()) {
2950 $access = true;
2951 if (isset($USER->enrol['tempguest'][$course->id])) {
2952 unset($USER->enrol['tempguest'][$course->id]);
2953 remove_temp_course_roles($coursecontext);
2955 } else {
2956 // Expired.
2957 unset($USER->enrol['enrolled'][$course->id]);
2960 if (isset($USER->enrol['tempguest'][$course->id])) {
2961 if ($USER->enrol['tempguest'][$course->id] == 0) {
2962 $access = true;
2963 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2964 $access = true;
2965 } else {
2966 // Expired.
2967 unset($USER->enrol['tempguest'][$course->id]);
2968 remove_temp_course_roles($coursecontext);
2972 if (!$access) {
2973 // Cache not ok.
2974 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2975 if ($until !== false) {
2976 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2977 if ($until == 0) {
2978 $until = ENROL_MAX_TIMESTAMP;
2980 $USER->enrol['enrolled'][$course->id] = $until;
2981 $access = true;
2983 } else if (core_course_category::can_view_course_info($course)) {
2984 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2985 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2986 $enrols = enrol_get_plugins(true);
2987 // First ask all enabled enrol instances in course if they want to auto enrol user.
2988 foreach ($instances as $instance) {
2989 if (!isset($enrols[$instance->enrol])) {
2990 continue;
2992 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2993 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2994 if ($until !== false) {
2995 if ($until == 0) {
2996 $until = ENROL_MAX_TIMESTAMP;
2998 $USER->enrol['enrolled'][$course->id] = $until;
2999 $access = true;
3000 break;
3003 // If not enrolled yet try to gain temporary guest access.
3004 if (!$access) {
3005 foreach ($instances as $instance) {
3006 if (!isset($enrols[$instance->enrol])) {
3007 continue;
3009 // Get a duration for the guest access, a timestamp in the future or false.
3010 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3011 if ($until !== false and $until > time()) {
3012 $USER->enrol['tempguest'][$course->id] = $until;
3013 $access = true;
3014 break;
3018 } else {
3019 // User is not enrolled and is not allowed to browse courses here.
3020 if ($preventredirect) {
3021 throw new require_login_exception('Course is not available');
3023 $PAGE->set_context(null);
3024 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3025 // the navigation will mess up when trying to find it.
3026 navigation_node::override_active_url(new moodle_url('/'));
3027 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3032 if (!$access) {
3033 if ($preventredirect) {
3034 throw new require_login_exception('Not enrolled');
3036 if ($setwantsurltome) {
3037 $SESSION->wantsurl = qualified_me();
3039 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3043 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3044 if ($cm && $cm->deletioninprogress) {
3045 if ($preventredirect) {
3046 throw new moodle_exception('activityisscheduledfordeletion');
3048 require_once($CFG->dirroot . '/course/lib.php');
3049 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3052 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3053 if ($cm && !$cm->uservisible) {
3054 if ($preventredirect) {
3055 throw new require_login_exception('Activity is hidden');
3057 // Get the error message that activity is not available and why (if explanation can be shown to the user).
3058 $PAGE->set_course($course);
3059 $renderer = $PAGE->get_renderer('course');
3060 $message = $renderer->course_section_cm_unavailable_error_message($cm);
3061 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
3064 // Set the global $COURSE.
3065 if ($cm) {
3066 $PAGE->set_cm($cm, $course);
3067 $PAGE->set_pagelayout('incourse');
3068 } else if (!empty($courseorid)) {
3069 $PAGE->set_course($course);
3072 foreach ($afterlogins as $plugintype => $plugins) {
3073 foreach ($plugins as $pluginfunction) {
3074 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3078 // Finally access granted, update lastaccess times.
3079 // Do not update access time for webservice or ajax requests.
3080 if (!WS_SERVER && !AJAX_SCRIPT) {
3081 user_accesstime_log($course->id);
3086 * A convenience function for where we must be logged in as admin
3087 * @return void
3089 function require_admin() {
3090 require_login(null, false);
3091 require_capability('moodle/site:config', context_system::instance());
3095 * This function just makes sure a user is logged out.
3097 * @package core_access
3098 * @category access
3100 function require_logout() {
3101 global $USER, $DB;
3103 if (!isloggedin()) {
3104 // This should not happen often, no need for hooks or events here.
3105 \core\session\manager::terminate_current();
3106 return;
3109 // Execute hooks before action.
3110 $authplugins = array();
3111 $authsequence = get_enabled_auth_plugins();
3112 foreach ($authsequence as $authname) {
3113 $authplugins[$authname] = get_auth_plugin($authname);
3114 $authplugins[$authname]->prelogout_hook();
3117 // Store info that gets removed during logout.
3118 $sid = session_id();
3119 $event = \core\event\user_loggedout::create(
3120 array(
3121 'userid' => $USER->id,
3122 'objectid' => $USER->id,
3123 'other' => array('sessionid' => $sid),
3126 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3127 $event->add_record_snapshot('sessions', $session);
3130 // Clone of $USER object to be used by auth plugins.
3131 $user = fullclone($USER);
3133 // Delete session record and drop $_SESSION content.
3134 \core\session\manager::terminate_current();
3136 // Trigger event AFTER action.
3137 $event->trigger();
3139 // Hook to execute auth plugins redirection after event trigger.
3140 foreach ($authplugins as $authplugin) {
3141 $authplugin->postlogout_hook($user);
3146 * Weaker version of require_login()
3148 * This is a weaker version of {@link require_login()} which only requires login
3149 * when called from within a course rather than the site page, unless
3150 * the forcelogin option is turned on.
3151 * @see require_login()
3153 * @package core_access
3154 * @category access
3156 * @param mixed $courseorid The course object or id in question
3157 * @param bool $autologinguest Allow autologin guests if that is wanted
3158 * @param object $cm Course activity module if known
3159 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3160 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3161 * in order to keep redirects working properly. MDL-14495
3162 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3163 * @return void
3164 * @throws coding_exception
3166 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3167 global $CFG, $PAGE, $SITE;
3168 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3169 or (!is_object($courseorid) and $courseorid == SITEID));
3170 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3171 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3172 // db queries so this is not really a performance concern, however it is obviously
3173 // better if you use get_fast_modinfo to get the cm before calling this.
3174 if (is_object($courseorid)) {
3175 $course = $courseorid;
3176 } else {
3177 $course = clone($SITE);
3179 $modinfo = get_fast_modinfo($course);
3180 $cm = $modinfo->get_cm($cm->id);
3182 if (!empty($CFG->forcelogin)) {
3183 // Login required for both SITE and courses.
3184 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3186 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3187 // Always login for hidden activities.
3188 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3190 } else if (isloggedin() && !isguestuser()) {
3191 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3192 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3194 } else if ($issite) {
3195 // Login for SITE not required.
3196 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3197 if (!empty($courseorid)) {
3198 if (is_object($courseorid)) {
3199 $course = $courseorid;
3200 } else {
3201 $course = clone $SITE;
3203 if ($cm) {
3204 if ($cm->course != $course->id) {
3205 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3207 $PAGE->set_cm($cm, $course);
3208 $PAGE->set_pagelayout('incourse');
3209 } else {
3210 $PAGE->set_course($course);
3212 } else {
3213 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3214 $PAGE->set_course($PAGE->course);
3216 // Do not update access time for webservice or ajax requests.
3217 if (!WS_SERVER && !AJAX_SCRIPT) {
3218 user_accesstime_log(SITEID);
3220 return;
3222 } else {
3223 // Course login always required.
3224 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3229 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3231 * @param string $keyvalue the key value
3232 * @param string $script unique script identifier
3233 * @param int $instance instance id
3234 * @return stdClass the key entry in the user_private_key table
3235 * @since Moodle 3.2
3236 * @throws moodle_exception
3238 function validate_user_key($keyvalue, $script, $instance) {
3239 global $DB;
3241 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3242 print_error('invalidkey');
3245 if (!empty($key->validuntil) and $key->validuntil < time()) {
3246 print_error('expiredkey');
3249 if ($key->iprestriction) {
3250 $remoteaddr = getremoteaddr(null);
3251 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3252 print_error('ipmismatch');
3255 return $key;
3259 * Require key login. Function terminates with error if key not found or incorrect.
3261 * @uses NO_MOODLE_COOKIES
3262 * @uses PARAM_ALPHANUM
3263 * @param string $script unique script identifier
3264 * @param int $instance optional instance id
3265 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3266 * @return int Instance ID
3268 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3269 global $DB;
3271 if (!NO_MOODLE_COOKIES) {
3272 print_error('sessioncookiesdisable');
3275 // Extra safety.
3276 \core\session\manager::write_close();
3278 if (null === $keyvalue) {
3279 $keyvalue = required_param('key', PARAM_ALPHANUM);
3282 $key = validate_user_key($keyvalue, $script, $instance);
3284 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3285 print_error('invaliduserid');
3288 core_user::require_active_user($user, true, true);
3290 // Emulate normal session.
3291 enrol_check_plugins($user);
3292 \core\session\manager::set_user($user);
3294 // Note we are not using normal login.
3295 if (!defined('USER_KEY_LOGIN')) {
3296 define('USER_KEY_LOGIN', true);
3299 // Return instance id - it might be empty.
3300 return $key->instance;
3304 * Creates a new private user access key.
3306 * @param string $script unique target identifier
3307 * @param int $userid
3308 * @param int $instance optional instance id
3309 * @param string $iprestriction optional ip restricted access
3310 * @param int $validuntil key valid only until given data
3311 * @return string access key value
3313 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3314 global $DB;
3316 $key = new stdClass();
3317 $key->script = $script;
3318 $key->userid = $userid;
3319 $key->instance = $instance;
3320 $key->iprestriction = $iprestriction;
3321 $key->validuntil = $validuntil;
3322 $key->timecreated = time();
3324 // Something long and unique.
3325 $key->value = md5($userid.'_'.time().random_string(40));
3326 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3327 // Must be unique.
3328 $key->value = md5($userid.'_'.time().random_string(40));
3330 $DB->insert_record('user_private_key', $key);
3331 return $key->value;
3335 * Delete the user's new private user access keys for a particular script.
3337 * @param string $script unique target identifier
3338 * @param int $userid
3339 * @return void
3341 function delete_user_key($script, $userid) {
3342 global $DB;
3343 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3347 * Gets a private user access key (and creates one if one doesn't exist).
3349 * @param string $script unique target identifier
3350 * @param int $userid
3351 * @param int $instance optional instance id
3352 * @param string $iprestriction optional ip restricted access
3353 * @param int $validuntil key valid only until given date
3354 * @return string access key value
3356 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3357 global $DB;
3359 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3360 'instance' => $instance, 'iprestriction' => $iprestriction,
3361 'validuntil' => $validuntil))) {
3362 return $key->value;
3363 } else {
3364 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3370 * Modify the user table by setting the currently logged in user's last login to now.
3372 * @return bool Always returns true
3374 function update_user_login_times() {
3375 global $USER, $DB, $SESSION;
3377 if (isguestuser()) {
3378 // Do not update guest access times/ips for performance.
3379 return true;
3382 $now = time();
3384 $user = new stdClass();
3385 $user->id = $USER->id;
3387 // Make sure all users that logged in have some firstaccess.
3388 if ($USER->firstaccess == 0) {
3389 $USER->firstaccess = $user->firstaccess = $now;
3392 // Store the previous current as lastlogin.
3393 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3395 $USER->currentlogin = $user->currentlogin = $now;
3397 // Function user_accesstime_log() may not update immediately, better do it here.
3398 $USER->lastaccess = $user->lastaccess = $now;
3399 $SESSION->userpreviousip = $USER->lastip;
3400 $USER->lastip = $user->lastip = getremoteaddr();
3402 // Note: do not call user_update_user() here because this is part of the login process,
3403 // the login event means that these fields were updated.
3404 $DB->update_record('user', $user);
3405 return true;
3409 * Determines if a user has completed setting up their account.
3411 * The lax mode (with $strict = false) has been introduced for special cases
3412 * only where we want to skip certain checks intentionally. This is valid in
3413 * certain mnet or ajax scenarios when the user cannot / should not be
3414 * redirected to edit their profile. In most cases, you should perform the
3415 * strict check.
3417 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3418 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3419 * @return bool
3421 function user_not_fully_set_up($user, $strict = true) {
3422 global $CFG;
3423 require_once($CFG->dirroot.'/user/profile/lib.php');
3425 if (isguestuser($user)) {
3426 return false;
3429 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3430 return true;
3433 if ($strict) {
3434 if (empty($user->id)) {
3435 // Strict mode can be used with existing accounts only.
3436 return true;
3438 if (!profile_has_required_custom_fields_set($user->id)) {
3439 return true;
3443 return false;
3447 * Check whether the user has exceeded the bounce threshold
3449 * @param stdClass $user A {@link $USER} object
3450 * @return bool true => User has exceeded bounce threshold
3452 function over_bounce_threshold($user) {
3453 global $CFG, $DB;
3455 if (empty($CFG->handlebounces)) {
3456 return false;
3459 if (empty($user->id)) {
3460 // No real (DB) user, nothing to do here.
3461 return false;
3464 // Set sensible defaults.
3465 if (empty($CFG->minbounces)) {
3466 $CFG->minbounces = 10;
3468 if (empty($CFG->bounceratio)) {
3469 $CFG->bounceratio = .20;
3471 $bouncecount = 0;
3472 $sendcount = 0;
3473 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3474 $bouncecount = $bounce->value;
3476 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3477 $sendcount = $send->value;
3479 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3483 * Used to increment or reset email sent count
3485 * @param stdClass $user object containing an id
3486 * @param bool $reset will reset the count to 0
3487 * @return void
3489 function set_send_count($user, $reset=false) {
3490 global $DB;
3492 if (empty($user->id)) {
3493 // No real (DB) user, nothing to do here.
3494 return;
3497 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3498 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3499 $DB->update_record('user_preferences', $pref);
3500 } else if (!empty($reset)) {
3501 // If it's not there and we're resetting, don't bother. Make a new one.
3502 $pref = new stdClass();
3503 $pref->name = 'email_send_count';
3504 $pref->value = 1;
3505 $pref->userid = $user->id;
3506 $DB->insert_record('user_preferences', $pref, false);
3511 * Increment or reset user's email bounce count
3513 * @param stdClass $user object containing an id
3514 * @param bool $reset will reset the count to 0
3516 function set_bounce_count($user, $reset=false) {
3517 global $DB;
3519 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3520 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3521 $DB->update_record('user_preferences', $pref);
3522 } else if (!empty($reset)) {
3523 // If it's not there and we're resetting, don't bother. Make a new one.
3524 $pref = new stdClass();
3525 $pref->name = 'email_bounce_count';
3526 $pref->value = 1;
3527 $pref->userid = $user->id;
3528 $DB->insert_record('user_preferences', $pref, false);
3533 * Determines if the logged in user is currently moving an activity
3535 * @param int $courseid The id of the course being tested
3536 * @return bool
3538 function ismoving($courseid) {
3539 global $USER;
3541 if (!empty($USER->activitycopy)) {
3542 return ($USER->activitycopycourse == $courseid);
3544 return false;
3548 * Returns a persons full name
3550 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3551 * The result may depend on system settings or language. 'override' will force the alternativefullnameformat to be used. In
3552 * English, fullname as well as alternativefullnameformat is set to 'firstname lastname' by default. But you could have
3553 * fullname set to 'firstname lastname' and alternativefullnameformat set to 'firstname middlename alternatename lastname'.
3555 * @param stdClass $user A {@link $USER} object to get full name of.
3556 * @param bool $override If true then the alternativefullnameformat format rather than fullnamedisplay format will be used.
3557 * @return string
3559 function fullname($user, $override=false) {
3560 global $CFG, $SESSION;
3562 if (!isset($user->firstname) and !isset($user->lastname)) {
3563 return '';
3566 // Get all of the name fields.
3567 $allnames = \core_user\fields::get_name_fields();
3568 if ($CFG->debugdeveloper) {
3569 foreach ($allnames as $allname) {
3570 if (!property_exists($user, $allname)) {
3571 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3572 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3573 // Message has been sent, no point in sending the message multiple times.
3574 break;
3579 if (!$override) {
3580 if (!empty($CFG->forcefirstname)) {
3581 $user->firstname = $CFG->forcefirstname;
3583 if (!empty($CFG->forcelastname)) {
3584 $user->lastname = $CFG->forcelastname;
3588 if (!empty($SESSION->fullnamedisplay)) {
3589 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3592 $template = null;
3593 // If the fullnamedisplay setting is available, set the template to that.
3594 if (isset($CFG->fullnamedisplay)) {
3595 $template = $CFG->fullnamedisplay;
3597 // If the template is empty, or set to language, return the language string.
3598 if ((empty($template) || $template == 'language') && !$override) {
3599 return get_string('fullnamedisplay', null, $user);
3602 // Check to see if we are displaying according to the alternative full name format.
3603 if ($override) {
3604 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3605 // Default to show just the user names according to the fullnamedisplay string.
3606 return get_string('fullnamedisplay', null, $user);
3607 } else {
3608 // If the override is true, then change the template to use the complete name.
3609 $template = $CFG->alternativefullnameformat;
3613 $requirednames = array();
3614 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3615 foreach ($allnames as $allname) {
3616 if (strpos($template, $allname) !== false) {
3617 $requirednames[] = $allname;
3621 $displayname = $template;
3622 // Switch in the actual data into the template.
3623 foreach ($requirednames as $altname) {
3624 if (isset($user->$altname)) {
3625 // Using empty() on the below if statement causes breakages.
3626 if ((string)$user->$altname == '') {
3627 $displayname = str_replace($altname, 'EMPTY', $displayname);
3628 } else {
3629 $displayname = str_replace($altname, $user->$altname, $displayname);
3631 } else {
3632 $displayname = str_replace($altname, 'EMPTY', $displayname);
3635 // Tidy up any misc. characters (Not perfect, but gets most characters).
3636 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3637 // katakana and parenthesis.
3638 $patterns = array();
3639 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3640 // filled in by a user.
3641 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3642 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3643 // This regular expression is to remove any double spaces in the display name.
3644 $patterns[] = '/\s{2,}/u';
3645 foreach ($patterns as $pattern) {
3646 $displayname = preg_replace($pattern, ' ', $displayname);
3649 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3650 $displayname = trim($displayname);
3651 if (empty($displayname)) {
3652 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3653 // people in general feel is a good setting to fall back on.
3654 $displayname = $user->firstname;
3656 return $displayname;
3660 * Reduces lines of duplicated code for getting user name fields.
3662 * See also {@link user_picture::unalias()}
3664 * @param object $addtoobject Object to add user name fields to.
3665 * @param object $secondobject Object that contains user name field information.
3666 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3667 * @param array $additionalfields Additional fields to be matched with data in the second object.
3668 * The key can be set to the user table field name.
3669 * @return object User name fields.
3671 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3672 $fields = [];
3673 foreach (\core_user\fields::get_name_fields() as $field) {
3674 $fields[$field] = $prefix . $field;
3676 if ($additionalfields) {
3677 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3678 // the key is a number and then sets the key to the array value.
3679 foreach ($additionalfields as $key => $value) {
3680 if (is_numeric($key)) {
3681 $additionalfields[$value] = $prefix . $value;
3682 unset($additionalfields[$key]);
3683 } else {
3684 $additionalfields[$key] = $prefix . $value;
3687 $fields = array_merge($fields, $additionalfields);
3689 foreach ($fields as $key => $field) {
3690 // Important that we have all of the user name fields present in the object that we are sending back.
3691 $addtoobject->$key = '';
3692 if (isset($secondobject->$field)) {
3693 $addtoobject->$key = $secondobject->$field;
3696 return $addtoobject;
3700 * Returns an array of values in order of occurance in a provided string.
3701 * The key in the result is the character postion in the string.
3703 * @param array $values Values to be found in the string format
3704 * @param string $stringformat The string which may contain values being searched for.
3705 * @return array An array of values in order according to placement in the string format.
3707 function order_in_string($values, $stringformat) {
3708 $valuearray = array();
3709 foreach ($values as $value) {
3710 $pattern = "/$value\b/";
3711 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3712 if (preg_match($pattern, $stringformat)) {
3713 $replacement = "thing";
3714 // Replace the value with something more unique to ensure we get the right position when using strpos().
3715 $newformat = preg_replace($pattern, $replacement, $stringformat);
3716 $position = strpos($newformat, $replacement);
3717 $valuearray[$position] = $value;
3720 ksort($valuearray);
3721 return $valuearray;
3725 * Returns whether a given authentication plugin exists.
3727 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3728 * @return boolean Whether the plugin is available.
3730 function exists_auth_plugin($auth) {
3731 global $CFG;
3733 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3734 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3736 return false;
3740 * Checks if a given plugin is in the list of enabled authentication plugins.
3742 * @param string $auth Authentication plugin.
3743 * @return boolean Whether the plugin is enabled.
3745 function is_enabled_auth($auth) {
3746 if (empty($auth)) {
3747 return false;
3750 $enabled = get_enabled_auth_plugins();
3752 return in_array($auth, $enabled);
3756 * Returns an authentication plugin instance.
3758 * @param string $auth name of authentication plugin
3759 * @return auth_plugin_base An instance of the required authentication plugin.
3761 function get_auth_plugin($auth) {
3762 global $CFG;
3764 // Check the plugin exists first.
3765 if (! exists_auth_plugin($auth)) {
3766 print_error('authpluginnotfound', 'debug', '', $auth);
3769 // Return auth plugin instance.
3770 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3771 $class = "auth_plugin_$auth";
3772 return new $class;
3776 * Returns array of active auth plugins.
3778 * @param bool $fix fix $CFG->auth if needed. Only set if logged in as admin.
3779 * @return array
3781 function get_enabled_auth_plugins($fix=false) {
3782 global $CFG;
3784 $default = array('manual', 'nologin');
3786 if (empty($CFG->auth)) {
3787 $auths = array();
3788 } else {
3789 $auths = explode(',', $CFG->auth);
3792 $auths = array_unique($auths);
3793 $oldauthconfig = implode(',', $auths);
3794 foreach ($auths as $k => $authname) {
3795 if (in_array($authname, $default)) {
3796 // The manual and nologin plugin never need to be stored.
3797 unset($auths[$k]);
3798 } else if (!exists_auth_plugin($authname)) {
3799 debugging(get_string('authpluginnotfound', 'debug', $authname));
3800 unset($auths[$k]);
3804 // Ideally only explicit interaction from a human admin should trigger a
3805 // change in auth config, see MDL-70424 for details.
3806 if ($fix) {
3807 $newconfig = implode(',', $auths);
3808 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3809 add_to_config_log('auth', $oldauthconfig, $newconfig, 'core');
3810 set_config('auth', $newconfig);
3814 return (array_merge($default, $auths));
3818 * Returns true if an internal authentication method is being used.
3819 * if method not specified then, global default is assumed
3821 * @param string $auth Form of authentication required
3822 * @return bool
3824 function is_internal_auth($auth) {
3825 // Throws error if bad $auth.
3826 $authplugin = get_auth_plugin($auth);
3827 return $authplugin->is_internal();
3831 * Returns true if the user is a 'restored' one.
3833 * Used in the login process to inform the user and allow him/her to reset the password
3835 * @param string $username username to be checked
3836 * @return bool
3838 function is_restored_user($username) {
3839 global $CFG, $DB;
3841 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3845 * Returns an array of user fields
3847 * @return array User field/column names
3849 function get_user_fieldnames() {
3850 global $DB;
3852 $fieldarray = $DB->get_columns('user');
3853 unset($fieldarray['id']);
3854 $fieldarray = array_keys($fieldarray);
3856 return $fieldarray;
3860 * Returns the string of the language for the new user.
3862 * @return string language for the new user
3864 function get_newuser_language() {
3865 global $CFG, $SESSION;
3866 return (!empty($CFG->autolangusercreation) && !empty($SESSION->lang)) ? $SESSION->lang : $CFG->lang;
3870 * Creates a bare-bones user record
3872 * @todo Outline auth types and provide code example
3874 * @param string $username New user's username to add to record
3875 * @param string $password New user's password to add to record
3876 * @param string $auth Form of authentication required
3877 * @return stdClass A complete user object
3879 function create_user_record($username, $password, $auth = 'manual') {
3880 global $CFG, $DB, $SESSION;
3881 require_once($CFG->dirroot.'/user/profile/lib.php');
3882 require_once($CFG->dirroot.'/user/lib.php');
3884 // Just in case check text case.
3885 $username = trim(core_text::strtolower($username));
3887 $authplugin = get_auth_plugin($auth);
3888 $customfields = $authplugin->get_custom_user_profile_fields();
3889 $newuser = new stdClass();
3890 if ($newinfo = $authplugin->get_userinfo($username)) {
3891 $newinfo = truncate_userinfo($newinfo);
3892 foreach ($newinfo as $key => $value) {
3893 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3894 $newuser->$key = $value;
3899 if (!empty($newuser->email)) {
3900 if (email_is_not_allowed($newuser->email)) {
3901 unset($newuser->email);
3905 if (!isset($newuser->city)) {
3906 $newuser->city = '';
3909 $newuser->auth = $auth;
3910 $newuser->username = $username;
3912 // Fix for MDL-8480
3913 // user CFG lang for user if $newuser->lang is empty
3914 // or $user->lang is not an installed language.
3915 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3916 $newuser->lang = get_newuser_language();
3918 $newuser->confirmed = 1;
3919 $newuser->lastip = getremoteaddr();
3920 $newuser->timecreated = time();
3921 $newuser->timemodified = $newuser->timecreated;
3922 $newuser->mnethostid = $CFG->mnet_localhost_id;
3924 $newuser->id = user_create_user($newuser, false, false);
3926 // Save user profile data.
3927 profile_save_data($newuser);
3929 $user = get_complete_user_data('id', $newuser->id);
3930 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3931 set_user_preference('auth_forcepasswordchange', 1, $user);
3933 // Set the password.
3934 update_internal_user_password($user, $password);
3936 // Trigger event.
3937 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3939 return $user;
3943 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3945 * @param string $username user's username to update the record
3946 * @return stdClass A complete user object
3948 function update_user_record($username) {
3949 global $DB, $CFG;
3950 // Just in case check text case.
3951 $username = trim(core_text::strtolower($username));
3953 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3954 return update_user_record_by_id($oldinfo->id);
3958 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3960 * @param int $id user id
3961 * @return stdClass A complete user object
3963 function update_user_record_by_id($id) {
3964 global $DB, $CFG;
3965 require_once($CFG->dirroot."/user/profile/lib.php");
3966 require_once($CFG->dirroot.'/user/lib.php');
3968 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3969 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3971 $newuser = array();
3972 $userauth = get_auth_plugin($oldinfo->auth);
3974 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3975 $newinfo = truncate_userinfo($newinfo);
3976 $customfields = $userauth->get_custom_user_profile_fields();
3978 foreach ($newinfo as $key => $value) {
3979 $iscustom = in_array($key, $customfields);
3980 if (!$iscustom) {
3981 $key = strtolower($key);
3983 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3984 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3985 // Unknown or must not be changed.
3986 continue;
3988 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
3989 continue;
3991 $confval = $userauth->config->{'field_updatelocal_' . $key};
3992 $lockval = $userauth->config->{'field_lock_' . $key};
3993 if ($confval === 'onlogin') {
3994 // MDL-4207 Don't overwrite modified user profile values with
3995 // empty LDAP values when 'unlocked if empty' is set. The purpose
3996 // of the setting 'unlocked if empty' is to allow the user to fill
3997 // in a value for the selected field _if LDAP is giving
3998 // nothing_ for this field. Thus it makes sense to let this value
3999 // stand in until LDAP is giving a value for this field.
4000 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4001 if ($iscustom || (in_array($key, $userauth->userfields) &&
4002 ((string)$oldinfo->$key !== (string)$value))) {
4003 $newuser[$key] = (string)$value;
4008 if ($newuser) {
4009 $newuser['id'] = $oldinfo->id;
4010 $newuser['timemodified'] = time();
4011 user_update_user((object) $newuser, false, false);
4013 // Save user profile data.
4014 profile_save_data((object) $newuser);
4016 // Trigger event.
4017 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4021 return get_complete_user_data('id', $oldinfo->id);
4025 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4027 * @param array $info Array of user properties to truncate if needed
4028 * @return array The now truncated information that was passed in
4030 function truncate_userinfo(array $info) {
4031 // Define the limits.
4032 $limit = array(
4033 'username' => 100,
4034 'idnumber' => 255,
4035 'firstname' => 100,
4036 'lastname' => 100,
4037 'email' => 100,
4038 'phone1' => 20,
4039 'phone2' => 20,
4040 'institution' => 255,
4041 'department' => 255,
4042 'address' => 255,
4043 'city' => 120,
4044 'country' => 2,
4047 // Apply where needed.
4048 foreach (array_keys($info) as $key) {
4049 if (!empty($limit[$key])) {
4050 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4054 return $info;
4058 * Marks user deleted in internal user database and notifies the auth plugin.
4059 * Also unenrols user from all roles and does other cleanup.
4061 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4063 * @param stdClass $user full user object before delete
4064 * @return boolean success
4065 * @throws coding_exception if invalid $user parameter detected
4067 function delete_user(stdClass $user) {
4068 global $CFG, $DB, $SESSION;
4069 require_once($CFG->libdir.'/grouplib.php');
4070 require_once($CFG->libdir.'/gradelib.php');
4071 require_once($CFG->dirroot.'/message/lib.php');
4072 require_once($CFG->dirroot.'/user/lib.php');
4074 // Make sure nobody sends bogus record type as parameter.
4075 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4076 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4079 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4080 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4081 debugging('Attempt to delete unknown user account.');
4082 return false;
4085 // There must be always exactly one guest record, originally the guest account was identified by username only,
4086 // now we use $CFG->siteguest for performance reasons.
4087 if ($user->username === 'guest' or isguestuser($user)) {
4088 debugging('Guest user account can not be deleted.');
4089 return false;
4092 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4093 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4094 if ($user->auth === 'manual' and is_siteadmin($user)) {
4095 debugging('Local administrator accounts can not be deleted.');
4096 return false;
4099 // Allow plugins to use this user object before we completely delete it.
4100 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4101 foreach ($pluginsfunction as $plugintype => $plugins) {
4102 foreach ($plugins as $pluginfunction) {
4103 $pluginfunction($user);
4108 // Keep user record before updating it, as we have to pass this to user_deleted event.
4109 $olduser = clone $user;
4111 // Keep a copy of user context, we need it for event.
4112 $usercontext = context_user::instance($user->id);
4114 // Delete all grades - backup is kept in grade_grades_history table.
4115 grade_user_delete($user->id);
4117 // TODO: remove from cohorts using standard API here.
4119 // Remove user tags.
4120 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4122 // Unconditionally unenrol from all courses.
4123 enrol_user_delete($user);
4125 // Unenrol from all roles in all contexts.
4126 // This might be slow but it is really needed - modules might do some extra cleanup!
4127 role_unassign_all(array('userid' => $user->id));
4129 // Notify the competency subsystem.
4130 \core_competency\api::hook_user_deleted($user->id);
4132 // Now do a brute force cleanup.
4134 // Delete all user events and subscription events.
4135 $DB->delete_records_select('event', 'userid = :userid AND subscriptionid IS NOT NULL', ['userid' => $user->id]);
4137 // Now, delete all calendar subscription from the user.
4138 $DB->delete_records('event_subscriptions', ['userid' => $user->id]);
4140 // Remove from all cohorts.
4141 $DB->delete_records('cohort_members', array('userid' => $user->id));
4143 // Remove from all groups.
4144 $DB->delete_records('groups_members', array('userid' => $user->id));
4146 // Brute force unenrol from all courses.
4147 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4149 // Purge user preferences.
4150 $DB->delete_records('user_preferences', array('userid' => $user->id));
4152 // Purge user extra profile info.
4153 $DB->delete_records('user_info_data', array('userid' => $user->id));
4155 // Purge log of previous password hashes.
4156 $DB->delete_records('user_password_history', array('userid' => $user->id));
4158 // Last course access not necessary either.
4159 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4160 // Remove all user tokens.
4161 $DB->delete_records('external_tokens', array('userid' => $user->id));
4163 // Unauthorise the user for all services.
4164 $DB->delete_records('external_services_users', array('userid' => $user->id));
4166 // Remove users private keys.
4167 $DB->delete_records('user_private_key', array('userid' => $user->id));
4169 // Remove users customised pages.
4170 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4172 // Remove user's oauth2 refresh tokens, if present.
4173 $DB->delete_records('oauth2_refresh_token', array('userid' => $user->id));
4175 // Delete user from $SESSION->bulk_users.
4176 if (isset($SESSION->bulk_users[$user->id])) {
4177 unset($SESSION->bulk_users[$user->id]);
4180 // Force logout - may fail if file based sessions used, sorry.
4181 \core\session\manager::kill_user_sessions($user->id);
4183 // Generate username from email address, or a fake email.
4184 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4186 $deltime = time();
4187 $deltimelength = core_text::strlen((string) $deltime);
4189 // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
4190 $delname = clean_param($delemail, PARAM_USERNAME);
4191 $delname = core_text::substr($delname, 0, 100 - ($deltimelength + 1)) . ".{$deltime}";
4193 // Workaround for bulk deletes of users with the same email address.
4194 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4195 $delname++;
4198 // Mark internal user record as "deleted".
4199 $updateuser = new stdClass();
4200 $updateuser->id = $user->id;
4201 $updateuser->deleted = 1;
4202 $updateuser->username = $delname; // Remember it just in case.
4203 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4204 $updateuser->idnumber = ''; // Clear this field to free it up.
4205 $updateuser->picture = 0;
4206 $updateuser->timemodified = $deltime;
4208 // Don't trigger update event, as user is being deleted.
4209 user_update_user($updateuser, false, false);
4211 // Delete all content associated with the user context, but not the context itself.
4212 $usercontext->delete_content();
4214 // Delete any search data.
4215 \core_search\manager::context_deleted($usercontext);
4217 // Any plugin that needs to cleanup should register this event.
4218 // Trigger event.
4219 $event = \core\event\user_deleted::create(
4220 array(
4221 'objectid' => $user->id,
4222 'relateduserid' => $user->id,
4223 'context' => $usercontext,
4224 'other' => array(
4225 'username' => $user->username,
4226 'email' => $user->email,
4227 'idnumber' => $user->idnumber,
4228 'picture' => $user->picture,
4229 'mnethostid' => $user->mnethostid
4233 $event->add_record_snapshot('user', $olduser);
4234 $event->trigger();
4236 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4237 // should know about this updated property persisted to the user's table.
4238 $user->timemodified = $updateuser->timemodified;
4240 // Notify auth plugin - do not block the delete even when plugin fails.
4241 $authplugin = get_auth_plugin($user->auth);
4242 $authplugin->user_delete($user);
4244 return true;
4248 * Retrieve the guest user object.
4250 * @return stdClass A {@link $USER} object
4252 function guest_user() {
4253 global $CFG, $DB;
4255 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4256 $newuser->confirmed = 1;
4257 $newuser->lang = get_newuser_language();
4258 $newuser->lastip = getremoteaddr();
4261 return $newuser;
4265 * Authenticates a user against the chosen authentication mechanism
4267 * Given a username and password, this function looks them
4268 * up using the currently selected authentication mechanism,
4269 * and if the authentication is successful, it returns a
4270 * valid $user object from the 'user' table.
4272 * Uses auth_ functions from the currently active auth module
4274 * After authenticate_user_login() returns success, you will need to
4275 * log that the user has logged in, and call complete_user_login() to set
4276 * the session up.
4278 * Note: this function works only with non-mnet accounts!
4280 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4281 * @param string $password User's password
4282 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4283 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4284 * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4285 * @return stdClass|false A {@link $USER} object or false if error
4287 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4288 global $CFG, $DB, $PAGE;
4289 require_once("$CFG->libdir/authlib.php");
4291 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4292 // we have found the user
4294 } else if (!empty($CFG->authloginviaemail)) {
4295 if ($email = clean_param($username, PARAM_EMAIL)) {
4296 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4297 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4298 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4299 if (count($users) === 1) {
4300 // Use email for login only if unique.
4301 $user = reset($users);
4302 $user = get_complete_user_data('id', $user->id);
4303 $username = $user->username;
4305 unset($users);
4309 // Make sure this request came from the login form.
4310 if (!\core\session\manager::validate_login_token($logintoken)) {
4311 $failurereason = AUTH_LOGIN_FAILED;
4313 // Trigger login failed event (specifying the ID of the found user, if available).
4314 \core\event\user_login_failed::create([
4315 'userid' => ($user->id ?? 0),
4316 'other' => [
4317 'username' => $username,
4318 'reason' => $failurereason,
4320 ])->trigger();
4322 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4323 return false;
4326 $authsenabled = get_enabled_auth_plugins();
4328 if ($user) {
4329 // Use manual if auth not set.
4330 $auth = empty($user->auth) ? 'manual' : $user->auth;
4332 if (in_array($user->auth, $authsenabled)) {
4333 $authplugin = get_auth_plugin($user->auth);
4334 $authplugin->pre_user_login_hook($user);
4337 if (!empty($user->suspended)) {
4338 $failurereason = AUTH_LOGIN_SUSPENDED;
4340 // Trigger login failed event.
4341 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4342 'other' => array('username' => $username, 'reason' => $failurereason)));
4343 $event->trigger();
4344 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4345 return false;
4347 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4348 // Legacy way to suspend user.
4349 $failurereason = AUTH_LOGIN_SUSPENDED;
4351 // Trigger login failed event.
4352 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4353 'other' => array('username' => $username, 'reason' => $failurereason)));
4354 $event->trigger();
4355 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4356 return false;
4358 $auths = array($auth);
4360 } else {
4361 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4362 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4363 $failurereason = AUTH_LOGIN_NOUSER;
4365 // Trigger login failed event.
4366 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4367 'reason' => $failurereason)));
4368 $event->trigger();
4369 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4370 return false;
4373 // User does not exist.
4374 $auths = $authsenabled;
4375 $user = new stdClass();
4376 $user->id = 0;
4379 if ($ignorelockout) {
4380 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4381 // or this function is called from a SSO script.
4382 } else if ($user->id) {
4383 // Verify login lockout after other ways that may prevent user login.
4384 if (login_is_lockedout($user)) {
4385 $failurereason = AUTH_LOGIN_LOCKOUT;
4387 // Trigger login failed event.
4388 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4389 'other' => array('username' => $username, 'reason' => $failurereason)));
4390 $event->trigger();
4392 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4393 return false;
4395 } else {
4396 // We can not lockout non-existing accounts.
4399 foreach ($auths as $auth) {
4400 $authplugin = get_auth_plugin($auth);
4402 // On auth fail fall through to the next plugin.
4403 if (!$authplugin->user_login($username, $password)) {
4404 continue;
4407 // Before performing login actions, check if user still passes password policy, if admin setting is enabled.
4408 if (!empty($CFG->passwordpolicycheckonlogin)) {
4409 $errmsg = '';
4410 $passed = check_password_policy($password, $errmsg, $user);
4411 if (!$passed) {
4412 // First trigger event for failure.
4413 $failedevent = \core\event\user_password_policy_failed::create_from_user($user);
4414 $failedevent->trigger();
4416 // If able to change password, set flag and move on.
4417 if ($authplugin->can_change_password()) {
4418 // Check if we are on internal change password page, or service is external, don't show notification.
4419 $internalchangeurl = new moodle_url('/login/change_password.php');
4420 if (!($PAGE->has_set_url() && $internalchangeurl->compare($PAGE->url)) && $authplugin->is_internal()) {
4421 \core\notification::error(get_string('passwordpolicynomatch', '', $errmsg));
4423 set_user_preference('auth_forcepasswordchange', 1, $user);
4424 } else if ($authplugin->can_reset_password()) {
4425 // Else force a reset if possible.
4426 \core\notification::error(get_string('forcepasswordresetnotice', '', $errmsg));
4427 redirect(new moodle_url('/login/forgot_password.php'));
4428 } else {
4429 $notifymsg = get_string('forcepasswordresetfailurenotice', '', $errmsg);
4430 // If support page is set, add link for help.
4431 if (!empty($CFG->supportpage)) {
4432 $link = \html_writer::link($CFG->supportpage, $CFG->supportpage);
4433 $link = \html_writer::tag('p', $link);
4434 $notifymsg .= $link;
4437 // If no change or reset is possible, add a notification for user.
4438 \core\notification::error($notifymsg);
4443 // Successful authentication.
4444 if ($user->id) {
4445 // User already exists in database.
4446 if (empty($user->auth)) {
4447 // For some reason auth isn't set yet.
4448 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4449 $user->auth = $auth;
4452 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4453 // the current hash algorithm while we have access to the user's password.
4454 update_internal_user_password($user, $password);
4456 if ($authplugin->is_synchronised_with_external()) {
4457 // Update user record from external DB.
4458 $user = update_user_record_by_id($user->id);
4460 } else {
4461 // The user is authenticated but user creation may be disabled.
4462 if (!empty($CFG->authpreventaccountcreation)) {
4463 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4465 // Trigger login failed event.
4466 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4467 'reason' => $failurereason)));
4468 $event->trigger();
4470 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4471 $_SERVER['HTTP_USER_AGENT']);
4472 return false;
4473 } else {
4474 $user = create_user_record($username, $password, $auth);
4478 $authplugin->sync_roles($user);
4480 foreach ($authsenabled as $hau) {
4481 $hauth = get_auth_plugin($hau);
4482 $hauth->user_authenticated_hook($user, $username, $password);
4485 if (empty($user->id)) {
4486 $failurereason = AUTH_LOGIN_NOUSER;
4487 // Trigger login failed event.
4488 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4489 'reason' => $failurereason)));
4490 $event->trigger();
4491 return false;
4494 if (!empty($user->suspended)) {
4495 // Just in case some auth plugin suspended account.
4496 $failurereason = AUTH_LOGIN_SUSPENDED;
4497 // Trigger login failed event.
4498 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4499 'other' => array('username' => $username, 'reason' => $failurereason)));
4500 $event->trigger();
4501 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4502 return false;
4505 login_attempt_valid($user);
4506 $failurereason = AUTH_LOGIN_OK;
4507 return $user;
4510 // Failed if all the plugins have failed.
4511 if (debugging('', DEBUG_ALL)) {
4512 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4515 if ($user->id) {
4516 login_attempt_failed($user);
4517 $failurereason = AUTH_LOGIN_FAILED;
4518 // Trigger login failed event.
4519 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4520 'other' => array('username' => $username, 'reason' => $failurereason)));
4521 $event->trigger();
4522 } else {
4523 $failurereason = AUTH_LOGIN_NOUSER;
4524 // Trigger login failed event.
4525 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4526 'reason' => $failurereason)));
4527 $event->trigger();
4530 return false;
4534 * Call to complete the user login process after authenticate_user_login()
4535 * has succeeded. It will setup the $USER variable and other required bits
4536 * and pieces.
4538 * NOTE:
4539 * - It will NOT log anything -- up to the caller to decide what to log.
4540 * - this function does not set any cookies any more!
4542 * @param stdClass $user
4543 * @return stdClass A {@link $USER} object - BC only, do not use
4545 function complete_user_login($user) {
4546 global $CFG, $DB, $USER, $SESSION;
4548 \core\session\manager::login_user($user);
4550 // Reload preferences from DB.
4551 unset($USER->preference);
4552 check_user_preferences_loaded($USER);
4554 // Update login times.
4555 update_user_login_times();
4557 // Extra session prefs init.
4558 set_login_session_preferences();
4560 // Trigger login event.
4561 $event = \core\event\user_loggedin::create(
4562 array(
4563 'userid' => $USER->id,
4564 'objectid' => $USER->id,
4565 'other' => array('username' => $USER->username),
4568 $event->trigger();
4570 // Check if the user is using a new browser or session (a new MoodleSession cookie is set in that case).
4571 // If the user is accessing from the same IP, ignore everything (most of the time will be a new session in the same browser).
4572 // Skip Web Service requests, CLI scripts, AJAX scripts, and request from the mobile app itself.
4573 $loginip = getremoteaddr();
4574 $isnewip = isset($SESSION->userpreviousip) && $SESSION->userpreviousip != $loginip;
4575 $isvalidenv = (!WS_SERVER && !CLI_SCRIPT && !NO_MOODLE_COOKIES) || PHPUNIT_TEST;
4577 if (!empty($SESSION->isnewsessioncookie) && $isnewip && $isvalidenv && !\core_useragent::is_moodle_app()) {
4579 $logintime = time();
4580 $ismoodleapp = false;
4581 $useragent = \core_useragent::get_user_agent_string();
4583 // Schedule adhoc task to sent a login notification to the user.
4584 $task = new \core\task\send_login_notifications();
4585 $task->set_userid($USER->id);
4586 $task->set_custom_data(compact('ismoodleapp', 'useragent', 'loginip', 'logintime'));
4587 $task->set_component('core');
4588 \core\task\manager::queue_adhoc_task($task);
4591 // Queue migrating the messaging data, if we need to.
4592 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4593 // Check if there are any legacy messages to migrate.
4594 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4595 \core_message\task\migrate_message_data::queue_task($USER->id);
4596 } else {
4597 set_user_preference('core_message_migrate_data', true, $USER->id);
4601 if (isguestuser()) {
4602 // No need to continue when user is THE guest.
4603 return $USER;
4606 if (CLI_SCRIPT) {
4607 // We can redirect to password change URL only in browser.
4608 return $USER;
4611 // Select password change url.
4612 $userauth = get_auth_plugin($USER->auth);
4614 // Check whether the user should be changing password.
4615 if (get_user_preferences('auth_forcepasswordchange', false)) {
4616 if ($userauth->can_change_password()) {
4617 if ($changeurl = $userauth->change_password_url()) {
4618 redirect($changeurl);
4619 } else {
4620 require_once($CFG->dirroot . '/login/lib.php');
4621 $SESSION->wantsurl = core_login_get_return_url();
4622 redirect($CFG->wwwroot.'/login/change_password.php');
4624 } else {
4625 print_error('nopasswordchangeforced', 'auth');
4628 return $USER;
4632 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4634 * @param string $password String to check.
4635 * @return boolean True if the $password matches the format of an md5 sum.
4637 function password_is_legacy_hash($password) {
4638 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4642 * Compare password against hash stored in user object to determine if it is valid.
4644 * If necessary it also updates the stored hash to the current format.
4646 * @param stdClass $user (Password property may be updated).
4647 * @param string $password Plain text password.
4648 * @return bool True if password is valid.
4650 function validate_internal_user_password($user, $password) {
4651 global $CFG;
4653 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4654 // Internal password is not used at all, it can not validate.
4655 return false;
4658 // If hash isn't a legacy (md5) hash, validate using the library function.
4659 if (!password_is_legacy_hash($user->password)) {
4660 return password_verify($password, $user->password);
4663 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4664 // is valid we can then update it to the new algorithm.
4666 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4667 $validated = false;
4669 if ($user->password === md5($password.$sitesalt)
4670 or $user->password === md5($password)
4671 or $user->password === md5(addslashes($password).$sitesalt)
4672 or $user->password === md5(addslashes($password))) {
4673 // Note: we are intentionally using the addslashes() here because we
4674 // need to accept old password hashes of passwords with magic quotes.
4675 $validated = true;
4677 } else {
4678 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4679 $alt = 'passwordsaltalt'.$i;
4680 if (!empty($CFG->$alt)) {
4681 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4682 $validated = true;
4683 break;
4689 if ($validated) {
4690 // If the password matches the existing md5 hash, update to the
4691 // current hash algorithm while we have access to the user's password.
4692 update_internal_user_password($user, $password);
4695 return $validated;
4699 * Calculate hash for a plain text password.
4701 * @param string $password Plain text password to be hashed.
4702 * @param bool $fasthash If true, use a low cost factor when generating the hash
4703 * This is much faster to generate but makes the hash
4704 * less secure. It is used when lots of hashes need to
4705 * be generated quickly.
4706 * @return string The hashed password.
4708 * @throws moodle_exception If a problem occurs while generating the hash.
4710 function hash_internal_user_password($password, $fasthash = false) {
4711 global $CFG;
4713 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4714 $options = ($fasthash) ? array('cost' => 4) : array();
4716 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4718 if ($generatedhash === false || $generatedhash === null) {
4719 throw new moodle_exception('Failed to generate password hash.');
4722 return $generatedhash;
4726 * Update password hash in user object (if necessary).
4728 * The password is updated if:
4729 * 1. The password has changed (the hash of $user->password is different
4730 * to the hash of $password).
4731 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4732 * md5 algorithm).
4734 * Updating the password will modify the $user object and the database
4735 * record to use the current hashing algorithm.
4736 * It will remove Web Services user tokens too.
4738 * @param stdClass $user User object (password property may be updated).
4739 * @param string $password Plain text password.
4740 * @param bool $fasthash If true, use a low cost factor when generating the hash
4741 * This is much faster to generate but makes the hash
4742 * less secure. It is used when lots of hashes need to
4743 * be generated quickly.
4744 * @return bool Always returns true.
4746 function update_internal_user_password($user, $password, $fasthash = false) {
4747 global $CFG, $DB;
4749 // Figure out what the hashed password should be.
4750 if (!isset($user->auth)) {
4751 debugging('User record in update_internal_user_password() must include field auth',
4752 DEBUG_DEVELOPER);
4753 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4755 $authplugin = get_auth_plugin($user->auth);
4756 if ($authplugin->prevent_local_passwords()) {
4757 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4758 } else {
4759 $hashedpassword = hash_internal_user_password($password, $fasthash);
4762 $algorithmchanged = false;
4764 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4765 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4766 $passwordchanged = ($user->password !== $hashedpassword);
4768 } else if (isset($user->password)) {
4769 // If verification fails then it means the password has changed.
4770 $passwordchanged = !password_verify($password, $user->password);
4771 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4772 } else {
4773 // While creating new user, password in unset in $user object, to avoid
4774 // saving it with user_create()
4775 $passwordchanged = true;
4778 if ($passwordchanged || $algorithmchanged) {
4779 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4780 $user->password = $hashedpassword;
4782 // Trigger event.
4783 $user = $DB->get_record('user', array('id' => $user->id));
4784 \core\event\user_password_updated::create_from_user($user)->trigger();
4786 // Remove WS user tokens.
4787 if (!empty($CFG->passwordchangetokendeletion)) {
4788 require_once($CFG->dirroot.'/webservice/lib.php');
4789 webservice::delete_user_ws_tokens($user->id);
4793 return true;
4797 * Get a complete user record, which includes all the info in the user record.
4799 * Intended for setting as $USER session variable
4801 * @param string $field The user field to be checked for a given value.
4802 * @param string $value The value to match for $field.
4803 * @param int $mnethostid
4804 * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4805 * found. Otherwise, it will just return false.
4806 * @return mixed False, or A {@link $USER} object.
4808 function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4809 global $CFG, $DB;
4811 if (!$field || !$value) {
4812 return false;
4815 // Change the field to lowercase.
4816 $field = core_text::strtolower($field);
4818 // List of case insensitive fields.
4819 $caseinsensitivefields = ['email'];
4821 // Username input is forced to lowercase and should be case sensitive.
4822 if ($field == 'username') {
4823 $value = core_text::strtolower($value);
4826 // Build the WHERE clause for an SQL query.
4827 $params = array('fieldval' => $value);
4829 // Do a case-insensitive query, if necessary. These are generally very expensive. The performance can be improved on some DBs
4830 // such as MySQL by pre-filtering users with accent-insensitive subselect.
4831 if (in_array($field, $caseinsensitivefields)) {
4832 $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4833 $idsubselect = $DB->sql_equal($field, ':fieldval2', false, false);
4834 $params['fieldval2'] = $value;
4835 } else {
4836 $fieldselect = "$field = :fieldval";
4837 $idsubselect = '';
4839 $constraints = "$fieldselect AND deleted <> 1";
4841 // If we are loading user data based on anything other than id,
4842 // we must also restrict our search based on mnet host.
4843 if ($field != 'id') {
4844 if (empty($mnethostid)) {
4845 // If empty, we restrict to local users.
4846 $mnethostid = $CFG->mnet_localhost_id;
4849 if (!empty($mnethostid)) {
4850 $params['mnethostid'] = $mnethostid;
4851 $constraints .= " AND mnethostid = :mnethostid";
4854 if ($idsubselect) {
4855 $constraints .= " AND id IN (SELECT id FROM {user} WHERE {$idsubselect})";
4858 // Get all the basic user data.
4859 try {
4860 // Make sure that there's only a single record that matches our query.
4861 // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4862 // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4863 $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST);
4864 } catch (dml_exception $exception) {
4865 if ($throwexception) {
4866 throw $exception;
4867 } else {
4868 // Return false when no records or multiple records were found.
4869 return false;
4873 // Get various settings and preferences.
4875 // Preload preference cache.
4876 check_user_preferences_loaded($user);
4878 // Load course enrolment related stuff.
4879 $user->lastcourseaccess = array(); // During last session.
4880 $user->currentcourseaccess = array(); // During current session.
4881 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4882 foreach ($lastaccesses as $lastaccess) {
4883 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4887 $sql = "SELECT g.id, g.courseid
4888 FROM {groups} g, {groups_members} gm
4889 WHERE gm.groupid=g.id AND gm.userid=?";
4891 // This is a special hack to speedup calendar display.
4892 $user->groupmember = array();
4893 if (!isguestuser($user)) {
4894 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4895 foreach ($groups as $group) {
4896 if (!array_key_exists($group->courseid, $user->groupmember)) {
4897 $user->groupmember[$group->courseid] = array();
4899 $user->groupmember[$group->courseid][$group->id] = $group->id;
4904 // Add cohort theme.
4905 if (!empty($CFG->allowcohortthemes)) {
4906 require_once($CFG->dirroot . '/cohort/lib.php');
4907 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4908 $user->cohorttheme = $cohorttheme;
4912 // Add the custom profile fields to the user record.
4913 $user->profile = array();
4914 if (!isguestuser($user)) {
4915 require_once($CFG->dirroot.'/user/profile/lib.php');
4916 profile_load_custom_fields($user);
4919 // Rewrite some variables if necessary.
4920 if (!empty($user->description)) {
4921 // No need to cart all of it around.
4922 $user->description = true;
4924 if (isguestuser($user)) {
4925 // Guest language always same as site.
4926 $user->lang = get_newuser_language();
4927 // Name always in current language.
4928 $user->firstname = get_string('guestuser');
4929 $user->lastname = ' ';
4932 return $user;
4936 * Validate a password against the configured password policy
4938 * @param string $password the password to be checked against the password policy
4939 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4940 * @param stdClass $user the user object to perform password validation against. Defaults to null if not provided.
4942 * @return bool true if the password is valid according to the policy. false otherwise.
4944 function check_password_policy($password, &$errmsg, $user = null) {
4945 global $CFG;
4947 if (!empty($CFG->passwordpolicy)) {
4948 $errmsg = '';
4949 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4950 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4952 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4953 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4955 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4956 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4958 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4959 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4961 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4962 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4964 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4965 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4968 // Fire any additional password policy functions from plugins.
4969 // Plugin functions should output an error message string or empty string for success.
4970 $pluginsfunction = get_plugins_with_function('check_password_policy');
4971 foreach ($pluginsfunction as $plugintype => $plugins) {
4972 foreach ($plugins as $pluginfunction) {
4973 $pluginerr = $pluginfunction($password, $user);
4974 if ($pluginerr) {
4975 $errmsg .= '<div>'. $pluginerr .'</div>';
4981 if ($errmsg == '') {
4982 return true;
4983 } else {
4984 return false;
4990 * When logging in, this function is run to set certain preferences for the current SESSION.
4992 function set_login_session_preferences() {
4993 global $SESSION;
4995 $SESSION->justloggedin = true;
4997 unset($SESSION->lang);
4998 unset($SESSION->forcelang);
4999 unset($SESSION->load_navigation_admin);
5004 * Delete a course, including all related data from the database, and any associated files.
5006 * @param mixed $courseorid The id of the course or course object to delete.
5007 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5008 * @return bool true if all the removals succeeded. false if there were any failures. If this
5009 * method returns false, some of the removals will probably have succeeded, and others
5010 * failed, but you have no way of knowing which.
5012 function delete_course($courseorid, $showfeedback = true) {
5013 global $DB;
5015 if (is_object($courseorid)) {
5016 $courseid = $courseorid->id;
5017 $course = $courseorid;
5018 } else {
5019 $courseid = $courseorid;
5020 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
5021 return false;
5024 $context = context_course::instance($courseid);
5026 // Frontpage course can not be deleted!!
5027 if ($courseid == SITEID) {
5028 return false;
5031 // Allow plugins to use this course before we completely delete it.
5032 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
5033 foreach ($pluginsfunction as $plugintype => $plugins) {
5034 foreach ($plugins as $pluginfunction) {
5035 $pluginfunction($course);
5040 // Tell the search manager we are about to delete a course. This prevents us sending updates
5041 // for each individual context being deleted.
5042 \core_search\manager::course_deleting_start($courseid);
5044 $handler = core_course\customfield\course_handler::create();
5045 $handler->delete_instance($courseid);
5047 // Make the course completely empty.
5048 remove_course_contents($courseid, $showfeedback);
5050 // Delete the course and related context instance.
5051 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
5053 $DB->delete_records("course", array("id" => $courseid));
5054 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5056 // Reset all course related caches here.
5057 core_courseformat\base::reset_course_cache($courseid);
5059 // Tell search that we have deleted the course so it can delete course data from the index.
5060 \core_search\manager::course_deleting_finish($courseid);
5062 // Trigger a course deleted event.
5063 $event = \core\event\course_deleted::create(array(
5064 'objectid' => $course->id,
5065 'context' => $context,
5066 'other' => array(
5067 'shortname' => $course->shortname,
5068 'fullname' => $course->fullname,
5069 'idnumber' => $course->idnumber
5072 $event->add_record_snapshot('course', $course);
5073 $event->trigger();
5075 return true;
5079 * Clear a course out completely, deleting all content but don't delete the course itself.
5081 * This function does not verify any permissions.
5083 * Please note this function also deletes all user enrolments,
5084 * enrolment instances and role assignments by default.
5086 * $options:
5087 * - 'keep_roles_and_enrolments' - false by default
5088 * - 'keep_groups_and_groupings' - false by default
5090 * @param int $courseid The id of the course that is being deleted
5091 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5092 * @param array $options extra options
5093 * @return bool true if all the removals succeeded. false if there were any failures. If this
5094 * method returns false, some of the removals will probably have succeeded, and others
5095 * failed, but you have no way of knowing which.
5097 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5098 global $CFG, $DB, $OUTPUT;
5100 require_once($CFG->libdir.'/badgeslib.php');
5101 require_once($CFG->libdir.'/completionlib.php');
5102 require_once($CFG->libdir.'/questionlib.php');
5103 require_once($CFG->libdir.'/gradelib.php');
5104 require_once($CFG->dirroot.'/group/lib.php');
5105 require_once($CFG->dirroot.'/comment/lib.php');
5106 require_once($CFG->dirroot.'/rating/lib.php');
5107 require_once($CFG->dirroot.'/notes/lib.php');
5109 // Handle course badges.
5110 badges_handle_course_deletion($courseid);
5112 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5113 $strdeleted = get_string('deleted').' - ';
5115 // Some crazy wishlist of stuff we should skip during purging of course content.
5116 $options = (array)$options;
5118 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5119 $coursecontext = context_course::instance($courseid);
5120 $fs = get_file_storage();
5122 // Delete course completion information, this has to be done before grades and enrols.
5123 $cc = new completion_info($course);
5124 $cc->clear_criteria();
5125 if ($showfeedback) {
5126 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5129 // Remove all data from gradebook - this needs to be done before course modules
5130 // because while deleting this information, the system may need to reference
5131 // the course modules that own the grades.
5132 remove_course_grades($courseid, $showfeedback);
5133 remove_grade_letters($coursecontext, $showfeedback);
5135 // Delete course blocks in any all child contexts,
5136 // they may depend on modules so delete them first.
5137 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5138 foreach ($childcontexts as $childcontext) {
5139 blocks_delete_all_for_context($childcontext->id);
5141 unset($childcontexts);
5142 blocks_delete_all_for_context($coursecontext->id);
5143 if ($showfeedback) {
5144 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5147 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $courseid]);
5148 rebuild_course_cache($courseid, true);
5150 // Get the list of all modules that are properly installed.
5151 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5153 // Delete every instance of every module,
5154 // this has to be done before deleting of course level stuff.
5155 $locations = core_component::get_plugin_list('mod');
5156 foreach ($locations as $modname => $moddir) {
5157 if ($modname === 'NEWMODULE') {
5158 continue;
5160 if (array_key_exists($modname, $allmodules)) {
5161 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5162 FROM {".$modname."} m
5163 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5164 WHERE m.course = :courseid";
5165 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5166 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5168 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5169 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5171 if ($instances) {
5172 foreach ($instances as $cm) {
5173 if ($cm->id) {
5174 // Delete activity context questions and question categories.
5175 question_delete_activity($cm);
5176 // Notify the competency subsystem.
5177 \core_competency\api::hook_course_module_deleted($cm);
5179 if (function_exists($moddelete)) {
5180 // This purges all module data in related tables, extra user prefs, settings, etc.
5181 $moddelete($cm->modinstance);
5182 } else {
5183 // NOTE: we should not allow installation of modules with missing delete support!
5184 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5185 $DB->delete_records($modname, array('id' => $cm->modinstance));
5188 if ($cm->id) {
5189 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5190 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5191 $DB->delete_records('course_modules_completion', ['coursemoduleid' => $cm->id]);
5192 $DB->delete_records('course_modules', array('id' => $cm->id));
5193 rebuild_course_cache($cm->course, true);
5197 if ($instances and $showfeedback) {
5198 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5200 } else {
5201 // Ooops, this module is not properly installed, force-delete it in the next block.
5205 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5207 // Delete completion defaults.
5208 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5210 // Remove all data from availability and completion tables that is associated
5211 // with course-modules belonging to this course. Note this is done even if the
5212 // features are not enabled now, in case they were enabled previously.
5213 $DB->delete_records_subquery('course_modules_completion', 'coursemoduleid', 'id',
5214 'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
5216 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5217 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5218 $allmodulesbyid = array_flip($allmodules);
5219 foreach ($cms as $cm) {
5220 if (array_key_exists($cm->module, $allmodulesbyid)) {
5221 try {
5222 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5223 } catch (Exception $e) {
5224 // Ignore weird or missing table problems.
5227 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5228 $DB->delete_records('course_modules', array('id' => $cm->id));
5229 rebuild_course_cache($cm->course, true);
5232 if ($showfeedback) {
5233 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5236 // Delete questions and question categories.
5237 question_delete_course($course);
5238 if ($showfeedback) {
5239 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5242 // Delete content bank contents.
5243 $cb = new \core_contentbank\contentbank();
5244 $cbdeleted = $cb->delete_contents($coursecontext);
5245 if ($showfeedback && $cbdeleted) {
5246 echo $OUTPUT->notification($strdeleted.get_string('contentbank', 'contentbank'), 'notifysuccess');
5249 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5250 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5251 foreach ($childcontexts as $childcontext) {
5252 $childcontext->delete();
5254 unset($childcontexts);
5256 // Remove roles and enrolments by default.
5257 if (empty($options['keep_roles_and_enrolments'])) {
5258 // This hack is used in restore when deleting contents of existing course.
5259 // During restore, we should remove only enrolment related data that the user performing the restore has a
5260 // permission to remove.
5261 $userid = $options['userid'] ?? null;
5262 enrol_course_delete($course, $userid);
5263 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5264 if ($showfeedback) {
5265 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5269 // Delete any groups, removing members and grouping/course links first.
5270 if (empty($options['keep_groups_and_groupings'])) {
5271 groups_delete_groupings($course->id, $showfeedback);
5272 groups_delete_groups($course->id, $showfeedback);
5275 // Filters be gone!
5276 filter_delete_all_for_context($coursecontext->id);
5278 // Notes, you shall not pass!
5279 note_delete_all($course->id);
5281 // Die comments!
5282 comment::delete_comments($coursecontext->id);
5284 // Ratings are history too.
5285 $delopt = new stdclass();
5286 $delopt->contextid = $coursecontext->id;
5287 $rm = new rating_manager();
5288 $rm->delete_ratings($delopt);
5290 // Delete course tags.
5291 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5293 // Give the course format the opportunity to remove its obscure data.
5294 $format = course_get_format($course);
5295 $format->delete_format_data();
5297 // Notify the competency subsystem.
5298 \core_competency\api::hook_course_deleted($course);
5300 // Delete calendar events.
5301 $DB->delete_records('event', array('courseid' => $course->id));
5302 $fs->delete_area_files($coursecontext->id, 'calendar');
5304 // Delete all related records in other core tables that may have a courseid
5305 // This array stores the tables that need to be cleared, as
5306 // table_name => column_name that contains the course id.
5307 $tablestoclear = array(
5308 'backup_courses' => 'courseid', // Scheduled backup stuff.
5309 'user_lastaccess' => 'courseid', // User access info.
5311 foreach ($tablestoclear as $table => $col) {
5312 $DB->delete_records($table, array($col => $course->id));
5315 // Delete all course backup files.
5316 $fs->delete_area_files($coursecontext->id, 'backup');
5318 // Cleanup course record - remove links to deleted stuff.
5319 $oldcourse = new stdClass();
5320 $oldcourse->id = $course->id;
5321 $oldcourse->summary = '';
5322 $oldcourse->cacherev = 0;
5323 $oldcourse->legacyfiles = 0;
5324 if (!empty($options['keep_groups_and_groupings'])) {
5325 $oldcourse->defaultgroupingid = 0;
5327 $DB->update_record('course', $oldcourse);
5329 // Delete course sections.
5330 $DB->delete_records('course_sections', array('course' => $course->id));
5332 // Delete legacy, section and any other course files.
5333 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5335 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5336 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5337 // Easy, do not delete the context itself...
5338 $coursecontext->delete_content();
5339 } else {
5340 // Hack alert!!!!
5341 // We can not drop all context stuff because it would bork enrolments and roles,
5342 // there might be also files used by enrol plugins...
5345 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5346 // also some non-standard unsupported plugins may try to store something there.
5347 fulldelete($CFG->dataroot.'/'.$course->id);
5349 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5350 $cachemodinfo = cache::make('core', 'coursemodinfo');
5351 $cachemodinfo->delete($courseid);
5353 // Trigger a course content deleted event.
5354 $event = \core\event\course_content_deleted::create(array(
5355 'objectid' => $course->id,
5356 'context' => $coursecontext,
5357 'other' => array('shortname' => $course->shortname,
5358 'fullname' => $course->fullname,
5359 'options' => $options) // Passing this for legacy reasons.
5361 $event->add_record_snapshot('course', $course);
5362 $event->trigger();
5364 return true;
5368 * Change dates in module - used from course reset.
5370 * @param string $modname forum, assignment, etc
5371 * @param array $fields array of date fields from mod table
5372 * @param int $timeshift time difference
5373 * @param int $courseid
5374 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5375 * @return bool success
5377 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5378 global $CFG, $DB;
5379 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5381 $return = true;
5382 $params = array($timeshift, $courseid);
5383 foreach ($fields as $field) {
5384 $updatesql = "UPDATE {".$modname."}
5385 SET $field = $field + ?
5386 WHERE course=? AND $field<>0";
5387 if ($modid) {
5388 $updatesql .= ' AND id=?';
5389 $params[] = $modid;
5391 $return = $DB->execute($updatesql, $params) && $return;
5394 return $return;
5398 * This function will empty a course of user data.
5399 * It will retain the activities and the structure of the course.
5401 * @param object $data an object containing all the settings including courseid (without magic quotes)
5402 * @return array status array of array component, item, error
5404 function reset_course_userdata($data) {
5405 global $CFG, $DB;
5406 require_once($CFG->libdir.'/gradelib.php');
5407 require_once($CFG->libdir.'/completionlib.php');
5408 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5409 require_once($CFG->dirroot.'/group/lib.php');
5411 $data->courseid = $data->id;
5412 $context = context_course::instance($data->courseid);
5414 $eventparams = array(
5415 'context' => $context,
5416 'courseid' => $data->id,
5417 'other' => array(
5418 'reset_options' => (array) $data
5421 $event = \core\event\course_reset_started::create($eventparams);
5422 $event->trigger();
5424 // Calculate the time shift of dates.
5425 if (!empty($data->reset_start_date)) {
5426 // Time part of course startdate should be zero.
5427 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5428 } else {
5429 $data->timeshift = 0;
5432 // Result array: component, item, error.
5433 $status = array();
5435 // Start the resetting.
5436 $componentstr = get_string('general');
5438 // Move the course start time.
5439 if (!empty($data->reset_start_date) and $data->timeshift) {
5440 // Change course start data.
5441 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5442 // Update all course and group events - do not move activity events.
5443 $updatesql = "UPDATE {event}
5444 SET timestart = timestart + ?
5445 WHERE courseid=? AND instance=0";
5446 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5448 // Update any date activity restrictions.
5449 if ($CFG->enableavailability) {
5450 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5453 // Update completion expected dates.
5454 if ($CFG->enablecompletion) {
5455 $modinfo = get_fast_modinfo($data->courseid);
5456 $changed = false;
5457 foreach ($modinfo->get_cms() as $cm) {
5458 if ($cm->completion && !empty($cm->completionexpected)) {
5459 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5460 array('id' => $cm->id));
5461 $changed = true;
5465 // Clear course cache if changes made.
5466 if ($changed) {
5467 rebuild_course_cache($data->courseid, true);
5470 // Update course date completion criteria.
5471 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5474 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5477 if (!empty($data->reset_end_date)) {
5478 // If the user set a end date value respect it.
5479 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5480 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5481 // If there is a time shift apply it to the end date as well.
5482 $enddate = $data->reset_end_date_old + $data->timeshift;
5483 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5486 if (!empty($data->reset_events)) {
5487 $DB->delete_records('event', array('courseid' => $data->courseid));
5488 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5491 if (!empty($data->reset_notes)) {
5492 require_once($CFG->dirroot.'/notes/lib.php');
5493 note_delete_all($data->courseid);
5494 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5497 if (!empty($data->delete_blog_associations)) {
5498 require_once($CFG->dirroot.'/blog/lib.php');
5499 blog_remove_associations_for_course($data->courseid);
5500 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5503 if (!empty($data->reset_completion)) {
5504 // Delete course and activity completion information.
5505 $course = $DB->get_record('course', array('id' => $data->courseid));
5506 $cc = new completion_info($course);
5507 $cc->delete_all_completion_data();
5508 $status[] = array('component' => $componentstr,
5509 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5512 if (!empty($data->reset_competency_ratings)) {
5513 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5514 $status[] = array('component' => $componentstr,
5515 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5518 $componentstr = get_string('roles');
5520 if (!empty($data->reset_roles_overrides)) {
5521 $children = $context->get_child_contexts();
5522 foreach ($children as $child) {
5523 $child->delete_capabilities();
5525 $context->delete_capabilities();
5526 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5529 if (!empty($data->reset_roles_local)) {
5530 $children = $context->get_child_contexts();
5531 foreach ($children as $child) {
5532 role_unassign_all(array('contextid' => $child->id));
5534 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5537 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5538 $data->unenrolled = array();
5539 if (!empty($data->unenrol_users)) {
5540 $plugins = enrol_get_plugins(true);
5541 $instances = enrol_get_instances($data->courseid, true);
5542 foreach ($instances as $key => $instance) {
5543 if (!isset($plugins[$instance->enrol])) {
5544 unset($instances[$key]);
5545 continue;
5549 $usersroles = enrol_get_course_users_roles($data->courseid);
5550 foreach ($data->unenrol_users as $withroleid) {
5551 if ($withroleid) {
5552 $sql = "SELECT ue.*
5553 FROM {user_enrolments} ue
5554 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5555 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5556 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5557 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5559 } else {
5560 // Without any role assigned at course context.
5561 $sql = "SELECT ue.*
5562 FROM {user_enrolments} ue
5563 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5564 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5565 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5566 WHERE ra.id IS null";
5567 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5570 $rs = $DB->get_recordset_sql($sql, $params);
5571 foreach ($rs as $ue) {
5572 if (!isset($instances[$ue->enrolid])) {
5573 continue;
5575 $instance = $instances[$ue->enrolid];
5576 $plugin = $plugins[$instance->enrol];
5577 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5578 continue;
5581 if ($withroleid && count($usersroles[$ue->userid]) > 1) {
5582 // If we don't remove all roles and user has more than one role, just remove this role.
5583 role_unassign($withroleid, $ue->userid, $context->id);
5585 unset($usersroles[$ue->userid][$withroleid]);
5586 } else {
5587 // If we remove all roles or user has only one role, unenrol user from course.
5588 $plugin->unenrol_user($instance, $ue->userid);
5590 $data->unenrolled[$ue->userid] = $ue->userid;
5592 $rs->close();
5595 if (!empty($data->unenrolled)) {
5596 $status[] = array(
5597 'component' => $componentstr,
5598 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5599 'error' => false
5603 $componentstr = get_string('groups');
5605 // Remove all group members.
5606 if (!empty($data->reset_groups_members)) {
5607 groups_delete_group_members($data->courseid);
5608 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5611 // Remove all groups.
5612 if (!empty($data->reset_groups_remove)) {
5613 groups_delete_groups($data->courseid, false);
5614 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5617 // Remove all grouping members.
5618 if (!empty($data->reset_groupings_members)) {
5619 groups_delete_groupings_groups($data->courseid, false);
5620 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5623 // Remove all groupings.
5624 if (!empty($data->reset_groupings_remove)) {
5625 groups_delete_groupings($data->courseid, false);
5626 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5629 // Look in every instance of every module for data to delete.
5630 $unsupportedmods = array();
5631 if ($allmods = $DB->get_records('modules') ) {
5632 foreach ($allmods as $mod) {
5633 $modname = $mod->name;
5634 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5635 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5636 if (file_exists($modfile)) {
5637 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5638 continue; // Skip mods with no instances.
5640 include_once($modfile);
5641 if (function_exists($moddeleteuserdata)) {
5642 $modstatus = $moddeleteuserdata($data);
5643 if (is_array($modstatus)) {
5644 $status = array_merge($status, $modstatus);
5645 } else {
5646 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5648 } else {
5649 $unsupportedmods[] = $mod;
5651 } else {
5652 debugging('Missing lib.php in '.$modname.' module!');
5654 // Update calendar events for all modules.
5655 course_module_bulk_update_calendar_events($modname, $data->courseid);
5659 // Mention unsupported mods.
5660 if (!empty($unsupportedmods)) {
5661 foreach ($unsupportedmods as $mod) {
5662 $status[] = array(
5663 'component' => get_string('modulenameplural', $mod->name),
5664 'item' => '',
5665 'error' => get_string('resetnotimplemented')
5670 $componentstr = get_string('gradebook', 'grades');
5671 // Reset gradebook,.
5672 if (!empty($data->reset_gradebook_items)) {
5673 remove_course_grades($data->courseid, false);
5674 grade_grab_course_grades($data->courseid);
5675 grade_regrade_final_grades($data->courseid);
5676 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5678 } else if (!empty($data->reset_gradebook_grades)) {
5679 grade_course_reset($data->courseid);
5680 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5682 // Reset comments.
5683 if (!empty($data->reset_comments)) {
5684 require_once($CFG->dirroot.'/comment/lib.php');
5685 comment::reset_course_page_comments($context);
5688 $event = \core\event\course_reset_ended::create($eventparams);
5689 $event->trigger();
5691 return $status;
5695 * Generate an email processing address.
5697 * @param int $modid
5698 * @param string $modargs
5699 * @return string Returns email processing address
5701 function generate_email_processing_address($modid, $modargs) {
5702 global $CFG;
5704 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5705 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5711 * @todo Finish documenting this function
5713 * @param string $modargs
5714 * @param string $body Currently unused
5716 function moodle_process_email($modargs, $body) {
5717 global $DB;
5719 // The first char should be an unencoded letter. We'll take this as an action.
5720 switch ($modargs[0]) {
5721 case 'B': { // Bounce.
5722 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5723 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5724 // Check the half md5 of their email.
5725 $md5check = substr(md5($user->email), 0, 16);
5726 if ($md5check == substr($modargs, -16)) {
5727 set_bounce_count($user);
5729 // Else maybe they've already changed it?
5732 break;
5733 // Maybe more later?
5737 // CORRESPONDENCE.
5740 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5742 * @param string $action 'get', 'buffer', 'close' or 'flush'
5743 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5745 function get_mailer($action='get') {
5746 global $CFG;
5748 /** @var moodle_phpmailer $mailer */
5749 static $mailer = null;
5750 static $counter = 0;
5752 if (!isset($CFG->smtpmaxbulk)) {
5753 $CFG->smtpmaxbulk = 1;
5756 if ($action == 'get') {
5757 $prevkeepalive = false;
5759 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5760 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5761 $counter++;
5762 // Reset the mailer.
5763 $mailer->Priority = 3;
5764 $mailer->CharSet = 'UTF-8'; // Our default.
5765 $mailer->ContentType = "text/plain";
5766 $mailer->Encoding = "8bit";
5767 $mailer->From = "root@localhost";
5768 $mailer->FromName = "Root User";
5769 $mailer->Sender = "";
5770 $mailer->Subject = "";
5771 $mailer->Body = "";
5772 $mailer->AltBody = "";
5773 $mailer->ConfirmReadingTo = "";
5775 $mailer->clearAllRecipients();
5776 $mailer->clearReplyTos();
5777 $mailer->clearAttachments();
5778 $mailer->clearCustomHeaders();
5779 return $mailer;
5782 $prevkeepalive = $mailer->SMTPKeepAlive;
5783 get_mailer('flush');
5786 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5787 $mailer = new moodle_phpmailer();
5789 $counter = 1;
5791 if ($CFG->smtphosts == 'qmail') {
5792 // Use Qmail system.
5793 $mailer->isQmail();
5795 } else if (empty($CFG->smtphosts)) {
5796 // Use PHP mail() = sendmail.
5797 $mailer->isMail();
5799 } else {
5800 // Use SMTP directly.
5801 $mailer->isSMTP();
5802 if (!empty($CFG->debugsmtp) && (!empty($CFG->debugdeveloper))) {
5803 $mailer->SMTPDebug = 3;
5805 // Specify main and backup servers.
5806 $mailer->Host = $CFG->smtphosts;
5807 // Specify secure connection protocol.
5808 $mailer->SMTPSecure = $CFG->smtpsecure;
5809 // Use previous keepalive.
5810 $mailer->SMTPKeepAlive = $prevkeepalive;
5812 if ($CFG->smtpuser) {
5813 // Use SMTP authentication.
5814 $mailer->SMTPAuth = true;
5815 $mailer->Username = $CFG->smtpuser;
5816 $mailer->Password = $CFG->smtppass;
5820 return $mailer;
5823 $nothing = null;
5825 // Keep smtp session open after sending.
5826 if ($action == 'buffer') {
5827 if (!empty($CFG->smtpmaxbulk)) {
5828 get_mailer('flush');
5829 $m = get_mailer();
5830 if ($m->Mailer == 'smtp') {
5831 $m->SMTPKeepAlive = true;
5834 return $nothing;
5837 // Close smtp session, but continue buffering.
5838 if ($action == 'flush') {
5839 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5840 if (!empty($mailer->SMTPDebug)) {
5841 echo '<pre>'."\n";
5843 $mailer->SmtpClose();
5844 if (!empty($mailer->SMTPDebug)) {
5845 echo '</pre>';
5848 return $nothing;
5851 // Close smtp session, do not buffer anymore.
5852 if ($action == 'close') {
5853 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5854 get_mailer('flush');
5855 $mailer->SMTPKeepAlive = false;
5857 $mailer = null; // Better force new instance.
5858 return $nothing;
5863 * A helper function to test for email diversion
5865 * @param string $email
5866 * @return bool Returns true if the email should be diverted
5868 function email_should_be_diverted($email) {
5869 global $CFG;
5871 if (empty($CFG->divertallemailsto)) {
5872 return false;
5875 if (empty($CFG->divertallemailsexcept)) {
5876 return true;
5879 $patterns = array_map('trim', preg_split("/[\s,]+/", $CFG->divertallemailsexcept));
5880 foreach ($patterns as $pattern) {
5881 if (preg_match("/$pattern/", $email)) {
5882 return false;
5886 return true;
5890 * Generate a unique email Message-ID using the moodle domain and install path
5892 * @param string $localpart An optional unique message id prefix.
5893 * @return string The formatted ID ready for appending to the email headers.
5895 function generate_email_messageid($localpart = null) {
5896 global $CFG;
5898 $urlinfo = parse_url($CFG->wwwroot);
5899 $base = '@' . $urlinfo['host'];
5901 // If multiple moodles are on the same domain we want to tell them
5902 // apart so we add the install path to the local part. This means
5903 // that the id local part should never contain a / character so
5904 // we can correctly parse the id to reassemble the wwwroot.
5905 if (isset($urlinfo['path'])) {
5906 $base = $urlinfo['path'] . $base;
5909 if (empty($localpart)) {
5910 $localpart = uniqid('', true);
5913 // Because we may have an option /installpath suffix to the local part
5914 // of the id we need to escape any / chars which are in the $localpart.
5915 $localpart = str_replace('/', '%2F', $localpart);
5917 return '<' . $localpart . $base . '>';
5921 * Send an email to a specified user
5923 * @param stdClass $user A {@link $USER} object
5924 * @param stdClass $from A {@link $USER} object
5925 * @param string $subject plain text subject line of the email
5926 * @param string $messagetext plain text version of the message
5927 * @param string $messagehtml complete html version of the message (optional)
5928 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in one of
5929 * the following directories: $CFG->cachedir, $CFG->dataroot, $CFG->dirroot, $CFG->localcachedir, $CFG->tempdir
5930 * @param string $attachname the name of the file (extension indicates MIME)
5931 * @param bool $usetrueaddress determines whether $from email address should
5932 * be sent out. Will be overruled by user profile setting for maildisplay
5933 * @param string $replyto Email address to reply to
5934 * @param string $replytoname Name of reply to recipient
5935 * @param int $wordwrapwidth custom word wrap width, default 79
5936 * @return bool Returns true if mail was sent OK and false if there was an error.
5938 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5939 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5941 global $CFG, $PAGE, $SITE;
5943 if (empty($user) or empty($user->id)) {
5944 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5945 return false;
5948 if (empty($user->email)) {
5949 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5950 return false;
5953 if (!empty($user->deleted)) {
5954 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5955 return false;
5958 if (defined('BEHAT_SITE_RUNNING')) {
5959 // Fake email sending in behat.
5960 return true;
5963 if (!empty($CFG->noemailever)) {
5964 // Hidden setting for development sites, set in config.php if needed.
5965 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5966 return true;
5969 if (email_should_be_diverted($user->email)) {
5970 $subject = "[DIVERTED {$user->email}] $subject";
5971 $user = clone($user);
5972 $user->email = $CFG->divertallemailsto;
5975 // Skip mail to suspended users.
5976 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5977 return true;
5980 if (!validate_email($user->email)) {
5981 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5982 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5983 return false;
5986 if (over_bounce_threshold($user)) {
5987 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5988 return false;
5991 // TLD .invalid is specifically reserved for invalid domain names.
5992 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5993 if (substr($user->email, -8) == '.invalid') {
5994 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5995 return true; // This is not an error.
5998 // If the user is a remote mnet user, parse the email text for URL to the
5999 // wwwroot and modify the url to direct the user's browser to login at their
6000 // home site (identity provider - idp) before hitting the link itself.
6001 if (is_mnet_remote_user($user)) {
6002 require_once($CFG->dirroot.'/mnet/lib.php');
6004 $jumpurl = mnet_get_idp_jump_url($user);
6005 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
6007 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
6008 $callback,
6009 $messagetext);
6010 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
6011 $callback,
6012 $messagehtml);
6014 $mail = get_mailer();
6016 if (!empty($mail->SMTPDebug)) {
6017 echo '<pre>' . "\n";
6020 $temprecipients = array();
6021 $tempreplyto = array();
6023 // Make sure that we fall back onto some reasonable no-reply address.
6024 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
6025 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
6027 if (!validate_email($noreplyaddress)) {
6028 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
6029 $noreplyaddress = $noreplyaddressdefault;
6032 // Make up an email address for handling bounces.
6033 if (!empty($CFG->handlebounces)) {
6034 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
6035 $mail->Sender = generate_email_processing_address(0, $modargs);
6036 } else {
6037 $mail->Sender = $noreplyaddress;
6040 // Make sure that the explicit replyto is valid, fall back to the implicit one.
6041 if (!empty($replyto) && !validate_email($replyto)) {
6042 debugging('email_to_user: Invalid replyto-email '.s($replyto));
6043 $replyto = $noreplyaddress;
6046 if (is_string($from)) { // So we can pass whatever we want if there is need.
6047 $mail->From = $noreplyaddress;
6048 $mail->FromName = $from;
6049 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
6050 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6051 // in a course with the sender.
6052 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
6053 if (!validate_email($from->email)) {
6054 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
6055 // Better not to use $noreplyaddress in this case.
6056 return false;
6058 $mail->From = $from->email;
6059 $fromdetails = new stdClass();
6060 $fromdetails->name = fullname($from);
6061 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6062 $fromdetails->siteshortname = format_string($SITE->shortname);
6063 $fromstring = $fromdetails->name;
6064 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
6065 $fromstring = get_string('emailvia', 'core', $fromdetails);
6067 $mail->FromName = $fromstring;
6068 if (empty($replyto)) {
6069 $tempreplyto[] = array($from->email, fullname($from));
6071 } else {
6072 $mail->From = $noreplyaddress;
6073 $fromdetails = new stdClass();
6074 $fromdetails->name = fullname($from);
6075 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6076 $fromdetails->siteshortname = format_string($SITE->shortname);
6077 $fromstring = $fromdetails->name;
6078 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
6079 $fromstring = get_string('emailvia', 'core', $fromdetails);
6081 $mail->FromName = $fromstring;
6082 if (empty($replyto)) {
6083 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
6087 if (!empty($replyto)) {
6088 $tempreplyto[] = array($replyto, $replytoname);
6091 $temprecipients[] = array($user->email, fullname($user));
6093 // Set word wrap.
6094 $mail->WordWrap = $wordwrapwidth;
6096 if (!empty($from->customheaders)) {
6097 // Add custom headers.
6098 if (is_array($from->customheaders)) {
6099 foreach ($from->customheaders as $customheader) {
6100 $mail->addCustomHeader($customheader);
6102 } else {
6103 $mail->addCustomHeader($from->customheaders);
6107 // If the X-PHP-Originating-Script email header is on then also add an additional
6108 // header with details of where exactly in moodle the email was triggered from,
6109 // either a call to message_send() or to email_to_user().
6110 if (ini_get('mail.add_x_header')) {
6112 $stack = debug_backtrace(false);
6113 $origin = $stack[0];
6115 foreach ($stack as $depth => $call) {
6116 if ($call['function'] == 'message_send') {
6117 $origin = $call;
6121 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
6122 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
6123 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
6126 if (!empty($CFG->emailheaders)) {
6127 $headers = array_map('trim', explode("\n", $CFG->emailheaders));
6128 foreach ($headers as $header) {
6129 if (!empty($header)) {
6130 $mail->addCustomHeader($header);
6135 if (!empty($from->priority)) {
6136 $mail->Priority = $from->priority;
6139 $renderer = $PAGE->get_renderer('core');
6140 $context = array(
6141 'sitefullname' => $SITE->fullname,
6142 'siteshortname' => $SITE->shortname,
6143 'sitewwwroot' => $CFG->wwwroot,
6144 'subject' => $subject,
6145 'prefix' => $CFG->emailsubjectprefix,
6146 'to' => $user->email,
6147 'toname' => fullname($user),
6148 'from' => $mail->From,
6149 'fromname' => $mail->FromName,
6151 if (!empty($tempreplyto[0])) {
6152 $context['replyto'] = $tempreplyto[0][0];
6153 $context['replytoname'] = $tempreplyto[0][1];
6155 if ($user->id > 0) {
6156 $context['touserid'] = $user->id;
6157 $context['tousername'] = $user->username;
6160 if (!empty($user->mailformat) && $user->mailformat == 1) {
6161 // Only process html templates if the user preferences allow html email.
6163 if (!$messagehtml) {
6164 // If no html has been given, BUT there is an html wrapping template then
6165 // auto convert the text to html and then wrap it.
6166 $messagehtml = trim(text_to_html($messagetext));
6168 $context['body'] = $messagehtml;
6169 $messagehtml = $renderer->render_from_template('core/email_html', $context);
6172 $context['body'] = html_to_text(nl2br($messagetext));
6173 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
6174 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
6175 $messagetext = $renderer->render_from_template('core/email_text', $context);
6177 // Autogenerate a MessageID if it's missing.
6178 if (empty($mail->MessageID)) {
6179 $mail->MessageID = generate_email_messageid();
6182 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6183 // Don't ever send HTML to users who don't want it.
6184 $mail->isHTML(true);
6185 $mail->Encoding = 'quoted-printable';
6186 $mail->Body = $messagehtml;
6187 $mail->AltBody = "\n$messagetext\n";
6188 } else {
6189 $mail->IsHTML(false);
6190 $mail->Body = "\n$messagetext\n";
6193 if ($attachment && $attachname) {
6194 if (preg_match( "~\\.\\.~" , $attachment )) {
6195 // Security check for ".." in dir path.
6196 $supportuser = core_user::get_support_user();
6197 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6198 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6199 } else {
6200 require_once($CFG->libdir.'/filelib.php');
6201 $mimetype = mimeinfo('type', $attachname);
6203 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6204 // The absolute (real) path is also fetched to ensure that comparisons to allowed paths are compared equally.
6205 $attachpath = str_replace('\\', '/', realpath($attachment));
6207 // Build an array of all filepaths from which attachments can be added (normalised slashes, absolute/real path).
6208 $allowedpaths = array_map(function(string $path): string {
6209 return str_replace('\\', '/', realpath($path));
6210 }, [
6211 $CFG->cachedir,
6212 $CFG->dataroot,
6213 $CFG->dirroot,
6214 $CFG->localcachedir,
6215 $CFG->tempdir,
6216 $CFG->localrequestdir,
6219 // Set addpath to true.
6220 $addpath = true;
6222 // Check if attachment includes one of the allowed paths.
6223 foreach (array_filter($allowedpaths) as $allowedpath) {
6224 // Set addpath to false if the attachment includes one of the allowed paths.
6225 if (strpos($attachpath, $allowedpath) === 0) {
6226 $addpath = false;
6227 break;
6231 // If the attachment is a full path to a file in the multiple allowed paths, use it as is,
6232 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6233 if ($addpath == true) {
6234 $attachment = $CFG->dataroot . '/' . $attachment;
6237 $mail->addAttachment($attachment, $attachname, 'base64', $mimetype);
6241 // Check if the email should be sent in an other charset then the default UTF-8.
6242 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6244 // Use the defined site mail charset or eventually the one preferred by the recipient.
6245 $charset = $CFG->sitemailcharset;
6246 if (!empty($CFG->allowusermailcharset)) {
6247 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6248 $charset = $useremailcharset;
6252 // Convert all the necessary strings if the charset is supported.
6253 $charsets = get_list_of_charsets();
6254 unset($charsets['UTF-8']);
6255 if (in_array($charset, $charsets)) {
6256 $mail->CharSet = $charset;
6257 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6258 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6259 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6260 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6262 foreach ($temprecipients as $key => $values) {
6263 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6265 foreach ($tempreplyto as $key => $values) {
6266 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6271 foreach ($temprecipients as $values) {
6272 $mail->addAddress($values[0], $values[1]);
6274 foreach ($tempreplyto as $values) {
6275 $mail->addReplyTo($values[0], $values[1]);
6278 if (!empty($CFG->emaildkimselector)) {
6279 $domain = substr(strrchr($mail->From, "@"), 1);
6280 $pempath = "{$CFG->dataroot}/dkim/{$domain}/{$CFG->emaildkimselector}.private";
6281 if (file_exists($pempath)) {
6282 $mail->DKIM_domain = $domain;
6283 $mail->DKIM_private = $pempath;
6284 $mail->DKIM_selector = $CFG->emaildkimselector;
6285 $mail->DKIM_identity = $mail->From;
6286 } else {
6287 debugging("Email DKIM selector chosen due to {$mail->From} but no certificate found at $pempath", DEBUG_DEVELOPER);
6291 if ($mail->send()) {
6292 set_send_count($user);
6293 if (!empty($mail->SMTPDebug)) {
6294 echo '</pre>';
6296 return true;
6297 } else {
6298 // Trigger event for failing to send email.
6299 $event = \core\event\email_failed::create(array(
6300 'context' => context_system::instance(),
6301 'userid' => $from->id,
6302 'relateduserid' => $user->id,
6303 'other' => array(
6304 'subject' => $subject,
6305 'message' => $messagetext,
6306 'errorinfo' => $mail->ErrorInfo
6309 $event->trigger();
6310 if (CLI_SCRIPT) {
6311 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6313 if (!empty($mail->SMTPDebug)) {
6314 echo '</pre>';
6316 return false;
6321 * Check to see if a user's real email address should be used for the "From" field.
6323 * @param object $from The user object for the user we are sending the email from.
6324 * @param object $user The user object that we are sending the email to.
6325 * @param array $unused No longer used.
6326 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6328 function can_send_from_real_email_address($from, $user, $unused = null) {
6329 global $CFG;
6330 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6331 return false;
6333 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6334 // Email is in the list of allowed domains for sending email,
6335 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6336 // in a course with the sender.
6337 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6338 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6339 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6340 && enrol_get_shared_courses($user, $from, false, true)))) {
6341 return true;
6343 return false;
6347 * Generate a signoff for emails based on support settings
6349 * @return string
6351 function generate_email_signoff() {
6352 global $CFG;
6354 $signoff = "\n";
6355 if (!empty($CFG->supportname)) {
6356 $signoff .= $CFG->supportname."\n";
6358 if (!empty($CFG->supportemail)) {
6359 $signoff .= $CFG->supportemail."\n";
6361 if (!empty($CFG->supportpage)) {
6362 $signoff .= $CFG->supportpage."\n";
6364 return $signoff;
6368 * Sets specified user's password and send the new password to the user via email.
6370 * @param stdClass $user A {@link $USER} object
6371 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6372 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6374 function setnew_password_and_mail($user, $fasthash = false) {
6375 global $CFG, $DB;
6377 // We try to send the mail in language the user understands,
6378 // unfortunately the filter_string() does not support alternative langs yet
6379 // so multilang will not work properly for site->fullname.
6380 $lang = empty($user->lang) ? get_newuser_language() : $user->lang;
6382 $site = get_site();
6384 $supportuser = core_user::get_support_user();
6386 $newpassword = generate_password();
6388 update_internal_user_password($user, $newpassword, $fasthash);
6390 $a = new stdClass();
6391 $a->firstname = fullname($user, true);
6392 $a->sitename = format_string($site->fullname);
6393 $a->username = $user->username;
6394 $a->newpassword = $newpassword;
6395 $a->link = $CFG->wwwroot .'/login/?lang='.$lang;
6396 $a->signoff = generate_email_signoff();
6398 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6400 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6402 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6403 return email_to_user($user, $supportuser, $subject, $message);
6408 * Resets specified user's password and send the new password to the user via email.
6410 * @param stdClass $user A {@link $USER} object
6411 * @return bool Returns true if mail was sent OK and false if there was an error.
6413 function reset_password_and_mail($user) {
6414 global $CFG;
6416 $site = get_site();
6417 $supportuser = core_user::get_support_user();
6419 $userauth = get_auth_plugin($user->auth);
6420 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6421 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6422 return false;
6425 $newpassword = generate_password();
6427 if (!$userauth->user_update_password($user, $newpassword)) {
6428 print_error("cannotsetpassword");
6431 $a = new stdClass();
6432 $a->firstname = $user->firstname;
6433 $a->lastname = $user->lastname;
6434 $a->sitename = format_string($site->fullname);
6435 $a->username = $user->username;
6436 $a->newpassword = $newpassword;
6437 $a->link = $CFG->wwwroot .'/login/change_password.php';
6438 $a->signoff = generate_email_signoff();
6440 $message = get_string('newpasswordtext', '', $a);
6442 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6444 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6446 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6447 return email_to_user($user, $supportuser, $subject, $message);
6451 * Send email to specified user with confirmation text and activation link.
6453 * @param stdClass $user A {@link $USER} object
6454 * @param string $confirmationurl user confirmation URL
6455 * @return bool Returns true if mail was sent OK and false if there was an error.
6457 function send_confirmation_email($user, $confirmationurl = null) {
6458 global $CFG;
6460 $site = get_site();
6461 $supportuser = core_user::get_support_user();
6463 $data = new stdClass();
6464 $data->sitename = format_string($site->fullname);
6465 $data->admin = generate_email_signoff();
6467 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6469 if (empty($confirmationurl)) {
6470 $confirmationurl = '/login/confirm.php';
6473 $confirmationurl = new moodle_url($confirmationurl);
6474 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6475 $confirmationurl->remove_params('data');
6476 $confirmationpath = $confirmationurl->out(false);
6478 // We need to custom encode the username to include trailing dots in the link.
6479 // Because of this custom encoding we can't use moodle_url directly.
6480 // Determine if a query string is present in the confirmation url.
6481 $hasquerystring = strpos($confirmationpath, '?') !== false;
6482 // Perform normal url encoding of the username first.
6483 $username = urlencode($user->username);
6484 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6485 $username = str_replace('.', '%2E', $username);
6487 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6489 $message = get_string('emailconfirmation', '', $data);
6490 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6492 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6493 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6497 * Sends a password change confirmation email.
6499 * @param stdClass $user A {@link $USER} object
6500 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6501 * @return bool Returns true if mail was sent OK and false if there was an error.
6503 function send_password_change_confirmation_email($user, $resetrecord) {
6504 global $CFG;
6506 $site = get_site();
6507 $supportuser = core_user::get_support_user();
6508 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6510 $data = new stdClass();
6511 $data->firstname = $user->firstname;
6512 $data->lastname = $user->lastname;
6513 $data->username = $user->username;
6514 $data->sitename = format_string($site->fullname);
6515 $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6516 $data->admin = generate_email_signoff();
6517 $data->resetminutes = $pwresetmins;
6519 $message = get_string('emailresetconfirmation', '', $data);
6520 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6522 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6523 return email_to_user($user, $supportuser, $subject, $message);
6528 * Sends an email containing information on how to change your password.
6530 * @param stdClass $user A {@link $USER} object
6531 * @return bool Returns true if mail was sent OK and false if there was an error.
6533 function send_password_change_info($user) {
6534 $site = get_site();
6535 $supportuser = core_user::get_support_user();
6537 $data = new stdClass();
6538 $data->firstname = $user->firstname;
6539 $data->lastname = $user->lastname;
6540 $data->username = $user->username;
6541 $data->sitename = format_string($site->fullname);
6542 $data->admin = generate_email_signoff();
6544 if (!is_enabled_auth($user->auth)) {
6545 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6546 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6547 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6548 return email_to_user($user, $supportuser, $subject, $message);
6551 $userauth = get_auth_plugin($user->auth);
6552 ['subject' => $subject, 'message' => $message] = $userauth->get_password_change_info($user);
6554 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6555 return email_to_user($user, $supportuser, $subject, $message);
6559 * Check that an email is allowed. It returns an error message if there was a problem.
6561 * @param string $email Content of email
6562 * @return string|false
6564 function email_is_not_allowed($email) {
6565 global $CFG;
6567 // Comparing lowercase domains.
6568 $email = strtolower($email);
6569 if (!empty($CFG->allowemailaddresses)) {
6570 $allowed = explode(' ', strtolower($CFG->allowemailaddresses));
6571 foreach ($allowed as $allowedpattern) {
6572 $allowedpattern = trim($allowedpattern);
6573 if (!$allowedpattern) {
6574 continue;
6576 if (strpos($allowedpattern, '.') === 0) {
6577 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6578 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6579 return false;
6582 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6583 return false;
6586 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6588 } else if (!empty($CFG->denyemailaddresses)) {
6589 $denied = explode(' ', strtolower($CFG->denyemailaddresses));
6590 foreach ($denied as $deniedpattern) {
6591 $deniedpattern = trim($deniedpattern);
6592 if (!$deniedpattern) {
6593 continue;
6595 if (strpos($deniedpattern, '.') === 0) {
6596 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6597 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6598 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6601 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6602 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6607 return false;
6610 // FILE HANDLING.
6613 * Returns local file storage instance
6615 * @return file_storage
6617 function get_file_storage($reset = false) {
6618 global $CFG;
6620 static $fs = null;
6622 if ($reset) {
6623 $fs = null;
6624 return;
6627 if ($fs) {
6628 return $fs;
6631 require_once("$CFG->libdir/filelib.php");
6633 $fs = new file_storage();
6635 return $fs;
6639 * Returns local file storage instance
6641 * @return file_browser
6643 function get_file_browser() {
6644 global $CFG;
6646 static $fb = null;
6648 if ($fb) {
6649 return $fb;
6652 require_once("$CFG->libdir/filelib.php");
6654 $fb = new file_browser();
6656 return $fb;
6660 * Returns file packer
6662 * @param string $mimetype default application/zip
6663 * @return file_packer
6665 function get_file_packer($mimetype='application/zip') {
6666 global $CFG;
6668 static $fp = array();
6670 if (isset($fp[$mimetype])) {
6671 return $fp[$mimetype];
6674 switch ($mimetype) {
6675 case 'application/zip':
6676 case 'application/vnd.moodle.profiling':
6677 $classname = 'zip_packer';
6678 break;
6680 case 'application/x-gzip' :
6681 $classname = 'tgz_packer';
6682 break;
6684 case 'application/vnd.moodle.backup':
6685 $classname = 'mbz_packer';
6686 break;
6688 default:
6689 return false;
6692 require_once("$CFG->libdir/filestorage/$classname.php");
6693 $fp[$mimetype] = new $classname();
6695 return $fp[$mimetype];
6699 * Returns current name of file on disk if it exists.
6701 * @param string $newfile File to be verified
6702 * @return string Current name of file on disk if true
6704 function valid_uploaded_file($newfile) {
6705 if (empty($newfile)) {
6706 return '';
6708 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6709 return $newfile['tmp_name'];
6710 } else {
6711 return '';
6716 * Returns the maximum size for uploading files.
6718 * There are seven possible upload limits:
6719 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6720 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6721 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6722 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6723 * 5. by the Moodle admin in $CFG->maxbytes
6724 * 6. by the teacher in the current course $course->maxbytes
6725 * 7. by the teacher for the current module, eg $assignment->maxbytes
6727 * These last two are passed to this function as arguments (in bytes).
6728 * Anything defined as 0 is ignored.
6729 * The smallest of all the non-zero numbers is returned.
6731 * @todo Finish documenting this function
6733 * @param int $sitebytes Set maximum size
6734 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6735 * @param int $modulebytes Current module ->maxbytes (in bytes)
6736 * @param bool $unused This parameter has been deprecated and is not used any more.
6737 * @return int The maximum size for uploading files.
6739 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6741 if (! $filesize = ini_get('upload_max_filesize')) {
6742 $filesize = '5M';
6744 $minimumsize = get_real_size($filesize);
6746 if ($postsize = ini_get('post_max_size')) {
6747 $postsize = get_real_size($postsize);
6748 if ($postsize < $minimumsize) {
6749 $minimumsize = $postsize;
6753 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6754 $minimumsize = $sitebytes;
6757 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6758 $minimumsize = $coursebytes;
6761 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6762 $minimumsize = $modulebytes;
6765 return $minimumsize;
6769 * Returns the maximum size for uploading files for the current user
6771 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6773 * @param context $context The context in which to check user capabilities
6774 * @param int $sitebytes Set maximum size
6775 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6776 * @param int $modulebytes Current module ->maxbytes (in bytes)
6777 * @param stdClass $user The user
6778 * @param bool $unused This parameter has been deprecated and is not used any more.
6779 * @return int The maximum size for uploading files.
6781 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6782 $unused = false) {
6783 global $USER;
6785 if (empty($user)) {
6786 $user = $USER;
6789 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6790 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6793 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6797 * Returns an array of possible sizes in local language
6799 * Related to {@link get_max_upload_file_size()} - this function returns an
6800 * array of possible sizes in an array, translated to the
6801 * local language.
6803 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6805 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6806 * with the value set to 0. This option will be the first in the list.
6808 * @uses SORT_NUMERIC
6809 * @param int $sitebytes Set maximum size
6810 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6811 * @param int $modulebytes Current module ->maxbytes (in bytes)
6812 * @param int|array $custombytes custom upload size/s which will be added to list,
6813 * Only value/s smaller then maxsize will be added to list.
6814 * @return array
6816 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6817 global $CFG;
6819 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6820 return array();
6823 if ($sitebytes == 0) {
6824 // Will get the minimum of upload_max_filesize or post_max_size.
6825 $sitebytes = get_max_upload_file_size();
6828 $filesize = array();
6829 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6830 5242880, 10485760, 20971520, 52428800, 104857600,
6831 262144000, 524288000, 786432000, 1073741824,
6832 2147483648, 4294967296, 8589934592);
6834 // If custombytes is given and is valid then add it to the list.
6835 if (is_number($custombytes) and $custombytes > 0) {
6836 $custombytes = (int)$custombytes;
6837 if (!in_array($custombytes, $sizelist)) {
6838 $sizelist[] = $custombytes;
6840 } else if (is_array($custombytes)) {
6841 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6844 // Allow maxbytes to be selected if it falls outside the above boundaries.
6845 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6846 // Note: get_real_size() is used in order to prevent problems with invalid values.
6847 $sizelist[] = get_real_size($CFG->maxbytes);
6850 foreach ($sizelist as $sizebytes) {
6851 if ($sizebytes < $maxsize && $sizebytes > 0) {
6852 $filesize[(string)intval($sizebytes)] = display_size($sizebytes, 0);
6856 $limitlevel = '';
6857 $displaysize = '';
6858 if ($modulebytes &&
6859 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6860 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6861 $limitlevel = get_string('activity', 'core');
6862 $displaysize = display_size($modulebytes, 0);
6863 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6865 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6866 $limitlevel = get_string('course', 'core');
6867 $displaysize = display_size($coursebytes, 0);
6868 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6870 } else if ($sitebytes) {
6871 $limitlevel = get_string('site', 'core');
6872 $displaysize = display_size($sitebytes, 0);
6873 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6876 krsort($filesize, SORT_NUMERIC);
6877 if ($limitlevel) {
6878 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6879 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6882 return $filesize;
6886 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6888 * If excludefiles is defined, then that file/directory is ignored
6889 * If getdirs is true, then (sub)directories are included in the output
6890 * If getfiles is true, then files are included in the output
6891 * (at least one of these must be true!)
6893 * @todo Finish documenting this function. Add examples of $excludefile usage.
6895 * @param string $rootdir A given root directory to start from
6896 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6897 * @param bool $descend If true then subdirectories are recursed as well
6898 * @param bool $getdirs If true then (sub)directories are included in the output
6899 * @param bool $getfiles If true then files are included in the output
6900 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6902 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6904 $dirs = array();
6906 if (!$getdirs and !$getfiles) { // Nothing to show.
6907 return $dirs;
6910 if (!is_dir($rootdir)) { // Must be a directory.
6911 return $dirs;
6914 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6915 return $dirs;
6918 if (!is_array($excludefiles)) {
6919 $excludefiles = array($excludefiles);
6922 while (false !== ($file = readdir($dir))) {
6923 $firstchar = substr($file, 0, 1);
6924 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6925 continue;
6927 $fullfile = $rootdir .'/'. $file;
6928 if (filetype($fullfile) == 'dir') {
6929 if ($getdirs) {
6930 $dirs[] = $file;
6932 if ($descend) {
6933 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6934 foreach ($subdirs as $subdir) {
6935 $dirs[] = $file .'/'. $subdir;
6938 } else if ($getfiles) {
6939 $dirs[] = $file;
6942 closedir($dir);
6944 asort($dirs);
6946 return $dirs;
6951 * Adds up all the files in a directory and works out the size.
6953 * @param string $rootdir The directory to start from
6954 * @param string $excludefile A file to exclude when summing directory size
6955 * @return int The summed size of all files and subfiles within the root directory
6957 function get_directory_size($rootdir, $excludefile='') {
6958 global $CFG;
6960 // Do it this way if we can, it's much faster.
6961 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6962 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6963 $output = null;
6964 $return = null;
6965 exec($command, $output, $return);
6966 if (is_array($output)) {
6967 // We told it to return k.
6968 return get_real_size(intval($output[0]).'k');
6972 if (!is_dir($rootdir)) {
6973 // Must be a directory.
6974 return 0;
6977 if (!$dir = @opendir($rootdir)) {
6978 // Can't open it for some reason.
6979 return 0;
6982 $size = 0;
6984 while (false !== ($file = readdir($dir))) {
6985 $firstchar = substr($file, 0, 1);
6986 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6987 continue;
6989 $fullfile = $rootdir .'/'. $file;
6990 if (filetype($fullfile) == 'dir') {
6991 $size += get_directory_size($fullfile, $excludefile);
6992 } else {
6993 $size += filesize($fullfile);
6996 closedir($dir);
6998 return $size;
7002 * Converts bytes into display form
7004 * @param int $size The size to convert to human readable form
7005 * @param int $decimalplaces If specified, uses fixed number of decimal places
7006 * @param string $fixedunits If specified, uses fixed units (e.g. 'KB')
7007 * @return string Display version of size
7009 function display_size($size, int $decimalplaces = 1, string $fixedunits = ''): string {
7011 static $units;
7013 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
7014 return get_string('unlimited');
7017 if (empty($units)) {
7018 $units[] = get_string('sizeb');
7019 $units[] = get_string('sizekb');
7020 $units[] = get_string('sizemb');
7021 $units[] = get_string('sizegb');
7022 $units[] = get_string('sizetb');
7023 $units[] = get_string('sizepb');
7026 switch ($fixedunits) {
7027 case 'PB' :
7028 $magnitude = 5;
7029 break;
7030 case 'TB' :
7031 $magnitude = 4;
7032 break;
7033 case 'GB' :
7034 $magnitude = 3;
7035 break;
7036 case 'MB' :
7037 $magnitude = 2;
7038 break;
7039 case 'KB' :
7040 $magnitude = 1;
7041 break;
7042 case 'B' :
7043 $magnitude = 0;
7044 break;
7045 case '':
7046 $magnitude = floor(log($size, 1024));
7047 $magnitude = max(0, min(5, $magnitude));
7048 break;
7049 default:
7050 throw new coding_exception('Unknown fixed units value: ' . $fixedunits);
7053 // Special case for magnitude 0 (bytes) - never use decimal places.
7054 $nbsp = "\xc2\xa0";
7055 if ($magnitude === 0) {
7056 return round($size) . $nbsp . $units[$magnitude];
7059 // Convert to specified units.
7060 $sizeinunit = $size / 1024 ** $magnitude;
7062 // Fixed decimal places.
7063 return sprintf('%.' . $decimalplaces . 'f', $sizeinunit) . $nbsp . $units[$magnitude];
7067 * Cleans a given filename by removing suspicious or troublesome characters
7069 * @see clean_param()
7070 * @param string $string file name
7071 * @return string cleaned file name
7073 function clean_filename($string) {
7074 return clean_param($string, PARAM_FILE);
7077 // STRING TRANSLATION.
7080 * Returns the code for the current language
7082 * @category string
7083 * @return string
7085 function current_language() {
7086 global $CFG, $USER, $SESSION, $COURSE;
7088 if (!empty($SESSION->forcelang)) {
7089 // Allows overriding course-forced language (useful for admins to check
7090 // issues in courses whose language they don't understand).
7091 // Also used by some code to temporarily get language-related information in a
7092 // specific language (see force_current_language()).
7093 $return = $SESSION->forcelang;
7095 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
7096 // Course language can override all other settings for this page.
7097 $return = $COURSE->lang;
7099 } else if (!empty($SESSION->lang)) {
7100 // Session language can override other settings.
7101 $return = $SESSION->lang;
7103 } else if (!empty($USER->lang)) {
7104 $return = $USER->lang;
7106 } else if (isset($CFG->lang)) {
7107 $return = $CFG->lang;
7109 } else {
7110 $return = 'en';
7113 // Just in case this slipped in from somewhere by accident.
7114 $return = str_replace('_utf8', '', $return);
7116 return $return;
7120 * Returns parent language of current active language if defined
7122 * @category string
7123 * @param string $lang null means current language
7124 * @return string
7126 function get_parent_language($lang=null) {
7128 $parentlang = get_string_manager()->get_string('parentlanguage', 'langconfig', null, $lang);
7130 if ($parentlang === 'en') {
7131 $parentlang = '';
7134 return $parentlang;
7138 * Force the current language to get strings and dates localised in the given language.
7140 * After calling this function, all strings will be provided in the given language
7141 * until this function is called again, or equivalent code is run.
7143 * @param string $language
7144 * @return string previous $SESSION->forcelang value
7146 function force_current_language($language) {
7147 global $SESSION;
7148 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
7149 if ($language !== $sessionforcelang) {
7150 // Seting forcelang to null or an empty string disables it's effect.
7151 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
7152 $SESSION->forcelang = $language;
7153 moodle_setlocale();
7156 return $sessionforcelang;
7160 * Returns current string_manager instance.
7162 * The param $forcereload is needed for CLI installer only where the string_manager instance
7163 * must be replaced during the install.php script life time.
7165 * @category string
7166 * @param bool $forcereload shall the singleton be released and new instance created instead?
7167 * @return core_string_manager
7169 function get_string_manager($forcereload=false) {
7170 global $CFG;
7172 static $singleton = null;
7174 if ($forcereload) {
7175 $singleton = null;
7177 if ($singleton === null) {
7178 if (empty($CFG->early_install_lang)) {
7180 $transaliases = array();
7181 if (empty($CFG->langlist)) {
7182 $translist = array();
7183 } else {
7184 $translist = explode(',', $CFG->langlist);
7185 $translist = array_map('trim', $translist);
7186 // Each language in the $CFG->langlist can has an "alias" that would substitute the default language name.
7187 foreach ($translist as $i => $value) {
7188 $parts = preg_split('/\s*\|\s*/', $value, 2);
7189 if (count($parts) == 2) {
7190 $transaliases[$parts[0]] = $parts[1];
7191 $translist[$i] = $parts[0];
7196 if (!empty($CFG->config_php_settings['customstringmanager'])) {
7197 $classname = $CFG->config_php_settings['customstringmanager'];
7199 if (class_exists($classname)) {
7200 $implements = class_implements($classname);
7202 if (isset($implements['core_string_manager'])) {
7203 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7204 return $singleton;
7206 } else {
7207 debugging('Unable to instantiate custom string manager: class '.$classname.
7208 ' does not implement the core_string_manager interface.');
7211 } else {
7212 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7216 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7218 } else {
7219 $singleton = new core_string_manager_install();
7223 return $singleton;
7227 * Returns a localized string.
7229 * Returns the translated string specified by $identifier as
7230 * for $module. Uses the same format files as STphp.
7231 * $a is an object, string or number that can be used
7232 * within translation strings
7234 * eg 'hello {$a->firstname} {$a->lastname}'
7235 * or 'hello {$a}'
7237 * If you would like to directly echo the localized string use
7238 * the function {@link print_string()}
7240 * Example usage of this function involves finding the string you would
7241 * like a local equivalent of and using its identifier and module information
7242 * to retrieve it.<br/>
7243 * If you open moodle/lang/en/moodle.php and look near line 278
7244 * you will find a string to prompt a user for their word for 'course'
7245 * <code>
7246 * $string['course'] = 'Course';
7247 * </code>
7248 * So if you want to display the string 'Course'
7249 * in any language that supports it on your site
7250 * you just need to use the identifier 'course'
7251 * <code>
7252 * $mystring = '<strong>'. get_string('course') .'</strong>';
7253 * or
7254 * </code>
7255 * If the string you want is in another file you'd take a slightly
7256 * different approach. Looking in moodle/lang/en/calendar.php you find
7257 * around line 75:
7258 * <code>
7259 * $string['typecourse'] = 'Course event';
7260 * </code>
7261 * If you want to display the string "Course event" in any language
7262 * supported you would use the identifier 'typecourse' and the module 'calendar'
7263 * (because it is in the file calendar.php):
7264 * <code>
7265 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7266 * </code>
7268 * As a last resort, should the identifier fail to map to a string
7269 * the returned string will be [[ $identifier ]]
7271 * In Moodle 2.3 there is a new argument to this function $lazyload.
7272 * Setting $lazyload to true causes get_string to return a lang_string object
7273 * rather than the string itself. The fetching of the string is then put off until
7274 * the string object is first used. The object can be used by calling it's out
7275 * method or by casting the object to a string, either directly e.g.
7276 * (string)$stringobject
7277 * or indirectly by using the string within another string or echoing it out e.g.
7278 * echo $stringobject
7279 * return "<p>{$stringobject}</p>";
7280 * It is worth noting that using $lazyload and attempting to use the string as an
7281 * array key will cause a fatal error as objects cannot be used as array keys.
7282 * But you should never do that anyway!
7283 * For more information {@link lang_string}
7285 * @category string
7286 * @param string $identifier The key identifier for the localized string
7287 * @param string $component The module where the key identifier is stored,
7288 * usually expressed as the filename in the language pack without the
7289 * .php on the end but can also be written as mod/forum or grade/export/xls.
7290 * If none is specified then moodle.php is used.
7291 * @param string|object|array $a An object, string or number that can be used
7292 * within translation strings
7293 * @param bool $lazyload If set to true a string object is returned instead of
7294 * the string itself. The string then isn't calculated until it is first used.
7295 * @return string The localized string.
7296 * @throws coding_exception
7298 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7299 global $CFG;
7301 // If the lazy load argument has been supplied return a lang_string object
7302 // instead.
7303 // We need to make sure it is true (and a bool) as you will see below there
7304 // used to be a forth argument at one point.
7305 if ($lazyload === true) {
7306 return new lang_string($identifier, $component, $a);
7309 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7310 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7313 // There is now a forth argument again, this time it is a boolean however so
7314 // we can still check for the old extralocations parameter.
7315 if (!is_bool($lazyload) && !empty($lazyload)) {
7316 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7319 if (strpos($component, '/') !== false) {
7320 debugging('The module name you passed to get_string is the deprecated format ' .
7321 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7322 $componentpath = explode('/', $component);
7324 switch ($componentpath[0]) {
7325 case 'mod':
7326 $component = $componentpath[1];
7327 break;
7328 case 'blocks':
7329 case 'block':
7330 $component = 'block_'.$componentpath[1];
7331 break;
7332 case 'enrol':
7333 $component = 'enrol_'.$componentpath[1];
7334 break;
7335 case 'format':
7336 $component = 'format_'.$componentpath[1];
7337 break;
7338 case 'grade':
7339 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7340 break;
7344 $result = get_string_manager()->get_string($identifier, $component, $a);
7346 // Debugging feature lets you display string identifier and component.
7347 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7348 $result .= ' {' . $identifier . '/' . $component . '}';
7350 return $result;
7354 * Converts an array of strings to their localized value.
7356 * @param array $array An array of strings
7357 * @param string $component The language module that these strings can be found in.
7358 * @return stdClass translated strings.
7360 function get_strings($array, $component = '') {
7361 $string = new stdClass;
7362 foreach ($array as $item) {
7363 $string->$item = get_string($item, $component);
7365 return $string;
7369 * Prints out a translated string.
7371 * Prints out a translated string using the return value from the {@link get_string()} function.
7373 * Example usage of this function when the string is in the moodle.php file:<br/>
7374 * <code>
7375 * echo '<strong>';
7376 * print_string('course');
7377 * echo '</strong>';
7378 * </code>
7380 * Example usage of this function when the string is not in the moodle.php file:<br/>
7381 * <code>
7382 * echo '<h1>';
7383 * print_string('typecourse', 'calendar');
7384 * echo '</h1>';
7385 * </code>
7387 * @category string
7388 * @param string $identifier The key identifier for the localized string
7389 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7390 * @param string|object|array $a An object, string or number that can be used within translation strings
7392 function print_string($identifier, $component = '', $a = null) {
7393 echo get_string($identifier, $component, $a);
7397 * Returns a list of charset codes
7399 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7400 * (checking that such charset is supported by the texlib library!)
7402 * @return array And associative array with contents in the form of charset => charset
7404 function get_list_of_charsets() {
7406 $charsets = array(
7407 'EUC-JP' => 'EUC-JP',
7408 'ISO-2022-JP'=> 'ISO-2022-JP',
7409 'ISO-8859-1' => 'ISO-8859-1',
7410 'SHIFT-JIS' => 'SHIFT-JIS',
7411 'GB2312' => 'GB2312',
7412 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7413 'UTF-8' => 'UTF-8');
7415 asort($charsets);
7417 return $charsets;
7421 * Returns a list of valid and compatible themes
7423 * @return array
7425 function get_list_of_themes() {
7426 global $CFG;
7428 $themes = array();
7430 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7431 $themelist = explode(',', $CFG->themelist);
7432 } else {
7433 $themelist = array_keys(core_component::get_plugin_list("theme"));
7436 foreach ($themelist as $key => $themename) {
7437 $theme = theme_config::load($themename);
7438 $themes[$themename] = $theme;
7441 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7443 return $themes;
7447 * Factory function for emoticon_manager
7449 * @return emoticon_manager singleton
7451 function get_emoticon_manager() {
7452 static $singleton = null;
7454 if (is_null($singleton)) {
7455 $singleton = new emoticon_manager();
7458 return $singleton;
7462 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7464 * Whenever this manager mentiones 'emoticon object', the following data
7465 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7466 * altidentifier and altcomponent
7468 * @see admin_setting_emoticons
7470 * @copyright 2010 David Mudrak
7471 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7473 class emoticon_manager {
7476 * Returns the currently enabled emoticons
7478 * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
7479 * @return array of emoticon objects
7481 public function get_emoticons($selectable = false) {
7482 global $CFG;
7483 $notselectable = ['martin', 'egg'];
7485 if (empty($CFG->emoticons)) {
7486 return array();
7489 $emoticons = $this->decode_stored_config($CFG->emoticons);
7491 if (!is_array($emoticons)) {
7492 // Something is wrong with the format of stored setting.
7493 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7494 return array();
7496 if ($selectable) {
7497 foreach ($emoticons as $index => $emote) {
7498 if (in_array($emote->altidentifier, $notselectable)) {
7499 // Skip this one.
7500 unset($emoticons[$index]);
7505 return $emoticons;
7509 * Converts emoticon object into renderable pix_emoticon object
7511 * @param stdClass $emoticon emoticon object
7512 * @param array $attributes explicit HTML attributes to set
7513 * @return pix_emoticon
7515 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7516 $stringmanager = get_string_manager();
7517 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7518 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7519 } else {
7520 $alt = s($emoticon->text);
7522 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7526 * Encodes the array of emoticon objects into a string storable in config table
7528 * @see self::decode_stored_config()
7529 * @param array $emoticons array of emtocion objects
7530 * @return string
7532 public function encode_stored_config(array $emoticons) {
7533 return json_encode($emoticons);
7537 * Decodes the string into an array of emoticon objects
7539 * @see self::encode_stored_config()
7540 * @param string $encoded
7541 * @return string|null
7543 public function decode_stored_config($encoded) {
7544 $decoded = json_decode($encoded);
7545 if (!is_array($decoded)) {
7546 return null;
7548 return $decoded;
7552 * Returns default set of emoticons supported by Moodle
7554 * @return array of sdtClasses
7556 public function default_emoticons() {
7557 return array(
7558 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7559 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7560 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7561 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7562 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7563 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7564 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7565 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7566 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7567 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7568 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7569 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7570 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7571 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7572 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7573 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7574 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7575 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7576 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7577 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7578 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7579 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7580 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7581 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7582 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7583 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7584 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7585 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7586 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7587 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7592 * Helper method preparing the stdClass with the emoticon properties
7594 * @param string|array $text or array of strings
7595 * @param string $imagename to be used by {@link pix_emoticon}
7596 * @param string $altidentifier alternative string identifier, null for no alt
7597 * @param string $altcomponent where the alternative string is defined
7598 * @param string $imagecomponent to be used by {@link pix_emoticon}
7599 * @return stdClass
7601 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7602 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7603 return (object)array(
7604 'text' => $text,
7605 'imagename' => $imagename,
7606 'imagecomponent' => $imagecomponent,
7607 'altidentifier' => $altidentifier,
7608 'altcomponent' => $altcomponent,
7613 // ENCRYPTION.
7616 * rc4encrypt
7618 * @param string $data Data to encrypt.
7619 * @return string The now encrypted data.
7621 function rc4encrypt($data) {
7622 return endecrypt(get_site_identifier(), $data, '');
7626 * rc4decrypt
7628 * @param string $data Data to decrypt.
7629 * @return string The now decrypted data.
7631 function rc4decrypt($data) {
7632 return endecrypt(get_site_identifier(), $data, 'de');
7636 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7638 * @todo Finish documenting this function
7640 * @param string $pwd The password to use when encrypting or decrypting
7641 * @param string $data The data to be decrypted/encrypted
7642 * @param string $case Either 'de' for decrypt or '' for encrypt
7643 * @return string
7645 function endecrypt ($pwd, $data, $case) {
7647 if ($case == 'de') {
7648 $data = urldecode($data);
7651 $key[] = '';
7652 $box[] = '';
7653 $pwdlength = strlen($pwd);
7655 for ($i = 0; $i <= 255; $i++) {
7656 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7657 $box[$i] = $i;
7660 $x = 0;
7662 for ($i = 0; $i <= 255; $i++) {
7663 $x = ($x + $box[$i] + $key[$i]) % 256;
7664 $tempswap = $box[$i];
7665 $box[$i] = $box[$x];
7666 $box[$x] = $tempswap;
7669 $cipher = '';
7671 $a = 0;
7672 $j = 0;
7674 for ($i = 0; $i < strlen($data); $i++) {
7675 $a = ($a + 1) % 256;
7676 $j = ($j + $box[$a]) % 256;
7677 $temp = $box[$a];
7678 $box[$a] = $box[$j];
7679 $box[$j] = $temp;
7680 $k = $box[(($box[$a] + $box[$j]) % 256)];
7681 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7682 $cipher .= chr($cipherby);
7685 if ($case == 'de') {
7686 $cipher = urldecode(urlencode($cipher));
7687 } else {
7688 $cipher = urlencode($cipher);
7691 return $cipher;
7694 // ENVIRONMENT CHECKING.
7697 * This method validates a plug name. It is much faster than calling clean_param.
7699 * @param string $name a string that might be a plugin name.
7700 * @return bool if this string is a valid plugin name.
7702 function is_valid_plugin_name($name) {
7703 // This does not work for 'mod', bad luck, use any other type.
7704 return core_component::is_valid_plugin_name('tool', $name);
7708 * Get a list of all the plugins of a given type that define a certain API function
7709 * in a certain file. The plugin component names and function names are returned.
7711 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7712 * @param string $function the part of the name of the function after the
7713 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7714 * names like report_courselist_hook.
7715 * @param string $file the name of file within the plugin that defines the
7716 * function. Defaults to lib.php.
7717 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7718 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7720 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7721 global $CFG;
7723 // We don't include here as all plugin types files would be included.
7724 $plugins = get_plugins_with_function($function, $file, false);
7726 if (empty($plugins[$plugintype])) {
7727 return array();
7730 $allplugins = core_component::get_plugin_list($plugintype);
7732 // Reformat the array and include the files.
7733 $pluginfunctions = array();
7734 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7736 // Check that it has not been removed and the file is still available.
7737 if (!empty($allplugins[$pluginname])) {
7739 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7740 if (file_exists($filepath)) {
7741 include_once($filepath);
7743 // Now that the file is loaded, we must verify the function still exists.
7744 if (function_exists($functionname)) {
7745 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7746 } else {
7747 // Invalidate the cache for next run.
7748 \cache_helper::invalidate_by_definition('core', 'plugin_functions');
7754 return $pluginfunctions;
7758 * Get a list of all the plugins that define a certain API function in a certain file.
7760 * @param string $function the part of the name of the function after the
7761 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7762 * names like report_courselist_hook.
7763 * @param string $file the name of file within the plugin that defines the
7764 * function. Defaults to lib.php.
7765 * @param bool $include Whether to include the files that contain the functions or not.
7766 * @return array with [plugintype][plugin] = functionname
7768 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7769 global $CFG;
7771 if (during_initial_install() || isset($CFG->upgraderunning)) {
7772 // API functions _must not_ be called during an installation or upgrade.
7773 return [];
7776 $cache = \cache::make('core', 'plugin_functions');
7778 // Including both although I doubt that we will find two functions definitions with the same name.
7779 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7780 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7781 $pluginfunctions = $cache->get($key);
7782 $dirty = false;
7784 // Use the plugin manager to check that plugins are currently installed.
7785 $pluginmanager = \core_plugin_manager::instance();
7787 if ($pluginfunctions !== false) {
7789 // Checking that the files are still available.
7790 foreach ($pluginfunctions as $plugintype => $plugins) {
7792 $allplugins = \core_component::get_plugin_list($plugintype);
7793 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7794 foreach ($plugins as $plugin => $function) {
7795 if (!isset($installedplugins[$plugin])) {
7796 // Plugin code is still present on disk but it is not installed.
7797 $dirty = true;
7798 break 2;
7801 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7802 if (empty($allplugins[$plugin])) {
7803 $dirty = true;
7804 break 2;
7807 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7808 if ($include && $fileexists) {
7809 // Include the files if it was requested.
7810 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7811 } else if (!$fileexists) {
7812 // If the file is not available any more it should not be returned.
7813 $dirty = true;
7814 break 2;
7817 // Check if the function still exists in the file.
7818 if ($include && !function_exists($function)) {
7819 $dirty = true;
7820 break 2;
7825 // If the cache is dirty, we should fall through and let it rebuild.
7826 if (!$dirty) {
7827 return $pluginfunctions;
7831 $pluginfunctions = array();
7833 // To fill the cached. Also, everything should continue working with cache disabled.
7834 $plugintypes = \core_component::get_plugin_types();
7835 foreach ($plugintypes as $plugintype => $unused) {
7837 // We need to include files here.
7838 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7839 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7840 foreach ($pluginswithfile as $plugin => $notused) {
7842 if (!isset($installedplugins[$plugin])) {
7843 continue;
7846 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7848 $pluginfunction = false;
7849 if (function_exists($fullfunction)) {
7850 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7851 $pluginfunction = $fullfunction;
7853 } else if ($plugintype === 'mod') {
7854 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7855 $shortfunction = $plugin . '_' . $function;
7856 if (function_exists($shortfunction)) {
7857 $pluginfunction = $shortfunction;
7861 if ($pluginfunction) {
7862 if (empty($pluginfunctions[$plugintype])) {
7863 $pluginfunctions[$plugintype] = array();
7865 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7870 $cache->set($key, $pluginfunctions);
7872 return $pluginfunctions;
7877 * Lists plugin-like directories within specified directory
7879 * This function was originally used for standard Moodle plugins, please use
7880 * new core_component::get_plugin_list() now.
7882 * This function is used for general directory listing and backwards compatility.
7884 * @param string $directory relative directory from root
7885 * @param string $exclude dir name to exclude from the list (defaults to none)
7886 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7887 * @return array Sorted array of directory names found under the requested parameters
7889 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7890 global $CFG;
7892 $plugins = array();
7894 if (empty($basedir)) {
7895 $basedir = $CFG->dirroot .'/'. $directory;
7897 } else {
7898 $basedir = $basedir .'/'. $directory;
7901 if ($CFG->debugdeveloper and empty($exclude)) {
7902 // Make sure devs do not use this to list normal plugins,
7903 // this is intended for general directories that are not plugins!
7905 $subtypes = core_component::get_plugin_types();
7906 if (in_array($basedir, $subtypes)) {
7907 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7909 unset($subtypes);
7912 $ignorelist = array_flip(array_filter([
7913 'CVS',
7914 '_vti_cnf',
7915 'amd',
7916 'classes',
7917 'simpletest',
7918 'tests',
7919 'templates',
7920 'yui',
7921 $exclude,
7922 ]));
7924 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7925 if (!$dirhandle = opendir($basedir)) {
7926 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7927 return array();
7929 while (false !== ($dir = readdir($dirhandle))) {
7930 if (strpos($dir, '.') === 0) {
7931 // Ignore directories starting with .
7932 // These are treated as hidden directories.
7933 continue;
7935 if (array_key_exists($dir, $ignorelist)) {
7936 // This directory features on the ignore list.
7937 continue;
7939 if (filetype($basedir .'/'. $dir) != 'dir') {
7940 continue;
7942 $plugins[] = $dir;
7944 closedir($dirhandle);
7946 if ($plugins) {
7947 asort($plugins);
7949 return $plugins;
7953 * Invoke plugin's callback functions
7955 * @param string $type plugin type e.g. 'mod'
7956 * @param string $name plugin name
7957 * @param string $feature feature name
7958 * @param string $action feature's action
7959 * @param array $params parameters of callback function, should be an array
7960 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7961 * @return mixed
7963 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7965 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7966 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7970 * Invoke component's callback functions
7972 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7973 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7974 * @param array $params parameters of callback function
7975 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7976 * @return mixed
7978 function component_callback($component, $function, array $params = array(), $default = null) {
7980 $functionname = component_callback_exists($component, $function);
7982 if ($params && (array_keys($params) !== range(0, count($params) - 1))) {
7983 // PHP 8 allows to have associative arrays in the call_user_func_array() parameters but
7984 // PHP 7 does not. Using associative arrays can result in different behavior in different PHP versions.
7985 // See https://php.watch/versions/8.0/named-parameters#named-params-call_user_func_array
7986 // This check can be removed when minimum PHP version for Moodle is raised to 8.
7987 debugging('Parameters array can not be an associative array while Moodle supports both PHP 7 and PHP 8.',
7988 DEBUG_DEVELOPER);
7989 $params = array_values($params);
7992 if ($functionname) {
7993 // Function exists, so just return function result.
7994 $ret = call_user_func_array($functionname, $params);
7995 if (is_null($ret)) {
7996 return $default;
7997 } else {
7998 return $ret;
8001 return $default;
8005 * Determine if a component callback exists and return the function name to call. Note that this
8006 * function will include the required library files so that the functioname returned can be
8007 * called directly.
8009 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
8010 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
8011 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
8012 * @throws coding_exception if invalid component specfied
8014 function component_callback_exists($component, $function) {
8015 global $CFG; // This is needed for the inclusions.
8017 $cleancomponent = clean_param($component, PARAM_COMPONENT);
8018 if (empty($cleancomponent)) {
8019 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8021 $component = $cleancomponent;
8023 list($type, $name) = core_component::normalize_component($component);
8024 $component = $type . '_' . $name;
8026 $oldfunction = $name.'_'.$function;
8027 $function = $component.'_'.$function;
8029 $dir = core_component::get_component_directory($component);
8030 if (empty($dir)) {
8031 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8034 // Load library and look for function.
8035 if (file_exists($dir.'/lib.php')) {
8036 require_once($dir.'/lib.php');
8039 if (!function_exists($function) and function_exists($oldfunction)) {
8040 if ($type !== 'mod' and $type !== 'core') {
8041 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
8043 $function = $oldfunction;
8046 if (function_exists($function)) {
8047 return $function;
8049 return false;
8053 * Call the specified callback method on the provided class.
8055 * If the callback returns null, then the default value is returned instead.
8056 * If the class does not exist, then the default value is returned.
8058 * @param string $classname The name of the class to call upon.
8059 * @param string $methodname The name of the staticically defined method on the class.
8060 * @param array $params The arguments to pass into the method.
8061 * @param mixed $default The default value.
8062 * @return mixed The return value.
8064 function component_class_callback($classname, $methodname, array $params, $default = null) {
8065 if (!class_exists($classname)) {
8066 return $default;
8069 if (!method_exists($classname, $methodname)) {
8070 return $default;
8073 $fullfunction = $classname . '::' . $methodname;
8074 $result = call_user_func_array($fullfunction, $params);
8076 if (null === $result) {
8077 return $default;
8078 } else {
8079 return $result;
8084 * Checks whether a plugin supports a specified feature.
8086 * @param string $type Plugin type e.g. 'mod'
8087 * @param string $name Plugin name e.g. 'forum'
8088 * @param string $feature Feature code (FEATURE_xx constant)
8089 * @param mixed $default default value if feature support unknown
8090 * @return mixed Feature result (false if not supported, null if feature is unknown,
8091 * otherwise usually true but may have other feature-specific value such as array)
8092 * @throws coding_exception
8094 function plugin_supports($type, $name, $feature, $default = null) {
8095 global $CFG;
8097 if ($type === 'mod' and $name === 'NEWMODULE') {
8098 // Somebody forgot to rename the module template.
8099 return false;
8102 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
8103 if (empty($component)) {
8104 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8107 $function = null;
8109 if ($type === 'mod') {
8110 // We need this special case because we support subplugins in modules,
8111 // otherwise it would end up in infinite loop.
8112 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8113 include_once("$CFG->dirroot/mod/$name/lib.php");
8114 $function = $component.'_supports';
8115 if (!function_exists($function)) {
8116 // Legacy non-frankenstyle function name.
8117 $function = $name.'_supports';
8121 } else {
8122 if (!$path = core_component::get_plugin_directory($type, $name)) {
8123 // Non existent plugin type.
8124 return false;
8126 if (file_exists("$path/lib.php")) {
8127 include_once("$path/lib.php");
8128 $function = $component.'_supports';
8132 if ($function and function_exists($function)) {
8133 $supports = $function($feature);
8134 if (is_null($supports)) {
8135 // Plugin does not know - use default.
8136 return $default;
8137 } else {
8138 return $supports;
8142 // Plugin does not care, so use default.
8143 return $default;
8147 * Returns true if the current version of PHP is greater that the specified one.
8149 * @todo Check PHP version being required here is it too low?
8151 * @param string $version The version of php being tested.
8152 * @return bool
8154 function check_php_version($version='5.2.4') {
8155 return (version_compare(phpversion(), $version) >= 0);
8159 * Determine if moodle installation requires update.
8161 * Checks version numbers of main code and all plugins to see
8162 * if there are any mismatches.
8164 * @return bool
8166 function moodle_needs_upgrading() {
8167 global $CFG;
8169 if (empty($CFG->version)) {
8170 return true;
8173 // There is no need to purge plugininfo caches here because
8174 // these caches are not used during upgrade and they are purged after
8175 // every upgrade.
8177 if (empty($CFG->allversionshash)) {
8178 return true;
8181 $hash = core_component::get_all_versions_hash();
8183 return ($hash !== $CFG->allversionshash);
8187 * Returns the major version of this site
8189 * Moodle version numbers consist of three numbers separated by a dot, for
8190 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
8191 * called major version. This function extracts the major version from either
8192 * $CFG->release (default) or eventually from the $release variable defined in
8193 * the main version.php.
8195 * @param bool $fromdisk should the version if source code files be used
8196 * @return string|false the major version like '2.3', false if could not be determined
8198 function moodle_major_version($fromdisk = false) {
8199 global $CFG;
8201 if ($fromdisk) {
8202 $release = null;
8203 require($CFG->dirroot.'/version.php');
8204 if (empty($release)) {
8205 return false;
8208 } else {
8209 if (empty($CFG->release)) {
8210 return false;
8212 $release = $CFG->release;
8215 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8216 return $matches[0];
8217 } else {
8218 return false;
8222 // MISCELLANEOUS.
8225 * Gets the system locale
8227 * @return string Retuns the current locale.
8229 function moodle_getlocale() {
8230 global $CFG;
8232 // Fetch the correct locale based on ostype.
8233 if ($CFG->ostype == 'WINDOWS') {
8234 $stringtofetch = 'localewin';
8235 } else {
8236 $stringtofetch = 'locale';
8239 if (!empty($CFG->locale)) { // Override locale for all language packs.
8240 return $CFG->locale;
8243 return get_string($stringtofetch, 'langconfig');
8247 * Sets the system locale
8249 * @category string
8250 * @param string $locale Can be used to force a locale
8252 function moodle_setlocale($locale='') {
8253 global $CFG;
8255 static $currentlocale = ''; // Last locale caching.
8257 $oldlocale = $currentlocale;
8259 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8260 if (!empty($locale)) {
8261 $currentlocale = $locale;
8262 } else {
8263 $currentlocale = moodle_getlocale();
8266 // Do nothing if locale already set up.
8267 if ($oldlocale == $currentlocale) {
8268 return;
8271 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8272 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8273 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8275 // Get current values.
8276 $monetary= setlocale (LC_MONETARY, 0);
8277 $numeric = setlocale (LC_NUMERIC, 0);
8278 $ctype = setlocale (LC_CTYPE, 0);
8279 if ($CFG->ostype != 'WINDOWS') {
8280 $messages= setlocale (LC_MESSAGES, 0);
8282 // Set locale to all.
8283 $result = setlocale (LC_ALL, $currentlocale);
8284 // If setting of locale fails try the other utf8 or utf-8 variant,
8285 // some operating systems support both (Debian), others just one (OSX).
8286 if ($result === false) {
8287 if (stripos($currentlocale, '.UTF-8') !== false) {
8288 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8289 setlocale (LC_ALL, $newlocale);
8290 } else if (stripos($currentlocale, '.UTF8') !== false) {
8291 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8292 setlocale (LC_ALL, $newlocale);
8295 // Set old values.
8296 setlocale (LC_MONETARY, $monetary);
8297 setlocale (LC_NUMERIC, $numeric);
8298 if ($CFG->ostype != 'WINDOWS') {
8299 setlocale (LC_MESSAGES, $messages);
8301 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8302 // To workaround a well-known PHP problem with Turkish letter Ii.
8303 setlocale (LC_CTYPE, $ctype);
8308 * Count words in a string.
8310 * Words are defined as things between whitespace.
8312 * @category string
8313 * @param string $string The text to be searched for words. May be HTML.
8314 * @return int The count of words in the specified string
8316 function count_words($string) {
8317 // Before stripping tags, add a space after the close tag of anything that is not obviously inline.
8318 // Also, br is a special case because it definitely delimits a word, but has no close tag.
8319 $string = preg_replace('~
8320 ( # Capture the tag we match.
8321 </ # Start of close tag.
8322 (?! # Do not match any of these specific close tag names.
8323 a> | b> | del> | em> | i> |
8324 ins> | s> | small> |
8325 strong> | sub> | sup> | u>
8327 \w+ # But, apart from those execptions, match any tag name.
8328 > # End of close tag.
8330 <br> | <br\s*/> # Special cases that are not close tags.
8332 ~x', '$1 ', $string); // Add a space after the close tag.
8333 // Now remove HTML tags.
8334 $string = strip_tags($string);
8335 // Decode HTML entities.
8336 $string = html_entity_decode($string);
8338 // Now, the word count is the number of blocks of characters separated
8339 // by any sort of space. That seems to be the definition used by all other systems.
8340 // To be precise about what is considered to separate words:
8341 // * Anything that Unicode considers a 'Separator'
8342 // * Anything that Unicode considers a 'Control character'
8343 // * An em- or en- dash.
8344 return count(preg_split('~[\p{Z}\p{Cc}—–]+~u', $string, -1, PREG_SPLIT_NO_EMPTY));
8348 * Count letters in a string.
8350 * Letters are defined as chars not in tags and different from whitespace.
8352 * @category string
8353 * @param string $string The text to be searched for letters. May be HTML.
8354 * @return int The count of letters in the specified text.
8356 function count_letters($string) {
8357 $string = strip_tags($string); // Tags are out now.
8358 $string = html_entity_decode($string);
8359 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8361 return core_text::strlen($string);
8365 * Generate and return a random string of the specified length.
8367 * @param int $length The length of the string to be created.
8368 * @return string
8370 function random_string($length=15) {
8371 $randombytes = random_bytes_emulate($length);
8372 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8373 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8374 $pool .= '0123456789';
8375 $poollen = strlen($pool);
8376 $string = '';
8377 for ($i = 0; $i < $length; $i++) {
8378 $rand = ord($randombytes[$i]);
8379 $string .= substr($pool, ($rand%($poollen)), 1);
8381 return $string;
8385 * Generate a complex random string (useful for md5 salts)
8387 * This function is based on the above {@link random_string()} however it uses a
8388 * larger pool of characters and generates a string between 24 and 32 characters
8390 * @param int $length Optional if set generates a string to exactly this length
8391 * @return string
8393 function complex_random_string($length=null) {
8394 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8395 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8396 $poollen = strlen($pool);
8397 if ($length===null) {
8398 $length = floor(rand(24, 32));
8400 $randombytes = random_bytes_emulate($length);
8401 $string = '';
8402 for ($i = 0; $i < $length; $i++) {
8403 $rand = ord($randombytes[$i]);
8404 $string .= $pool[($rand%$poollen)];
8406 return $string;
8410 * Try to generates cryptographically secure pseudo-random bytes.
8412 * Note this is achieved by fallbacking between:
8413 * - PHP 7 random_bytes().
8414 * - OpenSSL openssl_random_pseudo_bytes().
8415 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8417 * @param int $length requested length in bytes
8418 * @return string binary data
8420 function random_bytes_emulate($length) {
8421 global $CFG;
8422 if ($length <= 0) {
8423 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8424 return '';
8426 if (function_exists('random_bytes')) {
8427 // Use PHP 7 goodness.
8428 $hash = @random_bytes($length);
8429 if ($hash !== false) {
8430 return $hash;
8433 if (function_exists('openssl_random_pseudo_bytes')) {
8434 // If you have the openssl extension enabled.
8435 $hash = openssl_random_pseudo_bytes($length);
8436 if ($hash !== false) {
8437 return $hash;
8441 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8442 $staticdata = serialize($CFG) . serialize($_SERVER);
8443 $hash = '';
8444 do {
8445 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8446 } while (strlen($hash) < $length);
8448 return substr($hash, 0, $length);
8452 * Given some text (which may contain HTML) and an ideal length,
8453 * this function truncates the text neatly on a word boundary if possible
8455 * @category string
8456 * @param string $text text to be shortened
8457 * @param int $ideal ideal string length
8458 * @param boolean $exact if false, $text will not be cut mid-word
8459 * @param string $ending The string to append if the passed string is truncated
8460 * @return string $truncate shortened string
8462 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8463 // If the plain text is shorter than the maximum length, return the whole text.
8464 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8465 return $text;
8468 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8469 // and only tag in its 'line'.
8470 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8472 $totallength = core_text::strlen($ending);
8473 $truncate = '';
8475 // This array stores information about open and close tags and their position
8476 // in the truncated string. Each item in the array is an object with fields
8477 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8478 // (byte position in truncated text).
8479 $tagdetails = array();
8481 foreach ($lines as $linematchings) {
8482 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8483 if (!empty($linematchings[1])) {
8484 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8485 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8486 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8487 // Record closing tag.
8488 $tagdetails[] = (object) array(
8489 'open' => false,
8490 'tag' => core_text::strtolower($tagmatchings[1]),
8491 'pos' => core_text::strlen($truncate),
8494 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8495 // Record opening tag.
8496 $tagdetails[] = (object) array(
8497 'open' => true,
8498 'tag' => core_text::strtolower($tagmatchings[1]),
8499 'pos' => core_text::strlen($truncate),
8501 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8502 $tagdetails[] = (object) array(
8503 'open' => true,
8504 'tag' => core_text::strtolower('if'),
8505 'pos' => core_text::strlen($truncate),
8507 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8508 $tagdetails[] = (object) array(
8509 'open' => false,
8510 'tag' => core_text::strtolower('if'),
8511 'pos' => core_text::strlen($truncate),
8515 // Add html-tag to $truncate'd text.
8516 $truncate .= $linematchings[1];
8519 // Calculate the length of the plain text part of the line; handle entities as one character.
8520 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8521 if ($totallength + $contentlength > $ideal) {
8522 // The number of characters which are left.
8523 $left = $ideal - $totallength;
8524 $entitieslength = 0;
8525 // Search for html entities.
8526 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)) {
8527 // Calculate the real length of all entities in the legal range.
8528 foreach ($entities[0] as $entity) {
8529 if ($entity[1]+1-$entitieslength <= $left) {
8530 $left--;
8531 $entitieslength += core_text::strlen($entity[0]);
8532 } else {
8533 // No more characters left.
8534 break;
8538 $breakpos = $left + $entitieslength;
8540 // If the words shouldn't be cut in the middle...
8541 if (!$exact) {
8542 // Search the last occurence of a space.
8543 for (; $breakpos > 0; $breakpos--) {
8544 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8545 if ($char === '.' or $char === ' ') {
8546 $breakpos += 1;
8547 break;
8548 } else if (strlen($char) > 2) {
8549 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8550 $breakpos += 1;
8551 break;
8556 if ($breakpos == 0) {
8557 // This deals with the test_shorten_text_no_spaces case.
8558 $breakpos = $left + $entitieslength;
8559 } else if ($breakpos > $left + $entitieslength) {
8560 // This deals with the previous for loop breaking on the first char.
8561 $breakpos = $left + $entitieslength;
8564 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8565 // Maximum length is reached, so get off the loop.
8566 break;
8567 } else {
8568 $truncate .= $linematchings[2];
8569 $totallength += $contentlength;
8572 // If the maximum length is reached, get off the loop.
8573 if ($totallength >= $ideal) {
8574 break;
8578 // Add the defined ending to the text.
8579 $truncate .= $ending;
8581 // Now calculate the list of open html tags based on the truncate position.
8582 $opentags = array();
8583 foreach ($tagdetails as $taginfo) {
8584 if ($taginfo->open) {
8585 // Add tag to the beginning of $opentags list.
8586 array_unshift($opentags, $taginfo->tag);
8587 } else {
8588 // Can have multiple exact same open tags, close the last one.
8589 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8590 if ($pos !== false) {
8591 unset($opentags[$pos]);
8596 // Close all unclosed html-tags.
8597 foreach ($opentags as $tag) {
8598 if ($tag === 'if') {
8599 $truncate .= '<!--<![endif]-->';
8600 } else {
8601 $truncate .= '</' . $tag . '>';
8605 return $truncate;
8609 * Shortens a given filename by removing characters positioned after the ideal string length.
8610 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8611 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8613 * @param string $filename file name
8614 * @param int $length ideal string length
8615 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8616 * @return string $shortened shortened file name
8618 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8619 $shortened = $filename;
8620 // Extract a part of the filename if it's char size exceeds the ideal string length.
8621 if (core_text::strlen($filename) > $length) {
8622 // Exclude extension if present in filename.
8623 $mimetypes = get_mimetypes_array();
8624 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8625 if ($extension && !empty($mimetypes[$extension])) {
8626 $basename = pathinfo($filename, PATHINFO_FILENAME);
8627 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8628 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8629 $shortened .= '.' . $extension;
8630 } else {
8631 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8632 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8635 return $shortened;
8639 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8641 * @param array $path The paths to reduce the length.
8642 * @param int $length Ideal string length
8643 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8644 * @return array $result Shortened paths in array.
8646 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8647 $result = null;
8649 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8650 $carry[] = shorten_filename($singlepath, $length, $includehash);
8651 return $carry;
8652 }, []);
8654 return $result;
8658 * Given dates in seconds, how many weeks is the date from startdate
8659 * The first week is 1, the second 2 etc ...
8661 * @param int $startdate Timestamp for the start date
8662 * @param int $thedate Timestamp for the end date
8663 * @return string
8665 function getweek ($startdate, $thedate) {
8666 if ($thedate < $startdate) {
8667 return 0;
8670 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8674 * Returns a randomly generated password of length $maxlen. inspired by
8676 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8677 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8679 * @param int $maxlen The maximum size of the password being generated.
8680 * @return string
8682 function generate_password($maxlen=10) {
8683 global $CFG;
8685 if (empty($CFG->passwordpolicy)) {
8686 $fillers = PASSWORD_DIGITS;
8687 $wordlist = file($CFG->wordlist);
8688 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8689 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8690 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8691 $password = $word1 . $filler1 . $word2;
8692 } else {
8693 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8694 $digits = $CFG->minpassworddigits;
8695 $lower = $CFG->minpasswordlower;
8696 $upper = $CFG->minpasswordupper;
8697 $nonalphanum = $CFG->minpasswordnonalphanum;
8698 $total = $lower + $upper + $digits + $nonalphanum;
8699 // Var minlength should be the greater one of the two ( $minlen and $total ).
8700 $minlen = $minlen < $total ? $total : $minlen;
8701 // Var maxlen can never be smaller than minlen.
8702 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8703 $additional = $maxlen - $total;
8705 // Make sure we have enough characters to fulfill
8706 // complexity requirements.
8707 $passworddigits = PASSWORD_DIGITS;
8708 while ($digits > strlen($passworddigits)) {
8709 $passworddigits .= PASSWORD_DIGITS;
8711 $passwordlower = PASSWORD_LOWER;
8712 while ($lower > strlen($passwordlower)) {
8713 $passwordlower .= PASSWORD_LOWER;
8715 $passwordupper = PASSWORD_UPPER;
8716 while ($upper > strlen($passwordupper)) {
8717 $passwordupper .= PASSWORD_UPPER;
8719 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8720 while ($nonalphanum > strlen($passwordnonalphanum)) {
8721 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8724 // Now mix and shuffle it all.
8725 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8726 substr(str_shuffle ($passwordupper), 0, $upper) .
8727 substr(str_shuffle ($passworddigits), 0, $digits) .
8728 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8729 substr(str_shuffle ($passwordlower .
8730 $passwordupper .
8731 $passworddigits .
8732 $passwordnonalphanum), 0 , $additional));
8735 return substr ($password, 0, $maxlen);
8739 * Given a float, prints it nicely.
8740 * Localized floats must not be used in calculations!
8742 * The stripzeros feature is intended for making numbers look nicer in small
8743 * areas where it is not necessary to indicate the degree of accuracy by showing
8744 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8745 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8747 * @param float $float The float to print
8748 * @param int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision).
8749 * @param bool $localized use localized decimal separator
8750 * @param bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after
8751 * the decimal point are always striped if $decimalpoints is -1.
8752 * @return string locale float
8754 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8755 if (is_null($float)) {
8756 return '';
8758 if ($localized) {
8759 $separator = get_string('decsep', 'langconfig');
8760 } else {
8761 $separator = '.';
8763 if ($decimalpoints == -1) {
8764 // The following counts the number of decimals.
8765 // It is safe as both floatval() and round() functions have same behaviour when non-numeric values are provided.
8766 $floatval = floatval($float);
8767 for ($decimalpoints = 0; $floatval != round($float, $decimalpoints); $decimalpoints++);
8770 $result = number_format($float, $decimalpoints, $separator, '');
8771 if ($stripzeros) {
8772 // Remove zeros and final dot if not needed.
8773 $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
8775 return $result;
8779 * Converts locale specific floating point/comma number back to standard PHP float value
8780 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8782 * @param string $localefloat locale aware float representation
8783 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8784 * @return mixed float|bool - false or the parsed float.
8786 function unformat_float($localefloat, $strict = false) {
8787 $localefloat = trim($localefloat);
8789 if ($localefloat == '') {
8790 return null;
8793 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8794 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8796 if ($strict && !is_numeric($localefloat)) {
8797 return false;
8800 return (float)$localefloat;
8804 * Given a simple array, this shuffles it up just like shuffle()
8805 * Unlike PHP's shuffle() this function works on any machine.
8807 * @param array $array The array to be rearranged
8808 * @return array
8810 function swapshuffle($array) {
8812 $last = count($array) - 1;
8813 for ($i = 0; $i <= $last; $i++) {
8814 $from = rand(0, $last);
8815 $curr = $array[$i];
8816 $array[$i] = $array[$from];
8817 $array[$from] = $curr;
8819 return $array;
8823 * Like {@link swapshuffle()}, but works on associative arrays
8825 * @param array $array The associative array to be rearranged
8826 * @return array
8828 function swapshuffle_assoc($array) {
8830 $newarray = array();
8831 $newkeys = swapshuffle(array_keys($array));
8833 foreach ($newkeys as $newkey) {
8834 $newarray[$newkey] = $array[$newkey];
8836 return $newarray;
8840 * Given an arbitrary array, and a number of draws,
8841 * this function returns an array with that amount
8842 * of items. The indexes are retained.
8844 * @todo Finish documenting this function
8846 * @param array $array
8847 * @param int $draws
8848 * @return array
8850 function draw_rand_array($array, $draws) {
8852 $return = array();
8854 $last = count($array);
8856 if ($draws > $last) {
8857 $draws = $last;
8860 while ($draws > 0) {
8861 $last--;
8863 $keys = array_keys($array);
8864 $rand = rand(0, $last);
8866 $return[$keys[$rand]] = $array[$keys[$rand]];
8867 unset($array[$keys[$rand]]);
8869 $draws--;
8872 return $return;
8876 * Calculate the difference between two microtimes
8878 * @param string $a The first Microtime
8879 * @param string $b The second Microtime
8880 * @return string
8882 function microtime_diff($a, $b) {
8883 list($adec, $asec) = explode(' ', $a);
8884 list($bdec, $bsec) = explode(' ', $b);
8885 return $bsec - $asec + $bdec - $adec;
8889 * Given a list (eg a,b,c,d,e) this function returns
8890 * an array of 1->a, 2->b, 3->c etc
8892 * @param string $list The string to explode into array bits
8893 * @param string $separator The separator used within the list string
8894 * @return array The now assembled array
8896 function make_menu_from_list($list, $separator=',') {
8898 $array = array_reverse(explode($separator, $list), true);
8899 foreach ($array as $key => $item) {
8900 $outarray[$key+1] = trim($item);
8902 return $outarray;
8906 * Creates an array that represents all the current grades that
8907 * can be chosen using the given grading type.
8909 * Negative numbers
8910 * are scales, zero is no grade, and positive numbers are maximum
8911 * grades.
8913 * @todo Finish documenting this function or better deprecated this completely!
8915 * @param int $gradingtype
8916 * @return array
8918 function make_grades_menu($gradingtype) {
8919 global $DB;
8921 $grades = array();
8922 if ($gradingtype < 0) {
8923 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8924 return make_menu_from_list($scale->scale);
8926 } else if ($gradingtype > 0) {
8927 for ($i=$gradingtype; $i>=0; $i--) {
8928 $grades[$i] = $i .' / '. $gradingtype;
8930 return $grades;
8932 return $grades;
8936 * make_unique_id_code
8938 * @todo Finish documenting this function
8940 * @uses $_SERVER
8941 * @param string $extra Extra string to append to the end of the code
8942 * @return string
8944 function make_unique_id_code($extra = '') {
8946 $hostname = 'unknownhost';
8947 if (!empty($_SERVER['HTTP_HOST'])) {
8948 $hostname = $_SERVER['HTTP_HOST'];
8949 } else if (!empty($_ENV['HTTP_HOST'])) {
8950 $hostname = $_ENV['HTTP_HOST'];
8951 } else if (!empty($_SERVER['SERVER_NAME'])) {
8952 $hostname = $_SERVER['SERVER_NAME'];
8953 } else if (!empty($_ENV['SERVER_NAME'])) {
8954 $hostname = $_ENV['SERVER_NAME'];
8957 $date = gmdate("ymdHis");
8959 $random = random_string(6);
8961 if ($extra) {
8962 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8963 } else {
8964 return $hostname .'+'. $date .'+'. $random;
8970 * Function to check the passed address is within the passed subnet
8972 * The parameter is a comma separated string of subnet definitions.
8973 * Subnet strings can be in one of three formats:
8974 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8975 * 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)
8976 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8977 * Code for type 1 modified from user posted comments by mediator at
8978 * {@link http://au.php.net/manual/en/function.ip2long.php}
8980 * @param string $addr The address you are checking
8981 * @param string $subnetstr The string of subnet addresses
8982 * @return bool
8984 function address_in_subnet($addr, $subnetstr) {
8986 if ($addr == '0.0.0.0') {
8987 return false;
8989 $subnets = explode(',', $subnetstr);
8990 $found = false;
8991 $addr = trim($addr);
8992 $addr = cleanremoteaddr($addr, false); // Normalise.
8993 if ($addr === null) {
8994 return false;
8996 $addrparts = explode(':', $addr);
8998 $ipv6 = strpos($addr, ':');
9000 foreach ($subnets as $subnet) {
9001 $subnet = trim($subnet);
9002 if ($subnet === '') {
9003 continue;
9006 if (strpos($subnet, '/') !== false) {
9007 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
9008 list($ip, $mask) = explode('/', $subnet);
9009 $mask = trim($mask);
9010 if (!is_number($mask)) {
9011 continue; // Incorect mask number, eh?
9013 $ip = cleanremoteaddr($ip, false); // Normalise.
9014 if ($ip === null) {
9015 continue;
9017 if (strpos($ip, ':') !== false) {
9018 // IPv6.
9019 if (!$ipv6) {
9020 continue;
9022 if ($mask > 128 or $mask < 0) {
9023 continue; // Nonsense.
9025 if ($mask == 0) {
9026 return true; // Any address.
9028 if ($mask == 128) {
9029 if ($ip === $addr) {
9030 return true;
9032 continue;
9034 $ipparts = explode(':', $ip);
9035 $modulo = $mask % 16;
9036 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
9037 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
9038 if (implode(':', $ipnet) === implode(':', $addrnet)) {
9039 if ($modulo == 0) {
9040 return true;
9042 $pos = ($mask-$modulo)/16;
9043 $ipnet = hexdec($ipparts[$pos]);
9044 $addrnet = hexdec($addrparts[$pos]);
9045 $mask = 0xffff << (16 - $modulo);
9046 if (($addrnet & $mask) == ($ipnet & $mask)) {
9047 return true;
9051 } else {
9052 // IPv4.
9053 if ($ipv6) {
9054 continue;
9056 if ($mask > 32 or $mask < 0) {
9057 continue; // Nonsense.
9059 if ($mask == 0) {
9060 return true;
9062 if ($mask == 32) {
9063 if ($ip === $addr) {
9064 return true;
9066 continue;
9068 $mask = 0xffffffff << (32 - $mask);
9069 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
9070 return true;
9074 } else if (strpos($subnet, '-') !== false) {
9075 // 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.
9076 $parts = explode('-', $subnet);
9077 if (count($parts) != 2) {
9078 continue;
9081 if (strpos($subnet, ':') !== false) {
9082 // IPv6.
9083 if (!$ipv6) {
9084 continue;
9086 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9087 if ($ipstart === null) {
9088 continue;
9090 $ipparts = explode(':', $ipstart);
9091 $start = hexdec(array_pop($ipparts));
9092 $ipparts[] = trim($parts[1]);
9093 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
9094 if ($ipend === null) {
9095 continue;
9097 $ipparts[7] = '';
9098 $ipnet = implode(':', $ipparts);
9099 if (strpos($addr, $ipnet) !== 0) {
9100 continue;
9102 $ipparts = explode(':', $ipend);
9103 $end = hexdec($ipparts[7]);
9105 $addrend = hexdec($addrparts[7]);
9107 if (($addrend >= $start) and ($addrend <= $end)) {
9108 return true;
9111 } else {
9112 // IPv4.
9113 if ($ipv6) {
9114 continue;
9116 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9117 if ($ipstart === null) {
9118 continue;
9120 $ipparts = explode('.', $ipstart);
9121 $ipparts[3] = trim($parts[1]);
9122 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
9123 if ($ipend === null) {
9124 continue;
9127 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9128 return true;
9132 } else {
9133 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9134 if (strpos($subnet, ':') !== false) {
9135 // IPv6.
9136 if (!$ipv6) {
9137 continue;
9139 $parts = explode(':', $subnet);
9140 $count = count($parts);
9141 if ($parts[$count-1] === '') {
9142 unset($parts[$count-1]); // Trim trailing :'s.
9143 $count--;
9144 $subnet = implode('.', $parts);
9146 $isip = cleanremoteaddr($subnet, false); // Normalise.
9147 if ($isip !== null) {
9148 if ($isip === $addr) {
9149 return true;
9151 continue;
9152 } else if ($count > 8) {
9153 continue;
9155 $zeros = array_fill(0, 8-$count, '0');
9156 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9157 if (address_in_subnet($addr, $subnet)) {
9158 return true;
9161 } else {
9162 // IPv4.
9163 if ($ipv6) {
9164 continue;
9166 $parts = explode('.', $subnet);
9167 $count = count($parts);
9168 if ($parts[$count-1] === '') {
9169 unset($parts[$count-1]); // Trim trailing .
9170 $count--;
9171 $subnet = implode('.', $parts);
9173 if ($count == 4) {
9174 $subnet = cleanremoteaddr($subnet, false); // Normalise.
9175 if ($subnet === $addr) {
9176 return true;
9178 continue;
9179 } else if ($count > 4) {
9180 continue;
9182 $zeros = array_fill(0, 4-$count, '0');
9183 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9184 if (address_in_subnet($addr, $subnet)) {
9185 return true;
9191 return false;
9195 * For outputting debugging info
9197 * @param string $string The string to write
9198 * @param string $eol The end of line char(s) to use
9199 * @param string $sleep Period to make the application sleep
9200 * This ensures any messages have time to display before redirect
9202 function mtrace($string, $eol="\n", $sleep=0) {
9203 global $CFG;
9205 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
9206 $fn = $CFG->mtrace_wrapper;
9207 $fn($string, $eol);
9208 return;
9209 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
9210 // We must explicitly call the add_line function here.
9211 // Uses of fwrite to STDOUT are not picked up by ob_start.
9212 if ($output = \core\task\logmanager::add_line("{$string}{$eol}")) {
9213 fwrite(STDOUT, $output);
9215 } else {
9216 echo $string . $eol;
9219 // Flush again.
9220 flush();
9222 // Delay to keep message on user's screen in case of subsequent redirect.
9223 if ($sleep) {
9224 sleep($sleep);
9229 * Replace 1 or more slashes or backslashes to 1 slash
9231 * @param string $path The path to strip
9232 * @return string the path with double slashes removed
9234 function cleardoubleslashes ($path) {
9235 return preg_replace('/(\/|\\\){1,}/', '/', $path);
9239 * Is the current ip in a given list?
9241 * @param string $list
9242 * @return bool
9244 function remoteip_in_list($list) {
9245 $clientip = getremoteaddr(null);
9247 if (!$clientip) {
9248 // Ensure access on cli.
9249 return true;
9251 return \core\ip_utils::is_ip_in_subnet_list($clientip, $list);
9255 * Returns most reliable client address
9257 * @param string $default If an address can't be determined, then return this
9258 * @return string The remote IP address
9260 function getremoteaddr($default='0.0.0.0') {
9261 global $CFG;
9263 if (!isset($CFG->getremoteaddrconf)) {
9264 // This will happen, for example, before just after the upgrade, as the
9265 // user is redirected to the admin screen.
9266 $variablestoskip = GETREMOTEADDR_SKIP_DEFAULT;
9267 } else {
9268 $variablestoskip = $CFG->getremoteaddrconf;
9270 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
9271 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9272 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9273 return $address ? $address : $default;
9276 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
9277 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9278 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9280 $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
9281 global $CFG;
9282 return !\core\ip_utils::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore ?? '', ',');
9285 // Multiple proxies can append values to this header including an
9286 // untrusted original request header so we must only trust the last ip.
9287 $address = end($forwardedaddresses);
9289 if (substr_count($address, ":") > 1) {
9290 // Remove port and brackets from IPv6.
9291 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9292 $address = $matches[1];
9294 } else {
9295 // Remove port from IPv4.
9296 if (substr_count($address, ":") == 1) {
9297 $parts = explode(":", $address);
9298 $address = $parts[0];
9302 $address = cleanremoteaddr($address);
9303 return $address ? $address : $default;
9306 if (!empty($_SERVER['REMOTE_ADDR'])) {
9307 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9308 return $address ? $address : $default;
9309 } else {
9310 return $default;
9315 * Cleans an ip address. Internal addresses are now allowed.
9316 * (Originally local addresses were not allowed.)
9318 * @param string $addr IPv4 or IPv6 address
9319 * @param bool $compress use IPv6 address compression
9320 * @return string normalised ip address string, null if error
9322 function cleanremoteaddr($addr, $compress=false) {
9323 $addr = trim($addr);
9325 if (strpos($addr, ':') !== false) {
9326 // Can be only IPv6.
9327 $parts = explode(':', $addr);
9328 $count = count($parts);
9330 if (strpos($parts[$count-1], '.') !== false) {
9331 // Legacy ipv4 notation.
9332 $last = array_pop($parts);
9333 $ipv4 = cleanremoteaddr($last, true);
9334 if ($ipv4 === null) {
9335 return null;
9337 $bits = explode('.', $ipv4);
9338 $parts[] = dechex($bits[0]).dechex($bits[1]);
9339 $parts[] = dechex($bits[2]).dechex($bits[3]);
9340 $count = count($parts);
9341 $addr = implode(':', $parts);
9344 if ($count < 3 or $count > 8) {
9345 return null; // Severly malformed.
9348 if ($count != 8) {
9349 if (strpos($addr, '::') === false) {
9350 return null; // Malformed.
9352 // Uncompress.
9353 $insertat = array_search('', $parts, true);
9354 $missing = array_fill(0, 1 + 8 - $count, '0');
9355 array_splice($parts, $insertat, 1, $missing);
9356 foreach ($parts as $key => $part) {
9357 if ($part === '') {
9358 $parts[$key] = '0';
9363 $adr = implode(':', $parts);
9364 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9365 return null; // Incorrect format - sorry.
9368 // Normalise 0s and case.
9369 $parts = array_map('hexdec', $parts);
9370 $parts = array_map('dechex', $parts);
9372 $result = implode(':', $parts);
9374 if (!$compress) {
9375 return $result;
9378 if ($result === '0:0:0:0:0:0:0:0') {
9379 return '::'; // All addresses.
9382 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9383 if ($compressed !== $result) {
9384 return $compressed;
9387 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9388 if ($compressed !== $result) {
9389 return $compressed;
9392 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9393 if ($compressed !== $result) {
9394 return $compressed;
9397 return $result;
9400 // First get all things that look like IPv4 addresses.
9401 $parts = array();
9402 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9403 return null;
9405 unset($parts[0]);
9407 foreach ($parts as $key => $match) {
9408 if ($match > 255) {
9409 return null;
9411 $parts[$key] = (int)$match; // Normalise 0s.
9414 return implode('.', $parts);
9419 * Is IP address a public address?
9421 * @param string $ip The ip to check
9422 * @return bool true if the ip is public
9424 function ip_is_public($ip) {
9425 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9429 * This function will make a complete copy of anything it's given,
9430 * regardless of whether it's an object or not.
9432 * @param mixed $thing Something you want cloned
9433 * @return mixed What ever it is you passed it
9435 function fullclone($thing) {
9436 return unserialize(serialize($thing));
9440 * Used to make sure that $min <= $value <= $max
9442 * Make sure that value is between min, and max
9444 * @param int $min The minimum value
9445 * @param int $value The value to check
9446 * @param int $max The maximum value
9447 * @return int
9449 function bounded_number($min, $value, $max) {
9450 if ($value < $min) {
9451 return $min;
9453 if ($value > $max) {
9454 return $max;
9456 return $value;
9460 * Check if there is a nested array within the passed array
9462 * @param array $array
9463 * @return bool true if there is a nested array false otherwise
9465 function array_is_nested($array) {
9466 foreach ($array as $value) {
9467 if (is_array($value)) {
9468 return true;
9471 return false;
9475 * get_performance_info() pairs up with init_performance_info()
9476 * loaded in setup.php. Returns an array with 'html' and 'txt'
9477 * values ready for use, and each of the individual stats provided
9478 * separately as well.
9480 * @return array
9482 function get_performance_info() {
9483 global $CFG, $PERF, $DB, $PAGE;
9485 $info = array();
9486 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9488 $info['html'] = '';
9489 if (!empty($CFG->themedesignermode)) {
9490 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9491 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9493 $info['html'] .= '<ul class="list-unstyled row mx-md-0">'; // Holds userfriendly HTML representation.
9495 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9497 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9498 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9500 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9501 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9503 if (function_exists('memory_get_usage')) {
9504 $info['memory_total'] = memory_get_usage();
9505 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9506 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9507 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9508 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9511 if (function_exists('memory_get_peak_usage')) {
9512 $info['memory_peak'] = memory_get_peak_usage();
9513 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9514 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9517 $info['html'] .= '</ul><ul class="list-unstyled row mx-md-0">';
9518 $inc = get_included_files();
9519 $info['includecount'] = count($inc);
9520 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9521 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9523 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9524 // We can not track more performance before installation or before PAGE init, sorry.
9525 return $info;
9528 $filtermanager = filter_manager::instance();
9529 if (method_exists($filtermanager, 'get_performance_summary')) {
9530 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9531 $info = array_merge($filterinfo, $info);
9532 foreach ($filterinfo as $key => $value) {
9533 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9534 $info['txt'] .= "$key: $value ";
9538 $stringmanager = get_string_manager();
9539 if (method_exists($stringmanager, 'get_performance_summary')) {
9540 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9541 $info = array_merge($filterinfo, $info);
9542 foreach ($filterinfo as $key => $value) {
9543 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9544 $info['txt'] .= "$key: $value ";
9548 if (!empty($PERF->logwrites)) {
9549 $info['logwrites'] = $PERF->logwrites;
9550 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9551 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9554 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9555 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9556 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9558 if ($DB->want_read_slave()) {
9559 $info['dbreads_slave'] = $DB->perf_get_reads_slave();
9560 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads from slave: '.$info['dbreads_slave'].'</li> ';
9561 $info['txt'] .= 'db reads from slave: '.$info['dbreads_slave'].' ';
9564 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9565 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9566 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9568 if (function_exists('posix_times')) {
9569 $ptimes = posix_times();
9570 if (is_array($ptimes)) {
9571 foreach ($ptimes as $key => $val) {
9572 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9574 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9575 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9576 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9580 // Grab the load average for the last minute.
9581 // /proc will only work under some linux configurations
9582 // while uptime is there under MacOSX/Darwin and other unices.
9583 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9584 list($serverload) = explode(' ', $loadavg[0]);
9585 unset($loadavg);
9586 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9587 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9588 $serverload = $matches[1];
9589 } else {
9590 trigger_error('Could not parse uptime output!');
9593 if (!empty($serverload)) {
9594 $info['serverload'] = $serverload;
9595 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9596 $info['txt'] .= "serverload: {$info['serverload']} ";
9599 // Display size of session if session started.
9600 if ($si = \core\session\manager::get_performance_info()) {
9601 $info['sessionsize'] = $si['size'];
9602 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9603 $info['txt'] .= $si['txt'];
9606 $info['html'] .= '</ul>';
9607 $html = '';
9608 if ($stats = cache_helper::get_stats()) {
9610 $table = new html_table();
9611 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9612 $table->head = ['Mode', 'Cache item', 'Static', 'H', 'M', get_string('mappingprimary', 'cache'), 'H', 'M', 'S', 'I/O'];
9613 $table->data = [];
9614 $table->align = ['left', 'left', 'left', 'right', 'right', 'left', 'right', 'right', 'right', 'right'];
9616 $text = 'Caches used (hits/misses/sets): ';
9617 $hits = 0;
9618 $misses = 0;
9619 $sets = 0;
9620 $maxstores = 0;
9622 // We want to align static caches into their own column.
9623 $hasstatic = false;
9624 foreach ($stats as $definition => $details) {
9625 $numstores = count($details['stores']);
9626 $first = key($details['stores']);
9627 if ($first !== cache_store::STATIC_ACCEL) {
9628 $numstores++; // Add a blank space for the missing static store.
9630 $maxstores = max($maxstores, $numstores);
9633 $storec = 0;
9635 while ($storec++ < ($maxstores - 2)) {
9636 if ($storec == ($maxstores - 2)) {
9637 $table->head[] = get_string('mappingfinal', 'cache');
9638 } else {
9639 $table->head[] = "Store $storec";
9641 $table->align[] = 'left';
9642 $table->align[] = 'right';
9643 $table->align[] = 'right';
9644 $table->align[] = 'right';
9645 $table->align[] = 'right';
9646 $table->head[] = 'H';
9647 $table->head[] = 'M';
9648 $table->head[] = 'S';
9649 $table->head[] = 'I/O';
9652 ksort($stats);
9654 foreach ($stats as $definition => $details) {
9655 switch ($details['mode']) {
9656 case cache_store::MODE_APPLICATION:
9657 $modeclass = 'application';
9658 $mode = ' <span title="application cache">App</span>';
9659 break;
9660 case cache_store::MODE_SESSION:
9661 $modeclass = 'session';
9662 $mode = ' <span title="session cache">Ses</span>';
9663 break;
9664 case cache_store::MODE_REQUEST:
9665 $modeclass = 'request';
9666 $mode = ' <span title="request cache">Req</span>';
9667 break;
9669 $row = [$mode, $definition];
9671 $text .= "$definition {";
9673 $storec = 0;
9674 foreach ($details['stores'] as $store => $data) {
9676 if ($storec == 0 && $store !== cache_store::STATIC_ACCEL) {
9677 $row[] = '';
9678 $row[] = '';
9679 $row[] = '';
9680 $storec++;
9683 $hits += $data['hits'];
9684 $misses += $data['misses'];
9685 $sets += $data['sets'];
9686 if ($data['hits'] == 0 and $data['misses'] > 0) {
9687 $cachestoreclass = 'nohits bg-danger';
9688 } else if ($data['hits'] < $data['misses']) {
9689 $cachestoreclass = 'lowhits bg-warning text-dark';
9690 } else {
9691 $cachestoreclass = 'hihits';
9693 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9694 $cell = new html_table_cell($store);
9695 $cell->attributes = ['class' => $cachestoreclass];
9696 $row[] = $cell;
9697 $cell = new html_table_cell($data['hits']);
9698 $cell->attributes = ['class' => $cachestoreclass];
9699 $row[] = $cell;
9700 $cell = new html_table_cell($data['misses']);
9701 $cell->attributes = ['class' => $cachestoreclass];
9702 $row[] = $cell;
9704 if ($store !== cache_store::STATIC_ACCEL) {
9705 // The static cache is never set.
9706 $cell = new html_table_cell($data['sets']);
9707 $cell->attributes = ['class' => $cachestoreclass];
9708 $row[] = $cell;
9710 if ($data['hits'] || $data['sets']) {
9711 if ($data['iobytes'] === cache_store::IO_BYTES_NOT_SUPPORTED) {
9712 $size = '-';
9713 } else {
9714 $size = display_size($data['iobytes'], 1, 'KB');
9715 if ($data['iobytes'] >= 10 * 1024) {
9716 $cachestoreclass = ' bg-warning text-dark';
9719 } else {
9720 $size = '';
9722 $cell = new html_table_cell($size);
9723 $cell->attributes = ['class' => $cachestoreclass];
9724 $row[] = $cell;
9726 $storec++;
9728 while ($storec++ < $maxstores) {
9729 $row[] = '';
9730 $row[] = '';
9731 $row[] = '';
9732 $row[] = '';
9733 $row[] = '';
9735 $text .= '} ';
9737 $table->data[] = $row;
9740 $html .= html_writer::table($table);
9742 // Now lets also show sub totals for each cache store.
9743 $storetotals = [];
9744 $storetotal = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9745 foreach ($stats as $definition => $details) {
9746 foreach ($details['stores'] as $store => $data) {
9747 if (!array_key_exists($store, $storetotals)) {
9748 $storetotals[$store] = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9750 $storetotals[$store]['class'] = $data['class'];
9751 $storetotals[$store]['hits'] += $data['hits'];
9752 $storetotals[$store]['misses'] += $data['misses'];
9753 $storetotals[$store]['sets'] += $data['sets'];
9754 $storetotal['hits'] += $data['hits'];
9755 $storetotal['misses'] += $data['misses'];
9756 $storetotal['sets'] += $data['sets'];
9757 if ($data['iobytes'] !== cache_store::IO_BYTES_NOT_SUPPORTED) {
9758 $storetotals[$store]['iobytes'] += $data['iobytes'];
9759 $storetotal['iobytes'] += $data['iobytes'];
9764 $table = new html_table();
9765 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9766 $table->head = [get_string('storename', 'cache'), get_string('type_cachestore', 'plugin'), 'H', 'M', 'S', 'I/O'];
9767 $table->data = [];
9768 $table->align = ['left', 'left', 'right', 'right', 'right', 'right'];
9770 ksort($storetotals);
9772 foreach ($storetotals as $store => $data) {
9773 $row = [];
9774 if ($data['hits'] == 0 and $data['misses'] > 0) {
9775 $cachestoreclass = 'nohits bg-danger';
9776 } else if ($data['hits'] < $data['misses']) {
9777 $cachestoreclass = 'lowhits bg-warning text-dark';
9778 } else {
9779 $cachestoreclass = 'hihits';
9781 $cell = new html_table_cell($store);
9782 $cell->attributes = ['class' => $cachestoreclass];
9783 $row[] = $cell;
9784 $cell = new html_table_cell($data['class']);
9785 $cell->attributes = ['class' => $cachestoreclass];
9786 $row[] = $cell;
9787 $cell = new html_table_cell($data['hits']);
9788 $cell->attributes = ['class' => $cachestoreclass];
9789 $row[] = $cell;
9790 $cell = new html_table_cell($data['misses']);
9791 $cell->attributes = ['class' => $cachestoreclass];
9792 $row[] = $cell;
9793 $cell = new html_table_cell($data['sets']);
9794 $cell->attributes = ['class' => $cachestoreclass];
9795 $row[] = $cell;
9796 if ($data['hits'] || $data['sets']) {
9797 if ($data['iobytes']) {
9798 $size = display_size($data['iobytes'], 1, 'KB');
9799 } else {
9800 $size = '-';
9802 } else {
9803 $size = '';
9805 $cell = new html_table_cell($size);
9806 $cell->attributes = ['class' => $cachestoreclass];
9807 $row[] = $cell;
9808 $table->data[] = $row;
9810 if (!empty($storetotal['iobytes'])) {
9811 $size = display_size($storetotal['iobytes'], 1, 'KB');
9812 } else if (!empty($storetotal['hits']) || !empty($storetotal['sets'])) {
9813 $size = '-';
9814 } else {
9815 $size = '';
9817 $row = [
9818 get_string('total'),
9820 $storetotal['hits'],
9821 $storetotal['misses'],
9822 $storetotal['sets'],
9823 $size,
9825 $table->data[] = $row;
9827 $html .= html_writer::table($table);
9829 $info['cachesused'] = "$hits / $misses / $sets";
9830 $info['html'] .= $html;
9831 $info['txt'] .= $text.'. ';
9832 } else {
9833 $info['cachesused'] = '0 / 0 / 0';
9834 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9835 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9838 $info['html'] = '<div class="performanceinfo siteinfo container-fluid px-md-0 overflow-auto pt-3">'.$info['html'].'</div>';
9839 return $info;
9843 * Renames a file or directory to a unique name within the same directory.
9845 * This function is designed to avoid any potential race conditions, and select an unused name.
9847 * @param string $filepath Original filepath
9848 * @param string $prefix Prefix to use for the temporary name
9849 * @return string|bool New file path or false if failed
9850 * @since Moodle 3.10
9852 function rename_to_unused_name(string $filepath, string $prefix = '_temp_') {
9853 $dir = dirname($filepath);
9854 $basename = $dir . '/' . $prefix;
9855 $limit = 0;
9856 while ($limit < 100) {
9857 // Select a new name based on a random number.
9858 $newfilepath = $basename . md5(mt_rand());
9860 // Attempt a rename to that new name.
9861 if (@rename($filepath, $newfilepath)) {
9862 return $newfilepath;
9865 // The first time, do some sanity checks, maybe it is failing for a good reason and there
9866 // is no point trying 100 times if so.
9867 if ($limit === 0 && (!file_exists($filepath) || !is_writable($dir))) {
9868 return false;
9870 $limit++;
9872 return false;
9876 * Delete directory or only its content
9878 * @param string $dir directory path
9879 * @param bool $contentonly
9880 * @return bool success, true also if dir does not exist
9882 function remove_dir($dir, $contentonly=false) {
9883 if (!is_dir($dir)) {
9884 // Nothing to do.
9885 return true;
9888 if (!$contentonly) {
9889 // Start by renaming the directory; this will guarantee that other processes don't write to it
9890 // while it is in the process of being deleted.
9891 $tempdir = rename_to_unused_name($dir);
9892 if ($tempdir) {
9893 // If the rename was successful then delete the $tempdir instead.
9894 $dir = $tempdir;
9896 // If the rename fails, we will continue through and attempt to delete the directory
9897 // without renaming it since that is likely to at least delete most of the files.
9900 if (!$handle = opendir($dir)) {
9901 return false;
9903 $result = true;
9904 while (false!==($item = readdir($handle))) {
9905 if ($item != '.' && $item != '..') {
9906 if (is_dir($dir.'/'.$item)) {
9907 $result = remove_dir($dir.'/'.$item) && $result;
9908 } else {
9909 $result = unlink($dir.'/'.$item) && $result;
9913 closedir($handle);
9914 if ($contentonly) {
9915 clearstatcache(); // Make sure file stat cache is properly invalidated.
9916 return $result;
9918 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9919 clearstatcache(); // Make sure file stat cache is properly invalidated.
9920 return $result;
9924 * Detect if an object or a class contains a given property
9925 * will take an actual object or the name of a class
9927 * @param mix $obj Name of class or real object to test
9928 * @param string $property name of property to find
9929 * @return bool true if property exists
9931 function object_property_exists( $obj, $property ) {
9932 if (is_string( $obj )) {
9933 $properties = get_class_vars( $obj );
9934 } else {
9935 $properties = get_object_vars( $obj );
9937 return array_key_exists( $property, $properties );
9941 * Converts an object into an associative array
9943 * This function converts an object into an associative array by iterating
9944 * over its public properties. Because this function uses the foreach
9945 * construct, Iterators are respected. It works recursively on arrays of objects.
9946 * Arrays and simple values are returned as is.
9948 * If class has magic properties, it can implement IteratorAggregate
9949 * and return all available properties in getIterator()
9951 * @param mixed $var
9952 * @return array
9954 function convert_to_array($var) {
9955 $result = array();
9957 // Loop over elements/properties.
9958 foreach ($var as $key => $value) {
9959 // Recursively convert objects.
9960 if (is_object($value) || is_array($value)) {
9961 $result[$key] = convert_to_array($value);
9962 } else {
9963 // Simple values are untouched.
9964 $result[$key] = $value;
9967 return $result;
9971 * Detect a custom script replacement in the data directory that will
9972 * replace an existing moodle script
9974 * @return string|bool full path name if a custom script exists, false if no custom script exists
9976 function custom_script_path() {
9977 global $CFG, $SCRIPT;
9979 if ($SCRIPT === null) {
9980 // Probably some weird external script.
9981 return false;
9984 $scriptpath = $CFG->customscripts . $SCRIPT;
9986 // Check the custom script exists.
9987 if (file_exists($scriptpath) and is_file($scriptpath)) {
9988 return $scriptpath;
9989 } else {
9990 return false;
9995 * Returns whether or not the user object is a remote MNET user. This function
9996 * is in moodlelib because it does not rely on loading any of the MNET code.
9998 * @param object $user A valid user object
9999 * @return bool True if the user is from a remote Moodle.
10001 function is_mnet_remote_user($user) {
10002 global $CFG;
10004 if (!isset($CFG->mnet_localhost_id)) {
10005 include_once($CFG->dirroot . '/mnet/lib.php');
10006 $env = new mnet_environment();
10007 $env->init();
10008 unset($env);
10011 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
10015 * This function will search for browser prefereed languages, setting Moodle
10016 * to use the best one available if $SESSION->lang is undefined
10018 function setup_lang_from_browser() {
10019 global $CFG, $SESSION, $USER;
10021 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
10022 // Lang is defined in session or user profile, nothing to do.
10023 return;
10026 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
10027 return;
10030 // Extract and clean langs from headers.
10031 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
10032 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
10033 $rawlangs = explode(',', $rawlangs); // Convert to array.
10034 $langs = array();
10036 $order = 1.0;
10037 foreach ($rawlangs as $lang) {
10038 if (strpos($lang, ';') === false) {
10039 $langs[(string)$order] = $lang;
10040 $order = $order-0.01;
10041 } else {
10042 $parts = explode(';', $lang);
10043 $pos = strpos($parts[1], '=');
10044 $langs[substr($parts[1], $pos+1)] = $parts[0];
10047 krsort($langs, SORT_NUMERIC);
10049 // Look for such langs under standard locations.
10050 foreach ($langs as $lang) {
10051 // Clean it properly for include.
10052 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
10053 if (get_string_manager()->translation_exists($lang, false)) {
10054 // Lang exists, set it in session.
10055 $SESSION->lang = $lang;
10056 // We have finished. Go out.
10057 break;
10060 return;
10064 * Check if $url matches anything in proxybypass list
10066 * Any errors just result in the proxy being used (least bad)
10068 * @param string $url url to check
10069 * @return boolean true if we should bypass the proxy
10071 function is_proxybypass( $url ) {
10072 global $CFG;
10074 // Sanity check.
10075 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
10076 return false;
10079 // Get the host part out of the url.
10080 if (!$host = parse_url( $url, PHP_URL_HOST )) {
10081 return false;
10084 // Get the possible bypass hosts into an array.
10085 $matches = explode( ',', $CFG->proxybypass );
10087 // Check for a match.
10088 // (IPs need to match the left hand side and hosts the right of the url,
10089 // but we can recklessly check both as there can't be a false +ve).
10090 foreach ($matches as $match) {
10091 $match = trim($match);
10093 // Try for IP match (Left side).
10094 $lhs = substr($host, 0, strlen($match));
10095 if (strcasecmp($match, $lhs)==0) {
10096 return true;
10099 // Try for host match (Right side).
10100 $rhs = substr($host, -strlen($match));
10101 if (strcasecmp($match, $rhs)==0) {
10102 return true;
10106 // Nothing matched.
10107 return false;
10111 * Check if the passed navigation is of the new style
10113 * @param mixed $navigation
10114 * @return bool true for yes false for no
10116 function is_newnav($navigation) {
10117 if (is_array($navigation) && !empty($navigation['newnav'])) {
10118 return true;
10119 } else {
10120 return false;
10125 * Checks whether the given variable name is defined as a variable within the given object.
10127 * This will NOT work with stdClass objects, which have no class variables.
10129 * @param string $var The variable name
10130 * @param object $object The object to check
10131 * @return boolean
10133 function in_object_vars($var, $object) {
10134 $classvars = get_class_vars(get_class($object));
10135 $classvars = array_keys($classvars);
10136 return in_array($var, $classvars);
10140 * Returns an array without repeated objects.
10141 * This function is similar to array_unique, but for arrays that have objects as values
10143 * @param array $array
10144 * @param bool $keepkeyassoc
10145 * @return array
10147 function object_array_unique($array, $keepkeyassoc = true) {
10148 $duplicatekeys = array();
10149 $tmp = array();
10151 foreach ($array as $key => $val) {
10152 // Convert objects to arrays, in_array() does not support objects.
10153 if (is_object($val)) {
10154 $val = (array)$val;
10157 if (!in_array($val, $tmp)) {
10158 $tmp[] = $val;
10159 } else {
10160 $duplicatekeys[] = $key;
10164 foreach ($duplicatekeys as $key) {
10165 unset($array[$key]);
10168 return $keepkeyassoc ? $array : array_values($array);
10172 * Is a userid the primary administrator?
10174 * @param int $userid int id of user to check
10175 * @return boolean
10177 function is_primary_admin($userid) {
10178 $primaryadmin = get_admin();
10180 if ($userid == $primaryadmin->id) {
10181 return true;
10182 } else {
10183 return false;
10188 * Returns the site identifier
10190 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
10192 function get_site_identifier() {
10193 global $CFG;
10194 // Check to see if it is missing. If so, initialise it.
10195 if (empty($CFG->siteidentifier)) {
10196 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
10198 // Return it.
10199 return $CFG->siteidentifier;
10203 * Check whether the given password has no more than the specified
10204 * number of consecutive identical characters.
10206 * @param string $password password to be checked against the password policy
10207 * @param integer $maxchars maximum number of consecutive identical characters
10208 * @return bool
10210 function check_consecutive_identical_characters($password, $maxchars) {
10212 if ($maxchars < 1) {
10213 return true; // Zero 0 is to disable this check.
10215 if (strlen($password) <= $maxchars) {
10216 return true; // Too short to fail this test.
10219 $previouschar = '';
10220 $consecutivecount = 1;
10221 foreach (str_split($password) as $char) {
10222 if ($char != $previouschar) {
10223 $consecutivecount = 1;
10224 } else {
10225 $consecutivecount++;
10226 if ($consecutivecount > $maxchars) {
10227 return false; // Check failed already.
10231 $previouschar = $char;
10234 return true;
10238 * Helper function to do partial function binding.
10239 * so we can use it for preg_replace_callback, for example
10240 * this works with php functions, user functions, static methods and class methods
10241 * it returns you a callback that you can pass on like so:
10243 * $callback = partial('somefunction', $arg1, $arg2);
10244 * or
10245 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
10246 * or even
10247 * $obj = new someclass();
10248 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
10250 * and then the arguments that are passed through at calltime are appended to the argument list.
10252 * @param mixed $function a php callback
10253 * @param mixed $arg1,... $argv arguments to partially bind with
10254 * @return array Array callback
10256 function partial() {
10257 if (!class_exists('partial')) {
10259 * Used to manage function binding.
10260 * @copyright 2009 Penny Leach
10261 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10263 class partial{
10264 /** @var array */
10265 public $values = array();
10266 /** @var string The function to call as a callback. */
10267 public $func;
10269 * Constructor
10270 * @param string $func
10271 * @param array $args
10273 public function __construct($func, $args) {
10274 $this->values = $args;
10275 $this->func = $func;
10278 * Calls the callback function.
10279 * @return mixed
10281 public function method() {
10282 $args = func_get_args();
10283 return call_user_func_array($this->func, array_merge($this->values, $args));
10287 $args = func_get_args();
10288 $func = array_shift($args);
10289 $p = new partial($func, $args);
10290 return array($p, 'method');
10294 * helper function to load up and initialise the mnet environment
10295 * this must be called before you use mnet functions.
10297 * @return mnet_environment the equivalent of old $MNET global
10299 function get_mnet_environment() {
10300 global $CFG;
10301 require_once($CFG->dirroot . '/mnet/lib.php');
10302 static $instance = null;
10303 if (empty($instance)) {
10304 $instance = new mnet_environment();
10305 $instance->init();
10307 return $instance;
10311 * during xmlrpc server code execution, any code wishing to access
10312 * information about the remote peer must use this to get it.
10314 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
10316 function get_mnet_remote_client() {
10317 if (!defined('MNET_SERVER')) {
10318 debugging(get_string('notinxmlrpcserver', 'mnet'));
10319 return false;
10321 global $MNET_REMOTE_CLIENT;
10322 if (isset($MNET_REMOTE_CLIENT)) {
10323 return $MNET_REMOTE_CLIENT;
10325 return false;
10329 * during the xmlrpc server code execution, this will be called
10330 * to setup the object returned by {@link get_mnet_remote_client}
10332 * @param mnet_remote_client $client the client to set up
10333 * @throws moodle_exception
10335 function set_mnet_remote_client($client) {
10336 if (!defined('MNET_SERVER')) {
10337 throw new moodle_exception('notinxmlrpcserver', 'mnet');
10339 global $MNET_REMOTE_CLIENT;
10340 $MNET_REMOTE_CLIENT = $client;
10344 * return the jump url for a given remote user
10345 * this is used for rewriting forum post links in emails, etc
10347 * @param stdclass $user the user to get the idp url for
10349 function mnet_get_idp_jump_url($user) {
10350 global $CFG;
10352 static $mnetjumps = array();
10353 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
10354 $idp = mnet_get_peer_host($user->mnethostid);
10355 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
10356 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
10358 return $mnetjumps[$user->mnethostid];
10362 * Gets the homepage to use for the current user
10364 * @return int One of HOMEPAGE_*
10366 function get_home_page() {
10367 global $CFG;
10369 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
10370 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
10371 return HOMEPAGE_MY;
10372 } else if ($CFG->defaulthomepage == HOMEPAGE_MYCOURSES) {
10373 return HOMEPAGE_MYCOURSES;
10374 } else {
10375 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
10378 return HOMEPAGE_SITE;
10382 * Gets the name of a course to be displayed when showing a list of courses.
10383 * By default this is just $course->fullname but user can configure it. The
10384 * result of this function should be passed through print_string.
10385 * @param stdClass|core_course_list_element $course Moodle course object
10386 * @return string Display name of course (either fullname or short + fullname)
10388 function get_course_display_name_for_list($course) {
10389 global $CFG;
10390 if (!empty($CFG->courselistshortnames)) {
10391 if (!($course instanceof stdClass)) {
10392 $course = (object)convert_to_array($course);
10394 return get_string('courseextendednamedisplay', '', $course);
10395 } else {
10396 return $course->fullname;
10401 * Safe analogue of unserialize() that can only parse arrays
10403 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
10404 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
10405 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
10407 * @param string $expression
10408 * @return array|bool either parsed array or false if parsing was impossible.
10410 function unserialize_array($expression) {
10411 $subs = [];
10412 // Find nested arrays, parse them and store in $subs , substitute with special string.
10413 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
10414 $key = '--SUB' . count($subs) . '--';
10415 $subs[$key] = unserialize_array($matches[2]);
10416 if ($subs[$key] === false) {
10417 return false;
10419 $expression = str_replace($matches[2], $key . ';', $expression);
10422 // Check the expression is an array.
10423 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
10424 return false;
10426 // Get the size and elements of an array (key;value;key;value;....).
10427 $parts = explode(';', $matches1[2]);
10428 $size = intval($matches1[1]);
10429 if (count($parts) < $size * 2 + 1) {
10430 return false;
10432 // Analyze each part and make sure it is an integer or string or a substitute.
10433 $value = [];
10434 for ($i = 0; $i < $size * 2; $i++) {
10435 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
10436 $parts[$i] = (int)$matches2[1];
10437 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
10438 $parts[$i] = $matches3[2];
10439 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
10440 $parts[$i] = $subs[$parts[$i]];
10441 } else {
10442 return false;
10445 // Combine keys and values.
10446 for ($i = 0; $i < $size * 2; $i += 2) {
10447 $value[$parts[$i]] = $parts[$i+1];
10449 return $value;
10453 * Safe method for unserializing given input that is expected to contain only a serialized instance of an stdClass object
10455 * If any class type other than stdClass is included in the input string, it will not be instantiated and will be cast to an
10456 * stdClass object. The initial cast to array, then back to object is to ensure we are always returning the correct type,
10457 * otherwise we would return an instances of {@see __PHP_Incomplete_class} for malformed strings
10459 * @param string $input
10460 * @return stdClass
10462 function unserialize_object(string $input): stdClass {
10463 $instance = (array) unserialize($input, ['allowed_classes' => [stdClass::class]]);
10464 return (object) $instance;
10468 * The lang_string class
10470 * This special class is used to create an object representation of a string request.
10471 * It is special because processing doesn't occur until the object is first used.
10472 * The class was created especially to aid performance in areas where strings were
10473 * required to be generated but were not necessarily used.
10474 * As an example the admin tree when generated uses over 1500 strings, of which
10475 * normally only 1/3 are ever actually printed at any time.
10476 * The performance advantage is achieved by not actually processing strings that
10477 * arn't being used, as such reducing the processing required for the page.
10479 * How to use the lang_string class?
10480 * There are two methods of using the lang_string class, first through the
10481 * forth argument of the get_string function, and secondly directly.
10482 * The following are examples of both.
10483 * 1. Through get_string calls e.g.
10484 * $string = get_string($identifier, $component, $a, true);
10485 * $string = get_string('yes', 'moodle', null, true);
10486 * 2. Direct instantiation
10487 * $string = new lang_string($identifier, $component, $a, $lang);
10488 * $string = new lang_string('yes');
10490 * How do I use a lang_string object?
10491 * The lang_string object makes use of a magic __toString method so that you
10492 * are able to use the object exactly as you would use a string in most cases.
10493 * This means you are able to collect it into a variable and then directly
10494 * echo it, or concatenate it into another string, or similar.
10495 * The other thing you can do is manually get the string by calling the
10496 * lang_strings out method e.g.
10497 * $string = new lang_string('yes');
10498 * $string->out();
10499 * Also worth noting is that the out method can take one argument, $lang which
10500 * allows the developer to change the language on the fly.
10502 * When should I use a lang_string object?
10503 * The lang_string object is designed to be used in any situation where a
10504 * string may not be needed, but needs to be generated.
10505 * The admin tree is a good example of where lang_string objects should be
10506 * used.
10507 * A more practical example would be any class that requries strings that may
10508 * not be printed (after all classes get renderer by renderers and who knows
10509 * what they will do ;))
10511 * When should I not use a lang_string object?
10512 * Don't use lang_strings when you are going to use a string immediately.
10513 * There is no need as it will be processed immediately and there will be no
10514 * advantage, and in fact perhaps a negative hit as a class has to be
10515 * instantiated for a lang_string object, however get_string won't require
10516 * that.
10518 * Limitations:
10519 * 1. You cannot use a lang_string object as an array offset. Doing so will
10520 * result in PHP throwing an error. (You can use it as an object property!)
10522 * @package core
10523 * @category string
10524 * @copyright 2011 Sam Hemelryk
10525 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10527 class lang_string {
10529 /** @var string The strings identifier */
10530 protected $identifier;
10531 /** @var string The strings component. Default '' */
10532 protected $component = '';
10533 /** @var array|stdClass Any arguments required for the string. Default null */
10534 protected $a = null;
10535 /** @var string The language to use when processing the string. Default null */
10536 protected $lang = null;
10538 /** @var string The processed string (once processed) */
10539 protected $string = null;
10542 * A special boolean. If set to true then the object has been woken up and
10543 * cannot be regenerated. If this is set then $this->string MUST be used.
10544 * @var bool
10546 protected $forcedstring = false;
10549 * Constructs a lang_string object
10551 * This function should do as little processing as possible to ensure the best
10552 * performance for strings that won't be used.
10554 * @param string $identifier The strings identifier
10555 * @param string $component The strings component
10556 * @param stdClass|array $a Any arguments the string requires
10557 * @param string $lang The language to use when processing the string.
10558 * @throws coding_exception
10560 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10561 if (empty($component)) {
10562 $component = 'moodle';
10565 $this->identifier = $identifier;
10566 $this->component = $component;
10567 $this->lang = $lang;
10569 // We MUST duplicate $a to ensure that it if it changes by reference those
10570 // changes are not carried across.
10571 // To do this we always ensure $a or its properties/values are strings
10572 // and that any properties/values that arn't convertable are forgotten.
10573 if ($a !== null) {
10574 if (is_scalar($a)) {
10575 $this->a = $a;
10576 } else if ($a instanceof lang_string) {
10577 $this->a = $a->out();
10578 } else if (is_object($a) or is_array($a)) {
10579 $a = (array)$a;
10580 $this->a = array();
10581 foreach ($a as $key => $value) {
10582 // Make sure conversion errors don't get displayed (results in '').
10583 if (is_array($value)) {
10584 $this->a[$key] = '';
10585 } else if (is_object($value)) {
10586 if (method_exists($value, '__toString')) {
10587 $this->a[$key] = $value->__toString();
10588 } else {
10589 $this->a[$key] = '';
10591 } else {
10592 $this->a[$key] = (string)$value;
10598 if (debugging(false, DEBUG_DEVELOPER)) {
10599 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10600 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10602 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10603 throw new coding_exception('Invalid string compontent. Please check your string definition');
10605 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10606 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10612 * Processes the string.
10614 * This function actually processes the string, stores it in the string property
10615 * and then returns it.
10616 * You will notice that this function is VERY similar to the get_string method.
10617 * That is because it is pretty much doing the same thing.
10618 * However as this function is an upgrade it isn't as tolerant to backwards
10619 * compatibility.
10621 * @return string
10622 * @throws coding_exception
10624 protected function get_string() {
10625 global $CFG;
10627 // Check if we need to process the string.
10628 if ($this->string === null) {
10629 // Check the quality of the identifier.
10630 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10631 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);
10634 // Process the string.
10635 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10636 // Debugging feature lets you display string identifier and component.
10637 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10638 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10641 // Return the string.
10642 return $this->string;
10646 * Returns the string
10648 * @param string $lang The langauge to use when processing the string
10649 * @return string
10651 public function out($lang = null) {
10652 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10653 if ($this->forcedstring) {
10654 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10655 return $this->get_string();
10657 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10658 return $translatedstring->out();
10660 return $this->get_string();
10664 * Magic __toString method for printing a string
10666 * @return string
10668 public function __toString() {
10669 return $this->get_string();
10673 * Magic __set_state method used for var_export
10675 * @param array $array
10676 * @return self
10678 public static function __set_state(array $array): self {
10679 $tmp = new lang_string($array['identifier'], $array['component'], $array['a'], $array['lang']);
10680 $tmp->string = $array['string'];
10681 $tmp->forcedstring = $array['forcedstring'];
10682 return $tmp;
10686 * Prepares the lang_string for sleep and stores only the forcedstring and
10687 * string properties... the string cannot be regenerated so we need to ensure
10688 * it is generated for this.
10690 * @return string
10692 public function __sleep() {
10693 $this->get_string();
10694 $this->forcedstring = true;
10695 return array('forcedstring', 'string', 'lang');
10699 * Returns the identifier.
10701 * @return string
10703 public function get_identifier() {
10704 return $this->identifier;
10708 * Returns the component.
10710 * @return string
10712 public function get_component() {
10713 return $this->component;
10718 * Get human readable name describing the given callable.
10720 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10721 * It does not check if the callable actually exists.
10723 * @param callable|string|array $callable
10724 * @return string|bool Human readable name of callable, or false if not a valid callable.
10726 function get_callable_name($callable) {
10728 if (!is_callable($callable, true, $name)) {
10729 return false;
10731 } else {
10732 return $name;
10737 * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10738 * Never put your faith on this function and rely on its accuracy as there might be false positives.
10739 * It just performs some simple checks, and mainly is used for places where we want to hide some options
10740 * such as site registration when $CFG->wwwroot is not publicly accessible.
10741 * Good thing is there is no false negative.
10742 * Note that it's possible to force the result of this check by specifying $CFG->site_is_public in config.php
10744 * @return bool
10746 function site_is_public() {
10747 global $CFG;
10749 // Return early if site admin has forced this setting.
10750 if (isset($CFG->site_is_public)) {
10751 return (bool)$CFG->site_is_public;
10754 $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
10756 if ($host === 'localhost' || preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10757 $ispublic = false;
10758 } else if (\core\ip_utils::is_ip_address($host) && !ip_is_public($host)) {
10759 $ispublic = false;
10760 } else if (($address = \core\ip_utils::get_ip_address($host)) && !ip_is_public($address)) {
10761 $ispublic = false;
10762 } else {
10763 $ispublic = true;
10766 return $ispublic;