Automatically generated installer lang files
[moodle.git] / lib / moodlelib.php
blobecaff41a17f506bf0917e900f530170b7231c10e
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 $newuser->auth = $auth;
3906 $newuser->username = $username;
3908 // Fix for MDL-8480
3909 // user CFG lang for user if $newuser->lang is empty
3910 // or $user->lang is not an installed language.
3911 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3912 $newuser->lang = get_newuser_language();
3914 $newuser->confirmed = 1;
3915 $newuser->lastip = getremoteaddr();
3916 $newuser->timecreated = time();
3917 $newuser->timemodified = $newuser->timecreated;
3918 $newuser->mnethostid = $CFG->mnet_localhost_id;
3920 $newuser->id = user_create_user($newuser, false, false);
3922 // Save user profile data.
3923 profile_save_data($newuser);
3925 $user = get_complete_user_data('id', $newuser->id);
3926 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3927 set_user_preference('auth_forcepasswordchange', 1, $user);
3929 // Set the password.
3930 update_internal_user_password($user, $password);
3932 // Trigger event.
3933 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3935 return $user;
3939 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3941 * @param string $username user's username to update the record
3942 * @return stdClass A complete user object
3944 function update_user_record($username) {
3945 global $DB, $CFG;
3946 // Just in case check text case.
3947 $username = trim(core_text::strtolower($username));
3949 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3950 return update_user_record_by_id($oldinfo->id);
3954 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3956 * @param int $id user id
3957 * @return stdClass A complete user object
3959 function update_user_record_by_id($id) {
3960 global $DB, $CFG;
3961 require_once($CFG->dirroot."/user/profile/lib.php");
3962 require_once($CFG->dirroot.'/user/lib.php');
3964 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3965 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3967 $newuser = array();
3968 $userauth = get_auth_plugin($oldinfo->auth);
3970 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3971 $newinfo = truncate_userinfo($newinfo);
3972 $customfields = $userauth->get_custom_user_profile_fields();
3974 foreach ($newinfo as $key => $value) {
3975 $iscustom = in_array($key, $customfields);
3976 if (!$iscustom) {
3977 $key = strtolower($key);
3979 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3980 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3981 // Unknown or must not be changed.
3982 continue;
3984 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
3985 continue;
3987 $confval = $userauth->config->{'field_updatelocal_' . $key};
3988 $lockval = $userauth->config->{'field_lock_' . $key};
3989 if ($confval === 'onlogin') {
3990 // MDL-4207 Don't overwrite modified user profile values with
3991 // empty LDAP values when 'unlocked if empty' is set. The purpose
3992 // of the setting 'unlocked if empty' is to allow the user to fill
3993 // in a value for the selected field _if LDAP is giving
3994 // nothing_ for this field. Thus it makes sense to let this value
3995 // stand in until LDAP is giving a value for this field.
3996 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3997 if ($iscustom || (in_array($key, $userauth->userfields) &&
3998 ((string)$oldinfo->$key !== (string)$value))) {
3999 $newuser[$key] = (string)$value;
4004 if ($newuser) {
4005 $newuser['id'] = $oldinfo->id;
4006 $newuser['timemodified'] = time();
4007 user_update_user((object) $newuser, false, false);
4009 // Save user profile data.
4010 profile_save_data((object) $newuser);
4012 // Trigger event.
4013 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4017 return get_complete_user_data('id', $oldinfo->id);
4021 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4023 * @param array $info Array of user properties to truncate if needed
4024 * @return array The now truncated information that was passed in
4026 function truncate_userinfo(array $info) {
4027 // Define the limits.
4028 $limit = array(
4029 'username' => 100,
4030 'idnumber' => 255,
4031 'firstname' => 100,
4032 'lastname' => 100,
4033 'email' => 100,
4034 'phone1' => 20,
4035 'phone2' => 20,
4036 'institution' => 255,
4037 'department' => 255,
4038 'address' => 255,
4039 'city' => 120,
4040 'country' => 2,
4043 // Apply where needed.
4044 foreach (array_keys($info) as $key) {
4045 if (!empty($limit[$key])) {
4046 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4050 return $info;
4054 * Marks user deleted in internal user database and notifies the auth plugin.
4055 * Also unenrols user from all roles and does other cleanup.
4057 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4059 * @param stdClass $user full user object before delete
4060 * @return boolean success
4061 * @throws coding_exception if invalid $user parameter detected
4063 function delete_user(stdClass $user) {
4064 global $CFG, $DB, $SESSION;
4065 require_once($CFG->libdir.'/grouplib.php');
4066 require_once($CFG->libdir.'/gradelib.php');
4067 require_once($CFG->dirroot.'/message/lib.php');
4068 require_once($CFG->dirroot.'/user/lib.php');
4070 // Make sure nobody sends bogus record type as parameter.
4071 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4072 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4075 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4076 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4077 debugging('Attempt to delete unknown user account.');
4078 return false;
4081 // There must be always exactly one guest record, originally the guest account was identified by username only,
4082 // now we use $CFG->siteguest for performance reasons.
4083 if ($user->username === 'guest' or isguestuser($user)) {
4084 debugging('Guest user account can not be deleted.');
4085 return false;
4088 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4089 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4090 if ($user->auth === 'manual' and is_siteadmin($user)) {
4091 debugging('Local administrator accounts can not be deleted.');
4092 return false;
4095 // Allow plugins to use this user object before we completely delete it.
4096 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4097 foreach ($pluginsfunction as $plugintype => $plugins) {
4098 foreach ($plugins as $pluginfunction) {
4099 $pluginfunction($user);
4104 // Keep user record before updating it, as we have to pass this to user_deleted event.
4105 $olduser = clone $user;
4107 // Keep a copy of user context, we need it for event.
4108 $usercontext = context_user::instance($user->id);
4110 // Delete all grades - backup is kept in grade_grades_history table.
4111 grade_user_delete($user->id);
4113 // TODO: remove from cohorts using standard API here.
4115 // Remove user tags.
4116 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4118 // Unconditionally unenrol from all courses.
4119 enrol_user_delete($user);
4121 // Unenrol from all roles in all contexts.
4122 // This might be slow but it is really needed - modules might do some extra cleanup!
4123 role_unassign_all(array('userid' => $user->id));
4125 // Notify the competency subsystem.
4126 \core_competency\api::hook_user_deleted($user->id);
4128 // Now do a brute force cleanup.
4130 // Delete all user events and subscription events.
4131 $DB->delete_records_select('event', 'userid = :userid AND subscriptionid IS NOT NULL', ['userid' => $user->id]);
4133 // Now, delete all calendar subscription from the user.
4134 $DB->delete_records('event_subscriptions', ['userid' => $user->id]);
4136 // Remove from all cohorts.
4137 $DB->delete_records('cohort_members', array('userid' => $user->id));
4139 // Remove from all groups.
4140 $DB->delete_records('groups_members', array('userid' => $user->id));
4142 // Brute force unenrol from all courses.
4143 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4145 // Purge user preferences.
4146 $DB->delete_records('user_preferences', array('userid' => $user->id));
4148 // Purge user extra profile info.
4149 $DB->delete_records('user_info_data', array('userid' => $user->id));
4151 // Purge log of previous password hashes.
4152 $DB->delete_records('user_password_history', array('userid' => $user->id));
4154 // Last course access not necessary either.
4155 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4156 // Remove all user tokens.
4157 $DB->delete_records('external_tokens', array('userid' => $user->id));
4159 // Unauthorise the user for all services.
4160 $DB->delete_records('external_services_users', array('userid' => $user->id));
4162 // Remove users private keys.
4163 $DB->delete_records('user_private_key', array('userid' => $user->id));
4165 // Remove users customised pages.
4166 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4168 // Remove user's oauth2 refresh tokens, if present.
4169 $DB->delete_records('oauth2_refresh_token', array('userid' => $user->id));
4171 // Delete user from $SESSION->bulk_users.
4172 if (isset($SESSION->bulk_users[$user->id])) {
4173 unset($SESSION->bulk_users[$user->id]);
4176 // Force logout - may fail if file based sessions used, sorry.
4177 \core\session\manager::kill_user_sessions($user->id);
4179 // Generate username from email address, or a fake email.
4180 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4182 $deltime = time();
4183 $deltimelength = core_text::strlen((string) $deltime);
4185 // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
4186 $delname = clean_param($delemail, PARAM_USERNAME);
4187 $delname = core_text::substr($delname, 0, 100 - ($deltimelength + 1)) . ".{$deltime}";
4189 // Workaround for bulk deletes of users with the same email address.
4190 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4191 $delname++;
4194 // Mark internal user record as "deleted".
4195 $updateuser = new stdClass();
4196 $updateuser->id = $user->id;
4197 $updateuser->deleted = 1;
4198 $updateuser->username = $delname; // Remember it just in case.
4199 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4200 $updateuser->idnumber = ''; // Clear this field to free it up.
4201 $updateuser->picture = 0;
4202 $updateuser->timemodified = $deltime;
4204 // Don't trigger update event, as user is being deleted.
4205 user_update_user($updateuser, false, false);
4207 // Delete all content associated with the user context, but not the context itself.
4208 $usercontext->delete_content();
4210 // Delete any search data.
4211 \core_search\manager::context_deleted($usercontext);
4213 // Any plugin that needs to cleanup should register this event.
4214 // Trigger event.
4215 $event = \core\event\user_deleted::create(
4216 array(
4217 'objectid' => $user->id,
4218 'relateduserid' => $user->id,
4219 'context' => $usercontext,
4220 'other' => array(
4221 'username' => $user->username,
4222 'email' => $user->email,
4223 'idnumber' => $user->idnumber,
4224 'picture' => $user->picture,
4225 'mnethostid' => $user->mnethostid
4229 $event->add_record_snapshot('user', $olduser);
4230 $event->trigger();
4232 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4233 // should know about this updated property persisted to the user's table.
4234 $user->timemodified = $updateuser->timemodified;
4236 // Notify auth plugin - do not block the delete even when plugin fails.
4237 $authplugin = get_auth_plugin($user->auth);
4238 $authplugin->user_delete($user);
4240 return true;
4244 * Retrieve the guest user object.
4246 * @return stdClass A {@link $USER} object
4248 function guest_user() {
4249 global $CFG, $DB;
4251 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4252 $newuser->confirmed = 1;
4253 $newuser->lang = get_newuser_language();
4254 $newuser->lastip = getremoteaddr();
4257 return $newuser;
4261 * Authenticates a user against the chosen authentication mechanism
4263 * Given a username and password, this function looks them
4264 * up using the currently selected authentication mechanism,
4265 * and if the authentication is successful, it returns a
4266 * valid $user object from the 'user' table.
4268 * Uses auth_ functions from the currently active auth module
4270 * After authenticate_user_login() returns success, you will need to
4271 * log that the user has logged in, and call complete_user_login() to set
4272 * the session up.
4274 * Note: this function works only with non-mnet accounts!
4276 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4277 * @param string $password User's password
4278 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4279 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4280 * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4281 * @return stdClass|false A {@link $USER} object or false if error
4283 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4284 global $CFG, $DB, $PAGE;
4285 require_once("$CFG->libdir/authlib.php");
4287 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4288 // we have found the user
4290 } else if (!empty($CFG->authloginviaemail)) {
4291 if ($email = clean_param($username, PARAM_EMAIL)) {
4292 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4293 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4294 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4295 if (count($users) === 1) {
4296 // Use email for login only if unique.
4297 $user = reset($users);
4298 $user = get_complete_user_data('id', $user->id);
4299 $username = $user->username;
4301 unset($users);
4305 // Make sure this request came from the login form.
4306 if (!\core\session\manager::validate_login_token($logintoken)) {
4307 $failurereason = AUTH_LOGIN_FAILED;
4309 // Trigger login failed event (specifying the ID of the found user, if available).
4310 \core\event\user_login_failed::create([
4311 'userid' => ($user->id ?? 0),
4312 'other' => [
4313 'username' => $username,
4314 'reason' => $failurereason,
4316 ])->trigger();
4318 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4319 return false;
4322 $authsenabled = get_enabled_auth_plugins();
4324 if ($user) {
4325 // Use manual if auth not set.
4326 $auth = empty($user->auth) ? 'manual' : $user->auth;
4328 if (in_array($user->auth, $authsenabled)) {
4329 $authplugin = get_auth_plugin($user->auth);
4330 $authplugin->pre_user_login_hook($user);
4333 if (!empty($user->suspended)) {
4334 $failurereason = AUTH_LOGIN_SUSPENDED;
4336 // Trigger login failed event.
4337 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4338 'other' => array('username' => $username, 'reason' => $failurereason)));
4339 $event->trigger();
4340 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4341 return false;
4343 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4344 // Legacy way to suspend user.
4345 $failurereason = AUTH_LOGIN_SUSPENDED;
4347 // Trigger login failed event.
4348 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4349 'other' => array('username' => $username, 'reason' => $failurereason)));
4350 $event->trigger();
4351 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4352 return false;
4354 $auths = array($auth);
4356 } else {
4357 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4358 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4359 $failurereason = AUTH_LOGIN_NOUSER;
4361 // Trigger login failed event.
4362 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4363 'reason' => $failurereason)));
4364 $event->trigger();
4365 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4366 return false;
4369 // User does not exist.
4370 $auths = $authsenabled;
4371 $user = new stdClass();
4372 $user->id = 0;
4375 if ($ignorelockout) {
4376 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4377 // or this function is called from a SSO script.
4378 } else if ($user->id) {
4379 // Verify login lockout after other ways that may prevent user login.
4380 if (login_is_lockedout($user)) {
4381 $failurereason = AUTH_LOGIN_LOCKOUT;
4383 // Trigger login failed event.
4384 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4385 'other' => array('username' => $username, 'reason' => $failurereason)));
4386 $event->trigger();
4388 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4389 return false;
4391 } else {
4392 // We can not lockout non-existing accounts.
4395 foreach ($auths as $auth) {
4396 $authplugin = get_auth_plugin($auth);
4398 // On auth fail fall through to the next plugin.
4399 if (!$authplugin->user_login($username, $password)) {
4400 continue;
4403 // Before performing login actions, check if user still passes password policy, if admin setting is enabled.
4404 if (!empty($CFG->passwordpolicycheckonlogin)) {
4405 $errmsg = '';
4406 $passed = check_password_policy($password, $errmsg, $user);
4407 if (!$passed) {
4408 // First trigger event for failure.
4409 $failedevent = \core\event\user_password_policy_failed::create_from_user($user);
4410 $failedevent->trigger();
4412 // If able to change password, set flag and move on.
4413 if ($authplugin->can_change_password()) {
4414 // Check if we are on internal change password page, or service is external, don't show notification.
4415 $internalchangeurl = new moodle_url('/login/change_password.php');
4416 if (!($PAGE->has_set_url() && $internalchangeurl->compare($PAGE->url)) && $authplugin->is_internal()) {
4417 \core\notification::error(get_string('passwordpolicynomatch', '', $errmsg));
4419 set_user_preference('auth_forcepasswordchange', 1, $user);
4420 } else if ($authplugin->can_reset_password()) {
4421 // Else force a reset if possible.
4422 \core\notification::error(get_string('forcepasswordresetnotice', '', $errmsg));
4423 redirect(new moodle_url('/login/forgot_password.php'));
4424 } else {
4425 $notifymsg = get_string('forcepasswordresetfailurenotice', '', $errmsg);
4426 // If support page is set, add link for help.
4427 if (!empty($CFG->supportpage)) {
4428 $link = \html_writer::link($CFG->supportpage, $CFG->supportpage);
4429 $link = \html_writer::tag('p', $link);
4430 $notifymsg .= $link;
4433 // If no change or reset is possible, add a notification for user.
4434 \core\notification::error($notifymsg);
4439 // Successful authentication.
4440 if ($user->id) {
4441 // User already exists in database.
4442 if (empty($user->auth)) {
4443 // For some reason auth isn't set yet.
4444 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4445 $user->auth = $auth;
4448 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4449 // the current hash algorithm while we have access to the user's password.
4450 update_internal_user_password($user, $password);
4452 if ($authplugin->is_synchronised_with_external()) {
4453 // Update user record from external DB.
4454 $user = update_user_record_by_id($user->id);
4456 } else {
4457 // The user is authenticated but user creation may be disabled.
4458 if (!empty($CFG->authpreventaccountcreation)) {
4459 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4461 // Trigger login failed event.
4462 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4463 'reason' => $failurereason)));
4464 $event->trigger();
4466 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4467 $_SERVER['HTTP_USER_AGENT']);
4468 return false;
4469 } else {
4470 $user = create_user_record($username, $password, $auth);
4474 $authplugin->sync_roles($user);
4476 foreach ($authsenabled as $hau) {
4477 $hauth = get_auth_plugin($hau);
4478 $hauth->user_authenticated_hook($user, $username, $password);
4481 if (empty($user->id)) {
4482 $failurereason = AUTH_LOGIN_NOUSER;
4483 // Trigger login failed event.
4484 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4485 'reason' => $failurereason)));
4486 $event->trigger();
4487 return false;
4490 if (!empty($user->suspended)) {
4491 // Just in case some auth plugin suspended account.
4492 $failurereason = AUTH_LOGIN_SUSPENDED;
4493 // Trigger login failed event.
4494 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4495 'other' => array('username' => $username, 'reason' => $failurereason)));
4496 $event->trigger();
4497 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4498 return false;
4501 login_attempt_valid($user);
4502 $failurereason = AUTH_LOGIN_OK;
4503 return $user;
4506 // Failed if all the plugins have failed.
4507 if (debugging('', DEBUG_ALL)) {
4508 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4511 if ($user->id) {
4512 login_attempt_failed($user);
4513 $failurereason = AUTH_LOGIN_FAILED;
4514 // Trigger login failed event.
4515 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4516 'other' => array('username' => $username, 'reason' => $failurereason)));
4517 $event->trigger();
4518 } else {
4519 $failurereason = AUTH_LOGIN_NOUSER;
4520 // Trigger login failed event.
4521 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4522 'reason' => $failurereason)));
4523 $event->trigger();
4526 return false;
4530 * Call to complete the user login process after authenticate_user_login()
4531 * has succeeded. It will setup the $USER variable and other required bits
4532 * and pieces.
4534 * NOTE:
4535 * - It will NOT log anything -- up to the caller to decide what to log.
4536 * - this function does not set any cookies any more!
4538 * @param stdClass $user
4539 * @return stdClass A {@link $USER} object - BC only, do not use
4541 function complete_user_login($user) {
4542 global $CFG, $DB, $USER, $SESSION;
4544 \core\session\manager::login_user($user);
4546 // Reload preferences from DB.
4547 unset($USER->preference);
4548 check_user_preferences_loaded($USER);
4550 // Update login times.
4551 update_user_login_times();
4553 // Extra session prefs init.
4554 set_login_session_preferences();
4556 // Trigger login event.
4557 $event = \core\event\user_loggedin::create(
4558 array(
4559 'userid' => $USER->id,
4560 'objectid' => $USER->id,
4561 'other' => array('username' => $USER->username),
4564 $event->trigger();
4566 // Check if the user is using a new browser or session (a new MoodleSession cookie is set in that case).
4567 // If the user is accessing from the same IP, ignore everything (most of the time will be a new session in the same browser).
4568 // Skip Web Service requests, CLI scripts, AJAX scripts, and request from the mobile app itself.
4569 $loginip = getremoteaddr();
4570 $isnewip = isset($SESSION->userpreviousip) && $SESSION->userpreviousip != $loginip;
4571 $isvalidenv = (!WS_SERVER && !CLI_SCRIPT && !NO_MOODLE_COOKIES) || PHPUNIT_TEST;
4573 if (!empty($SESSION->isnewsessioncookie) && $isnewip && $isvalidenv && !\core_useragent::is_moodle_app()) {
4575 $logintime = time();
4576 $ismoodleapp = false;
4577 $useragent = \core_useragent::get_user_agent_string();
4579 // Schedule adhoc task to sent a login notification to the user.
4580 $task = new \core\task\send_login_notifications();
4581 $task->set_userid($USER->id);
4582 $task->set_custom_data(compact('ismoodleapp', 'useragent', 'loginip', 'logintime'));
4583 $task->set_component('core');
4584 \core\task\manager::queue_adhoc_task($task);
4587 // Queue migrating the messaging data, if we need to.
4588 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4589 // Check if there are any legacy messages to migrate.
4590 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4591 \core_message\task\migrate_message_data::queue_task($USER->id);
4592 } else {
4593 set_user_preference('core_message_migrate_data', true, $USER->id);
4597 if (isguestuser()) {
4598 // No need to continue when user is THE guest.
4599 return $USER;
4602 if (CLI_SCRIPT) {
4603 // We can redirect to password change URL only in browser.
4604 return $USER;
4607 // Select password change url.
4608 $userauth = get_auth_plugin($USER->auth);
4610 // Check whether the user should be changing password.
4611 if (get_user_preferences('auth_forcepasswordchange', false)) {
4612 if ($userauth->can_change_password()) {
4613 if ($changeurl = $userauth->change_password_url()) {
4614 redirect($changeurl);
4615 } else {
4616 require_once($CFG->dirroot . '/login/lib.php');
4617 $SESSION->wantsurl = core_login_get_return_url();
4618 redirect($CFG->wwwroot.'/login/change_password.php');
4620 } else {
4621 print_error('nopasswordchangeforced', 'auth');
4624 return $USER;
4628 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4630 * @param string $password String to check.
4631 * @return boolean True if the $password matches the format of an md5 sum.
4633 function password_is_legacy_hash($password) {
4634 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4638 * Compare password against hash stored in user object to determine if it is valid.
4640 * If necessary it also updates the stored hash to the current format.
4642 * @param stdClass $user (Password property may be updated).
4643 * @param string $password Plain text password.
4644 * @return bool True if password is valid.
4646 function validate_internal_user_password($user, $password) {
4647 global $CFG;
4649 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4650 // Internal password is not used at all, it can not validate.
4651 return false;
4654 // If hash isn't a legacy (md5) hash, validate using the library function.
4655 if (!password_is_legacy_hash($user->password)) {
4656 return password_verify($password, $user->password);
4659 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4660 // is valid we can then update it to the new algorithm.
4662 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4663 $validated = false;
4665 if ($user->password === md5($password.$sitesalt)
4666 or $user->password === md5($password)
4667 or $user->password === md5(addslashes($password).$sitesalt)
4668 or $user->password === md5(addslashes($password))) {
4669 // Note: we are intentionally using the addslashes() here because we
4670 // need to accept old password hashes of passwords with magic quotes.
4671 $validated = true;
4673 } else {
4674 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4675 $alt = 'passwordsaltalt'.$i;
4676 if (!empty($CFG->$alt)) {
4677 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4678 $validated = true;
4679 break;
4685 if ($validated) {
4686 // If the password matches the existing md5 hash, update to the
4687 // current hash algorithm while we have access to the user's password.
4688 update_internal_user_password($user, $password);
4691 return $validated;
4695 * Calculate hash for a plain text password.
4697 * @param string $password Plain text password to be hashed.
4698 * @param bool $fasthash If true, use a low cost factor when generating the hash
4699 * This is much faster to generate but makes the hash
4700 * less secure. It is used when lots of hashes need to
4701 * be generated quickly.
4702 * @return string The hashed password.
4704 * @throws moodle_exception If a problem occurs while generating the hash.
4706 function hash_internal_user_password($password, $fasthash = false) {
4707 global $CFG;
4709 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4710 $options = ($fasthash) ? array('cost' => 4) : array();
4712 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4714 if ($generatedhash === false || $generatedhash === null) {
4715 throw new moodle_exception('Failed to generate password hash.');
4718 return $generatedhash;
4722 * Update password hash in user object (if necessary).
4724 * The password is updated if:
4725 * 1. The password has changed (the hash of $user->password is different
4726 * to the hash of $password).
4727 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4728 * md5 algorithm).
4730 * Updating the password will modify the $user object and the database
4731 * record to use the current hashing algorithm.
4732 * It will remove Web Services user tokens too.
4734 * @param stdClass $user User object (password property may be updated).
4735 * @param string $password Plain text password.
4736 * @param bool $fasthash If true, use a low cost factor when generating the hash
4737 * This is much faster to generate but makes the hash
4738 * less secure. It is used when lots of hashes need to
4739 * be generated quickly.
4740 * @return bool Always returns true.
4742 function update_internal_user_password($user, $password, $fasthash = false) {
4743 global $CFG, $DB;
4745 // Figure out what the hashed password should be.
4746 if (!isset($user->auth)) {
4747 debugging('User record in update_internal_user_password() must include field auth',
4748 DEBUG_DEVELOPER);
4749 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4751 $authplugin = get_auth_plugin($user->auth);
4752 if ($authplugin->prevent_local_passwords()) {
4753 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4754 } else {
4755 $hashedpassword = hash_internal_user_password($password, $fasthash);
4758 $algorithmchanged = false;
4760 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4761 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4762 $passwordchanged = ($user->password !== $hashedpassword);
4764 } else if (isset($user->password)) {
4765 // If verification fails then it means the password has changed.
4766 $passwordchanged = !password_verify($password, $user->password);
4767 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4768 } else {
4769 // While creating new user, password in unset in $user object, to avoid
4770 // saving it with user_create()
4771 $passwordchanged = true;
4774 if ($passwordchanged || $algorithmchanged) {
4775 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4776 $user->password = $hashedpassword;
4778 // Trigger event.
4779 $user = $DB->get_record('user', array('id' => $user->id));
4780 \core\event\user_password_updated::create_from_user($user)->trigger();
4782 // Remove WS user tokens.
4783 if (!empty($CFG->passwordchangetokendeletion)) {
4784 require_once($CFG->dirroot.'/webservice/lib.php');
4785 webservice::delete_user_ws_tokens($user->id);
4789 return true;
4793 * Get a complete user record, which includes all the info in the user record.
4795 * Intended for setting as $USER session variable
4797 * @param string $field The user field to be checked for a given value.
4798 * @param string $value The value to match for $field.
4799 * @param int $mnethostid
4800 * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4801 * found. Otherwise, it will just return false.
4802 * @return mixed False, or A {@link $USER} object.
4804 function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4805 global $CFG, $DB;
4807 if (!$field || !$value) {
4808 return false;
4811 // Change the field to lowercase.
4812 $field = core_text::strtolower($field);
4814 // List of case insensitive fields.
4815 $caseinsensitivefields = ['email'];
4817 // Username input is forced to lowercase and should be case sensitive.
4818 if ($field == 'username') {
4819 $value = core_text::strtolower($value);
4822 // Build the WHERE clause for an SQL query.
4823 $params = array('fieldval' => $value);
4825 // Do a case-insensitive query, if necessary. These are generally very expensive. The performance can be improved on some DBs
4826 // such as MySQL by pre-filtering users with accent-insensitive subselect.
4827 if (in_array($field, $caseinsensitivefields)) {
4828 $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4829 $idsubselect = $DB->sql_equal($field, ':fieldval2', false, false);
4830 $params['fieldval2'] = $value;
4831 } else {
4832 $fieldselect = "$field = :fieldval";
4833 $idsubselect = '';
4835 $constraints = "$fieldselect AND deleted <> 1";
4837 // If we are loading user data based on anything other than id,
4838 // we must also restrict our search based on mnet host.
4839 if ($field != 'id') {
4840 if (empty($mnethostid)) {
4841 // If empty, we restrict to local users.
4842 $mnethostid = $CFG->mnet_localhost_id;
4845 if (!empty($mnethostid)) {
4846 $params['mnethostid'] = $mnethostid;
4847 $constraints .= " AND mnethostid = :mnethostid";
4850 if ($idsubselect) {
4851 $constraints .= " AND id IN (SELECT id FROM {user} WHERE {$idsubselect})";
4854 // Get all the basic user data.
4855 try {
4856 // Make sure that there's only a single record that matches our query.
4857 // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4858 // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4859 $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST);
4860 } catch (dml_exception $exception) {
4861 if ($throwexception) {
4862 throw $exception;
4863 } else {
4864 // Return false when no records or multiple records were found.
4865 return false;
4869 // Get various settings and preferences.
4871 // Preload preference cache.
4872 check_user_preferences_loaded($user);
4874 // Load course enrolment related stuff.
4875 $user->lastcourseaccess = array(); // During last session.
4876 $user->currentcourseaccess = array(); // During current session.
4877 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4878 foreach ($lastaccesses as $lastaccess) {
4879 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4883 $sql = "SELECT g.id, g.courseid
4884 FROM {groups} g, {groups_members} gm
4885 WHERE gm.groupid=g.id AND gm.userid=?";
4887 // This is a special hack to speedup calendar display.
4888 $user->groupmember = array();
4889 if (!isguestuser($user)) {
4890 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4891 foreach ($groups as $group) {
4892 if (!array_key_exists($group->courseid, $user->groupmember)) {
4893 $user->groupmember[$group->courseid] = array();
4895 $user->groupmember[$group->courseid][$group->id] = $group->id;
4900 // Add cohort theme.
4901 if (!empty($CFG->allowcohortthemes)) {
4902 require_once($CFG->dirroot . '/cohort/lib.php');
4903 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4904 $user->cohorttheme = $cohorttheme;
4908 // Add the custom profile fields to the user record.
4909 $user->profile = array();
4910 if (!isguestuser($user)) {
4911 require_once($CFG->dirroot.'/user/profile/lib.php');
4912 profile_load_custom_fields($user);
4915 // Rewrite some variables if necessary.
4916 if (!empty($user->description)) {
4917 // No need to cart all of it around.
4918 $user->description = true;
4920 if (isguestuser($user)) {
4921 // Guest language always same as site.
4922 $user->lang = get_newuser_language();
4923 // Name always in current language.
4924 $user->firstname = get_string('guestuser');
4925 $user->lastname = ' ';
4928 return $user;
4932 * Validate a password against the configured password policy
4934 * @param string $password the password to be checked against the password policy
4935 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4936 * @param stdClass $user the user object to perform password validation against. Defaults to null if not provided.
4938 * @return bool true if the password is valid according to the policy. false otherwise.
4940 function check_password_policy($password, &$errmsg, $user = null) {
4941 global $CFG;
4943 if (!empty($CFG->passwordpolicy)) {
4944 $errmsg = '';
4945 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4946 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4948 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4949 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4951 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4952 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4954 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4955 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4957 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4958 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4960 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4961 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4964 // Fire any additional password policy functions from plugins.
4965 // Plugin functions should output an error message string or empty string for success.
4966 $pluginsfunction = get_plugins_with_function('check_password_policy');
4967 foreach ($pluginsfunction as $plugintype => $plugins) {
4968 foreach ($plugins as $pluginfunction) {
4969 $pluginerr = $pluginfunction($password, $user);
4970 if ($pluginerr) {
4971 $errmsg .= '<div>'. $pluginerr .'</div>';
4977 if ($errmsg == '') {
4978 return true;
4979 } else {
4980 return false;
4986 * When logging in, this function is run to set certain preferences for the current SESSION.
4988 function set_login_session_preferences() {
4989 global $SESSION;
4991 $SESSION->justloggedin = true;
4993 unset($SESSION->lang);
4994 unset($SESSION->forcelang);
4995 unset($SESSION->load_navigation_admin);
5000 * Delete a course, including all related data from the database, and any associated files.
5002 * @param mixed $courseorid The id of the course or course object to delete.
5003 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5004 * @return bool true if all the removals succeeded. false if there were any failures. If this
5005 * method returns false, some of the removals will probably have succeeded, and others
5006 * failed, but you have no way of knowing which.
5008 function delete_course($courseorid, $showfeedback = true) {
5009 global $DB;
5011 if (is_object($courseorid)) {
5012 $courseid = $courseorid->id;
5013 $course = $courseorid;
5014 } else {
5015 $courseid = $courseorid;
5016 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
5017 return false;
5020 $context = context_course::instance($courseid);
5022 // Frontpage course can not be deleted!!
5023 if ($courseid == SITEID) {
5024 return false;
5027 // Allow plugins to use this course before we completely delete it.
5028 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
5029 foreach ($pluginsfunction as $plugintype => $plugins) {
5030 foreach ($plugins as $pluginfunction) {
5031 $pluginfunction($course);
5036 // Tell the search manager we are about to delete a course. This prevents us sending updates
5037 // for each individual context being deleted.
5038 \core_search\manager::course_deleting_start($courseid);
5040 $handler = core_course\customfield\course_handler::create();
5041 $handler->delete_instance($courseid);
5043 // Make the course completely empty.
5044 remove_course_contents($courseid, $showfeedback);
5046 // Delete the course and related context instance.
5047 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
5049 $DB->delete_records("course", array("id" => $courseid));
5050 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5052 // Reset all course related caches here.
5053 core_courseformat\base::reset_course_cache($courseid);
5055 // Tell search that we have deleted the course so it can delete course data from the index.
5056 \core_search\manager::course_deleting_finish($courseid);
5058 // Trigger a course deleted event.
5059 $event = \core\event\course_deleted::create(array(
5060 'objectid' => $course->id,
5061 'context' => $context,
5062 'other' => array(
5063 'shortname' => $course->shortname,
5064 'fullname' => $course->fullname,
5065 'idnumber' => $course->idnumber
5068 $event->add_record_snapshot('course', $course);
5069 $event->trigger();
5071 return true;
5075 * Clear a course out completely, deleting all content but don't delete the course itself.
5077 * This function does not verify any permissions.
5079 * Please note this function also deletes all user enrolments,
5080 * enrolment instances and role assignments by default.
5082 * $options:
5083 * - 'keep_roles_and_enrolments' - false by default
5084 * - 'keep_groups_and_groupings' - false by default
5086 * @param int $courseid The id of the course that is being deleted
5087 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5088 * @param array $options extra options
5089 * @return bool true if all the removals succeeded. false if there were any failures. If this
5090 * method returns false, some of the removals will probably have succeeded, and others
5091 * failed, but you have no way of knowing which.
5093 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5094 global $CFG, $DB, $OUTPUT;
5096 require_once($CFG->libdir.'/badgeslib.php');
5097 require_once($CFG->libdir.'/completionlib.php');
5098 require_once($CFG->libdir.'/questionlib.php');
5099 require_once($CFG->libdir.'/gradelib.php');
5100 require_once($CFG->dirroot.'/group/lib.php');
5101 require_once($CFG->dirroot.'/comment/lib.php');
5102 require_once($CFG->dirroot.'/rating/lib.php');
5103 require_once($CFG->dirroot.'/notes/lib.php');
5105 // Handle course badges.
5106 badges_handle_course_deletion($courseid);
5108 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5109 $strdeleted = get_string('deleted').' - ';
5111 // Some crazy wishlist of stuff we should skip during purging of course content.
5112 $options = (array)$options;
5114 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5115 $coursecontext = context_course::instance($courseid);
5116 $fs = get_file_storage();
5118 // Delete course completion information, this has to be done before grades and enrols.
5119 $cc = new completion_info($course);
5120 $cc->clear_criteria();
5121 if ($showfeedback) {
5122 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5125 // Remove all data from gradebook - this needs to be done before course modules
5126 // because while deleting this information, the system may need to reference
5127 // the course modules that own the grades.
5128 remove_course_grades($courseid, $showfeedback);
5129 remove_grade_letters($coursecontext, $showfeedback);
5131 // Delete course blocks in any all child contexts,
5132 // they may depend on modules so delete them first.
5133 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5134 foreach ($childcontexts as $childcontext) {
5135 blocks_delete_all_for_context($childcontext->id);
5137 unset($childcontexts);
5138 blocks_delete_all_for_context($coursecontext->id);
5139 if ($showfeedback) {
5140 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5143 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $courseid]);
5144 rebuild_course_cache($courseid, true);
5146 // Get the list of all modules that are properly installed.
5147 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5149 // Delete every instance of every module,
5150 // this has to be done before deleting of course level stuff.
5151 $locations = core_component::get_plugin_list('mod');
5152 foreach ($locations as $modname => $moddir) {
5153 if ($modname === 'NEWMODULE') {
5154 continue;
5156 if (array_key_exists($modname, $allmodules)) {
5157 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5158 FROM {".$modname."} m
5159 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5160 WHERE m.course = :courseid";
5161 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5162 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5164 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5165 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5167 if ($instances) {
5168 foreach ($instances as $cm) {
5169 if ($cm->id) {
5170 // Delete activity context questions and question categories.
5171 question_delete_activity($cm);
5172 // Notify the competency subsystem.
5173 \core_competency\api::hook_course_module_deleted($cm);
5175 if (function_exists($moddelete)) {
5176 // This purges all module data in related tables, extra user prefs, settings, etc.
5177 $moddelete($cm->modinstance);
5178 } else {
5179 // NOTE: we should not allow installation of modules with missing delete support!
5180 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5181 $DB->delete_records($modname, array('id' => $cm->modinstance));
5184 if ($cm->id) {
5185 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5186 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5187 $DB->delete_records('course_modules_completion', ['coursemoduleid' => $cm->id]);
5188 $DB->delete_records('course_modules', array('id' => $cm->id));
5189 rebuild_course_cache($cm->course, true);
5193 if ($instances and $showfeedback) {
5194 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5196 } else {
5197 // Ooops, this module is not properly installed, force-delete it in the next block.
5201 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5203 // Delete completion defaults.
5204 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5206 // Remove all data from availability and completion tables that is associated
5207 // with course-modules belonging to this course. Note this is done even if the
5208 // features are not enabled now, in case they were enabled previously.
5209 $DB->delete_records_subquery('course_modules_completion', 'coursemoduleid', 'id',
5210 'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
5212 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5213 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5214 $allmodulesbyid = array_flip($allmodules);
5215 foreach ($cms as $cm) {
5216 if (array_key_exists($cm->module, $allmodulesbyid)) {
5217 try {
5218 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5219 } catch (Exception $e) {
5220 // Ignore weird or missing table problems.
5223 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5224 $DB->delete_records('course_modules', array('id' => $cm->id));
5225 rebuild_course_cache($cm->course, true);
5228 if ($showfeedback) {
5229 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5232 // Delete questions and question categories.
5233 question_delete_course($course);
5234 if ($showfeedback) {
5235 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5238 // Delete content bank contents.
5239 $cb = new \core_contentbank\contentbank();
5240 $cbdeleted = $cb->delete_contents($coursecontext);
5241 if ($showfeedback && $cbdeleted) {
5242 echo $OUTPUT->notification($strdeleted.get_string('contentbank', 'contentbank'), 'notifysuccess');
5245 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5246 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5247 foreach ($childcontexts as $childcontext) {
5248 $childcontext->delete();
5250 unset($childcontexts);
5252 // Remove roles and enrolments by default.
5253 if (empty($options['keep_roles_and_enrolments'])) {
5254 // This hack is used in restore when deleting contents of existing course.
5255 // During restore, we should remove only enrolment related data that the user performing the restore has a
5256 // permission to remove.
5257 $userid = $options['userid'] ?? null;
5258 enrol_course_delete($course, $userid);
5259 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5260 if ($showfeedback) {
5261 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5265 // Delete any groups, removing members and grouping/course links first.
5266 if (empty($options['keep_groups_and_groupings'])) {
5267 groups_delete_groupings($course->id, $showfeedback);
5268 groups_delete_groups($course->id, $showfeedback);
5271 // Filters be gone!
5272 filter_delete_all_for_context($coursecontext->id);
5274 // Notes, you shall not pass!
5275 note_delete_all($course->id);
5277 // Die comments!
5278 comment::delete_comments($coursecontext->id);
5280 // Ratings are history too.
5281 $delopt = new stdclass();
5282 $delopt->contextid = $coursecontext->id;
5283 $rm = new rating_manager();
5284 $rm->delete_ratings($delopt);
5286 // Delete course tags.
5287 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5289 // Give the course format the opportunity to remove its obscure data.
5290 $format = course_get_format($course);
5291 $format->delete_format_data();
5293 // Notify the competency subsystem.
5294 \core_competency\api::hook_course_deleted($course);
5296 // Delete calendar events.
5297 $DB->delete_records('event', array('courseid' => $course->id));
5298 $fs->delete_area_files($coursecontext->id, 'calendar');
5300 // Delete all related records in other core tables that may have a courseid
5301 // This array stores the tables that need to be cleared, as
5302 // table_name => column_name that contains the course id.
5303 $tablestoclear = array(
5304 'backup_courses' => 'courseid', // Scheduled backup stuff.
5305 'user_lastaccess' => 'courseid', // User access info.
5307 foreach ($tablestoclear as $table => $col) {
5308 $DB->delete_records($table, array($col => $course->id));
5311 // Delete all course backup files.
5312 $fs->delete_area_files($coursecontext->id, 'backup');
5314 // Cleanup course record - remove links to deleted stuff.
5315 $oldcourse = new stdClass();
5316 $oldcourse->id = $course->id;
5317 $oldcourse->summary = '';
5318 $oldcourse->cacherev = 0;
5319 $oldcourse->legacyfiles = 0;
5320 if (!empty($options['keep_groups_and_groupings'])) {
5321 $oldcourse->defaultgroupingid = 0;
5323 $DB->update_record('course', $oldcourse);
5325 // Delete course sections.
5326 $DB->delete_records('course_sections', array('course' => $course->id));
5328 // Delete legacy, section and any other course files.
5329 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5331 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5332 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5333 // Easy, do not delete the context itself...
5334 $coursecontext->delete_content();
5335 } else {
5336 // Hack alert!!!!
5337 // We can not drop all context stuff because it would bork enrolments and roles,
5338 // there might be also files used by enrol plugins...
5341 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5342 // also some non-standard unsupported plugins may try to store something there.
5343 fulldelete($CFG->dataroot.'/'.$course->id);
5345 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5346 course_modinfo::purge_course_cache($courseid);
5348 // Trigger a course content deleted event.
5349 $event = \core\event\course_content_deleted::create(array(
5350 'objectid' => $course->id,
5351 'context' => $coursecontext,
5352 'other' => array('shortname' => $course->shortname,
5353 'fullname' => $course->fullname,
5354 'options' => $options) // Passing this for legacy reasons.
5356 $event->add_record_snapshot('course', $course);
5357 $event->trigger();
5359 return true;
5363 * Change dates in module - used from course reset.
5365 * @param string $modname forum, assignment, etc
5366 * @param array $fields array of date fields from mod table
5367 * @param int $timeshift time difference
5368 * @param int $courseid
5369 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5370 * @return bool success
5372 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5373 global $CFG, $DB;
5374 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5376 $return = true;
5377 $params = array($timeshift, $courseid);
5378 foreach ($fields as $field) {
5379 $updatesql = "UPDATE {".$modname."}
5380 SET $field = $field + ?
5381 WHERE course=? AND $field<>0";
5382 if ($modid) {
5383 $updatesql .= ' AND id=?';
5384 $params[] = $modid;
5386 $return = $DB->execute($updatesql, $params) && $return;
5389 return $return;
5393 * This function will empty a course of user data.
5394 * It will retain the activities and the structure of the course.
5396 * @param object $data an object containing all the settings including courseid (without magic quotes)
5397 * @return array status array of array component, item, error
5399 function reset_course_userdata($data) {
5400 global $CFG, $DB;
5401 require_once($CFG->libdir.'/gradelib.php');
5402 require_once($CFG->libdir.'/completionlib.php');
5403 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5404 require_once($CFG->dirroot.'/group/lib.php');
5406 $data->courseid = $data->id;
5407 $context = context_course::instance($data->courseid);
5409 $eventparams = array(
5410 'context' => $context,
5411 'courseid' => $data->id,
5412 'other' => array(
5413 'reset_options' => (array) $data
5416 $event = \core\event\course_reset_started::create($eventparams);
5417 $event->trigger();
5419 // Calculate the time shift of dates.
5420 if (!empty($data->reset_start_date)) {
5421 // Time part of course startdate should be zero.
5422 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5423 } else {
5424 $data->timeshift = 0;
5427 // Result array: component, item, error.
5428 $status = array();
5430 // Start the resetting.
5431 $componentstr = get_string('general');
5433 // Move the course start time.
5434 if (!empty($data->reset_start_date) and $data->timeshift) {
5435 // Change course start data.
5436 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5437 // Update all course and group events - do not move activity events.
5438 $updatesql = "UPDATE {event}
5439 SET timestart = timestart + ?
5440 WHERE courseid=? AND instance=0";
5441 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5443 // Update any date activity restrictions.
5444 if ($CFG->enableavailability) {
5445 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5448 // Update completion expected dates.
5449 if ($CFG->enablecompletion) {
5450 $modinfo = get_fast_modinfo($data->courseid);
5451 $changed = false;
5452 foreach ($modinfo->get_cms() as $cm) {
5453 if ($cm->completion && !empty($cm->completionexpected)) {
5454 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5455 array('id' => $cm->id));
5456 $changed = true;
5460 // Clear course cache if changes made.
5461 if ($changed) {
5462 rebuild_course_cache($data->courseid, true);
5465 // Update course date completion criteria.
5466 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5469 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5472 if (!empty($data->reset_end_date)) {
5473 // If the user set a end date value respect it.
5474 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5475 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5476 // If there is a time shift apply it to the end date as well.
5477 $enddate = $data->reset_end_date_old + $data->timeshift;
5478 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5481 if (!empty($data->reset_events)) {
5482 $DB->delete_records('event', array('courseid' => $data->courseid));
5483 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5486 if (!empty($data->reset_notes)) {
5487 require_once($CFG->dirroot.'/notes/lib.php');
5488 note_delete_all($data->courseid);
5489 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5492 if (!empty($data->delete_blog_associations)) {
5493 require_once($CFG->dirroot.'/blog/lib.php');
5494 blog_remove_associations_for_course($data->courseid);
5495 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5498 if (!empty($data->reset_completion)) {
5499 // Delete course and activity completion information.
5500 $course = $DB->get_record('course', array('id' => $data->courseid));
5501 $cc = new completion_info($course);
5502 $cc->delete_all_completion_data();
5503 $status[] = array('component' => $componentstr,
5504 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5507 if (!empty($data->reset_competency_ratings)) {
5508 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5509 $status[] = array('component' => $componentstr,
5510 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5513 $componentstr = get_string('roles');
5515 if (!empty($data->reset_roles_overrides)) {
5516 $children = $context->get_child_contexts();
5517 foreach ($children as $child) {
5518 $child->delete_capabilities();
5520 $context->delete_capabilities();
5521 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5524 if (!empty($data->reset_roles_local)) {
5525 $children = $context->get_child_contexts();
5526 foreach ($children as $child) {
5527 role_unassign_all(array('contextid' => $child->id));
5529 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5532 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5533 $data->unenrolled = array();
5534 if (!empty($data->unenrol_users)) {
5535 $plugins = enrol_get_plugins(true);
5536 $instances = enrol_get_instances($data->courseid, true);
5537 foreach ($instances as $key => $instance) {
5538 if (!isset($plugins[$instance->enrol])) {
5539 unset($instances[$key]);
5540 continue;
5544 $usersroles = enrol_get_course_users_roles($data->courseid);
5545 foreach ($data->unenrol_users as $withroleid) {
5546 if ($withroleid) {
5547 $sql = "SELECT ue.*
5548 FROM {user_enrolments} ue
5549 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5550 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5551 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5552 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5554 } else {
5555 // Without any role assigned at course context.
5556 $sql = "SELECT ue.*
5557 FROM {user_enrolments} ue
5558 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5559 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5560 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5561 WHERE ra.id IS null";
5562 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5565 $rs = $DB->get_recordset_sql($sql, $params);
5566 foreach ($rs as $ue) {
5567 if (!isset($instances[$ue->enrolid])) {
5568 continue;
5570 $instance = $instances[$ue->enrolid];
5571 $plugin = $plugins[$instance->enrol];
5572 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5573 continue;
5576 if ($withroleid && count($usersroles[$ue->userid]) > 1) {
5577 // If we don't remove all roles and user has more than one role, just remove this role.
5578 role_unassign($withroleid, $ue->userid, $context->id);
5580 unset($usersroles[$ue->userid][$withroleid]);
5581 } else {
5582 // If we remove all roles or user has only one role, unenrol user from course.
5583 $plugin->unenrol_user($instance, $ue->userid);
5585 $data->unenrolled[$ue->userid] = $ue->userid;
5587 $rs->close();
5590 if (!empty($data->unenrolled)) {
5591 $status[] = array(
5592 'component' => $componentstr,
5593 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5594 'error' => false
5598 $componentstr = get_string('groups');
5600 // Remove all group members.
5601 if (!empty($data->reset_groups_members)) {
5602 groups_delete_group_members($data->courseid);
5603 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5606 // Remove all groups.
5607 if (!empty($data->reset_groups_remove)) {
5608 groups_delete_groups($data->courseid, false);
5609 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5612 // Remove all grouping members.
5613 if (!empty($data->reset_groupings_members)) {
5614 groups_delete_groupings_groups($data->courseid, false);
5615 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5618 // Remove all groupings.
5619 if (!empty($data->reset_groupings_remove)) {
5620 groups_delete_groupings($data->courseid, false);
5621 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5624 // Look in every instance of every module for data to delete.
5625 $unsupportedmods = array();
5626 if ($allmods = $DB->get_records('modules') ) {
5627 foreach ($allmods as $mod) {
5628 $modname = $mod->name;
5629 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5630 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5631 if (file_exists($modfile)) {
5632 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5633 continue; // Skip mods with no instances.
5635 include_once($modfile);
5636 if (function_exists($moddeleteuserdata)) {
5637 $modstatus = $moddeleteuserdata($data);
5638 if (is_array($modstatus)) {
5639 $status = array_merge($status, $modstatus);
5640 } else {
5641 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5643 } else {
5644 $unsupportedmods[] = $mod;
5646 } else {
5647 debugging('Missing lib.php in '.$modname.' module!');
5649 // Update calendar events for all modules.
5650 course_module_bulk_update_calendar_events($modname, $data->courseid);
5654 // Mention unsupported mods.
5655 if (!empty($unsupportedmods)) {
5656 foreach ($unsupportedmods as $mod) {
5657 $status[] = array(
5658 'component' => get_string('modulenameplural', $mod->name),
5659 'item' => '',
5660 'error' => get_string('resetnotimplemented')
5665 $componentstr = get_string('gradebook', 'grades');
5666 // Reset gradebook,.
5667 if (!empty($data->reset_gradebook_items)) {
5668 remove_course_grades($data->courseid, false);
5669 grade_grab_course_grades($data->courseid);
5670 grade_regrade_final_grades($data->courseid);
5671 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5673 } else if (!empty($data->reset_gradebook_grades)) {
5674 grade_course_reset($data->courseid);
5675 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5677 // Reset comments.
5678 if (!empty($data->reset_comments)) {
5679 require_once($CFG->dirroot.'/comment/lib.php');
5680 comment::reset_course_page_comments($context);
5683 $event = \core\event\course_reset_ended::create($eventparams);
5684 $event->trigger();
5686 return $status;
5690 * Generate an email processing address.
5692 * @param int $modid
5693 * @param string $modargs
5694 * @return string Returns email processing address
5696 function generate_email_processing_address($modid, $modargs) {
5697 global $CFG;
5699 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5700 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5706 * @todo Finish documenting this function
5708 * @param string $modargs
5709 * @param string $body Currently unused
5711 function moodle_process_email($modargs, $body) {
5712 global $DB;
5714 // The first char should be an unencoded letter. We'll take this as an action.
5715 switch ($modargs[0]) {
5716 case 'B': { // Bounce.
5717 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5718 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5719 // Check the half md5 of their email.
5720 $md5check = substr(md5($user->email), 0, 16);
5721 if ($md5check == substr($modargs, -16)) {
5722 set_bounce_count($user);
5724 // Else maybe they've already changed it?
5727 break;
5728 // Maybe more later?
5732 // CORRESPONDENCE.
5735 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5737 * @param string $action 'get', 'buffer', 'close' or 'flush'
5738 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5740 function get_mailer($action='get') {
5741 global $CFG;
5743 /** @var moodle_phpmailer $mailer */
5744 static $mailer = null;
5745 static $counter = 0;
5747 if (!isset($CFG->smtpmaxbulk)) {
5748 $CFG->smtpmaxbulk = 1;
5751 if ($action == 'get') {
5752 $prevkeepalive = false;
5754 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5755 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5756 $counter++;
5757 // Reset the mailer.
5758 $mailer->Priority = 3;
5759 $mailer->CharSet = 'UTF-8'; // Our default.
5760 $mailer->ContentType = "text/plain";
5761 $mailer->Encoding = "8bit";
5762 $mailer->From = "root@localhost";
5763 $mailer->FromName = "Root User";
5764 $mailer->Sender = "";
5765 $mailer->Subject = "";
5766 $mailer->Body = "";
5767 $mailer->AltBody = "";
5768 $mailer->ConfirmReadingTo = "";
5770 $mailer->clearAllRecipients();
5771 $mailer->clearReplyTos();
5772 $mailer->clearAttachments();
5773 $mailer->clearCustomHeaders();
5774 return $mailer;
5777 $prevkeepalive = $mailer->SMTPKeepAlive;
5778 get_mailer('flush');
5781 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5782 $mailer = new moodle_phpmailer();
5784 $counter = 1;
5786 if ($CFG->smtphosts == 'qmail') {
5787 // Use Qmail system.
5788 $mailer->isQmail();
5790 } else if (empty($CFG->smtphosts)) {
5791 // Use PHP mail() = sendmail.
5792 $mailer->isMail();
5794 } else {
5795 // Use SMTP directly.
5796 $mailer->isSMTP();
5797 if (!empty($CFG->debugsmtp) && (!empty($CFG->debugdeveloper))) {
5798 $mailer->SMTPDebug = 3;
5800 // Specify main and backup servers.
5801 $mailer->Host = $CFG->smtphosts;
5802 // Specify secure connection protocol.
5803 $mailer->SMTPSecure = $CFG->smtpsecure;
5804 // Use previous keepalive.
5805 $mailer->SMTPKeepAlive = $prevkeepalive;
5807 if ($CFG->smtpuser) {
5808 // Use SMTP authentication.
5809 $mailer->SMTPAuth = true;
5810 $mailer->Username = $CFG->smtpuser;
5811 $mailer->Password = $CFG->smtppass;
5815 return $mailer;
5818 $nothing = null;
5820 // Keep smtp session open after sending.
5821 if ($action == 'buffer') {
5822 if (!empty($CFG->smtpmaxbulk)) {
5823 get_mailer('flush');
5824 $m = get_mailer();
5825 if ($m->Mailer == 'smtp') {
5826 $m->SMTPKeepAlive = true;
5829 return $nothing;
5832 // Close smtp session, but continue buffering.
5833 if ($action == 'flush') {
5834 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5835 if (!empty($mailer->SMTPDebug)) {
5836 echo '<pre>'."\n";
5838 $mailer->SmtpClose();
5839 if (!empty($mailer->SMTPDebug)) {
5840 echo '</pre>';
5843 return $nothing;
5846 // Close smtp session, do not buffer anymore.
5847 if ($action == 'close') {
5848 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5849 get_mailer('flush');
5850 $mailer->SMTPKeepAlive = false;
5852 $mailer = null; // Better force new instance.
5853 return $nothing;
5858 * A helper function to test for email diversion
5860 * @param string $email
5861 * @return bool Returns true if the email should be diverted
5863 function email_should_be_diverted($email) {
5864 global $CFG;
5866 if (empty($CFG->divertallemailsto)) {
5867 return false;
5870 if (empty($CFG->divertallemailsexcept)) {
5871 return true;
5874 $patterns = array_map('trim', preg_split("/[\s,]+/", $CFG->divertallemailsexcept));
5875 foreach ($patterns as $pattern) {
5876 if (preg_match("/$pattern/", $email)) {
5877 return false;
5881 return true;
5885 * Generate a unique email Message-ID using the moodle domain and install path
5887 * @param string $localpart An optional unique message id prefix.
5888 * @return string The formatted ID ready for appending to the email headers.
5890 function generate_email_messageid($localpart = null) {
5891 global $CFG;
5893 $urlinfo = parse_url($CFG->wwwroot);
5894 $base = '@' . $urlinfo['host'];
5896 // If multiple moodles are on the same domain we want to tell them
5897 // apart so we add the install path to the local part. This means
5898 // that the id local part should never contain a / character so
5899 // we can correctly parse the id to reassemble the wwwroot.
5900 if (isset($urlinfo['path'])) {
5901 $base = $urlinfo['path'] . $base;
5904 if (empty($localpart)) {
5905 $localpart = uniqid('', true);
5908 // Because we may have an option /installpath suffix to the local part
5909 // of the id we need to escape any / chars which are in the $localpart.
5910 $localpart = str_replace('/', '%2F', $localpart);
5912 return '<' . $localpart . $base . '>';
5916 * Send an email to a specified user
5918 * @param stdClass $user A {@link $USER} object
5919 * @param stdClass $from A {@link $USER} object
5920 * @param string $subject plain text subject line of the email
5921 * @param string $messagetext plain text version of the message
5922 * @param string $messagehtml complete html version of the message (optional)
5923 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in one of
5924 * the following directories: $CFG->cachedir, $CFG->dataroot, $CFG->dirroot, $CFG->localcachedir, $CFG->tempdir
5925 * @param string $attachname the name of the file (extension indicates MIME)
5926 * @param bool $usetrueaddress determines whether $from email address should
5927 * be sent out. Will be overruled by user profile setting for maildisplay
5928 * @param string $replyto Email address to reply to
5929 * @param string $replytoname Name of reply to recipient
5930 * @param int $wordwrapwidth custom word wrap width, default 79
5931 * @return bool Returns true if mail was sent OK and false if there was an error.
5933 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5934 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5936 global $CFG, $PAGE, $SITE;
5938 if (empty($user) or empty($user->id)) {
5939 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5940 return false;
5943 if (empty($user->email)) {
5944 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5945 return false;
5948 if (!empty($user->deleted)) {
5949 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5950 return false;
5953 if (defined('BEHAT_SITE_RUNNING')) {
5954 // Fake email sending in behat.
5955 return true;
5958 if (!empty($CFG->noemailever)) {
5959 // Hidden setting for development sites, set in config.php if needed.
5960 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5961 return true;
5964 if (email_should_be_diverted($user->email)) {
5965 $subject = "[DIVERTED {$user->email}] $subject";
5966 $user = clone($user);
5967 $user->email = $CFG->divertallemailsto;
5970 // Skip mail to suspended users.
5971 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5972 return true;
5975 if (!validate_email($user->email)) {
5976 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5977 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5978 return false;
5981 if (over_bounce_threshold($user)) {
5982 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5983 return false;
5986 // TLD .invalid is specifically reserved for invalid domain names.
5987 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5988 if (substr($user->email, -8) == '.invalid') {
5989 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5990 return true; // This is not an error.
5993 // If the user is a remote mnet user, parse the email text for URL to the
5994 // wwwroot and modify the url to direct the user's browser to login at their
5995 // home site (identity provider - idp) before hitting the link itself.
5996 if (is_mnet_remote_user($user)) {
5997 require_once($CFG->dirroot.'/mnet/lib.php');
5999 $jumpurl = mnet_get_idp_jump_url($user);
6000 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
6002 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
6003 $callback,
6004 $messagetext);
6005 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
6006 $callback,
6007 $messagehtml);
6009 $mail = get_mailer();
6011 if (!empty($mail->SMTPDebug)) {
6012 echo '<pre>' . "\n";
6015 $temprecipients = array();
6016 $tempreplyto = array();
6018 // Make sure that we fall back onto some reasonable no-reply address.
6019 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
6020 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
6022 if (!validate_email($noreplyaddress)) {
6023 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
6024 $noreplyaddress = $noreplyaddressdefault;
6027 // Make up an email address for handling bounces.
6028 if (!empty($CFG->handlebounces)) {
6029 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
6030 $mail->Sender = generate_email_processing_address(0, $modargs);
6031 } else {
6032 $mail->Sender = $noreplyaddress;
6035 // Make sure that the explicit replyto is valid, fall back to the implicit one.
6036 if (!empty($replyto) && !validate_email($replyto)) {
6037 debugging('email_to_user: Invalid replyto-email '.s($replyto));
6038 $replyto = $noreplyaddress;
6041 if (is_string($from)) { // So we can pass whatever we want if there is need.
6042 $mail->From = $noreplyaddress;
6043 $mail->FromName = $from;
6044 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
6045 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6046 // in a course with the sender.
6047 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
6048 if (!validate_email($from->email)) {
6049 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
6050 // Better not to use $noreplyaddress in this case.
6051 return false;
6053 $mail->From = $from->email;
6054 $fromdetails = new stdClass();
6055 $fromdetails->name = fullname($from);
6056 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6057 $fromdetails->siteshortname = format_string($SITE->shortname);
6058 $fromstring = $fromdetails->name;
6059 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
6060 $fromstring = get_string('emailvia', 'core', $fromdetails);
6062 $mail->FromName = $fromstring;
6063 if (empty($replyto)) {
6064 $tempreplyto[] = array($from->email, fullname($from));
6066 } else {
6067 $mail->From = $noreplyaddress;
6068 $fromdetails = new stdClass();
6069 $fromdetails->name = fullname($from);
6070 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6071 $fromdetails->siteshortname = format_string($SITE->shortname);
6072 $fromstring = $fromdetails->name;
6073 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
6074 $fromstring = get_string('emailvia', 'core', $fromdetails);
6076 $mail->FromName = $fromstring;
6077 if (empty($replyto)) {
6078 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
6082 if (!empty($replyto)) {
6083 $tempreplyto[] = array($replyto, $replytoname);
6086 $temprecipients[] = array($user->email, fullname($user));
6088 // Set word wrap.
6089 $mail->WordWrap = $wordwrapwidth;
6091 if (!empty($from->customheaders)) {
6092 // Add custom headers.
6093 if (is_array($from->customheaders)) {
6094 foreach ($from->customheaders as $customheader) {
6095 $mail->addCustomHeader($customheader);
6097 } else {
6098 $mail->addCustomHeader($from->customheaders);
6102 // If the X-PHP-Originating-Script email header is on then also add an additional
6103 // header with details of where exactly in moodle the email was triggered from,
6104 // either a call to message_send() or to email_to_user().
6105 if (ini_get('mail.add_x_header')) {
6107 $stack = debug_backtrace(false);
6108 $origin = $stack[0];
6110 foreach ($stack as $depth => $call) {
6111 if ($call['function'] == 'message_send') {
6112 $origin = $call;
6116 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
6117 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
6118 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
6121 if (!empty($CFG->emailheaders)) {
6122 $headers = array_map('trim', explode("\n", $CFG->emailheaders));
6123 foreach ($headers as $header) {
6124 if (!empty($header)) {
6125 $mail->addCustomHeader($header);
6130 if (!empty($from->priority)) {
6131 $mail->Priority = $from->priority;
6134 $renderer = $PAGE->get_renderer('core');
6135 $context = array(
6136 'sitefullname' => $SITE->fullname,
6137 'siteshortname' => $SITE->shortname,
6138 'sitewwwroot' => $CFG->wwwroot,
6139 'subject' => $subject,
6140 'prefix' => $CFG->emailsubjectprefix,
6141 'to' => $user->email,
6142 'toname' => fullname($user),
6143 'from' => $mail->From,
6144 'fromname' => $mail->FromName,
6146 if (!empty($tempreplyto[0])) {
6147 $context['replyto'] = $tempreplyto[0][0];
6148 $context['replytoname'] = $tempreplyto[0][1];
6150 if ($user->id > 0) {
6151 $context['touserid'] = $user->id;
6152 $context['tousername'] = $user->username;
6155 if (!empty($user->mailformat) && $user->mailformat == 1) {
6156 // Only process html templates if the user preferences allow html email.
6158 if (!$messagehtml) {
6159 // If no html has been given, BUT there is an html wrapping template then
6160 // auto convert the text to html and then wrap it.
6161 $messagehtml = trim(text_to_html($messagetext));
6163 $context['body'] = $messagehtml;
6164 $messagehtml = $renderer->render_from_template('core/email_html', $context);
6167 $context['body'] = html_to_text(nl2br($messagetext));
6168 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
6169 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
6170 $messagetext = $renderer->render_from_template('core/email_text', $context);
6172 // Autogenerate a MessageID if it's missing.
6173 if (empty($mail->MessageID)) {
6174 $mail->MessageID = generate_email_messageid();
6177 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6178 // Don't ever send HTML to users who don't want it.
6179 $mail->isHTML(true);
6180 $mail->Encoding = 'quoted-printable';
6181 $mail->Body = $messagehtml;
6182 $mail->AltBody = "\n$messagetext\n";
6183 } else {
6184 $mail->IsHTML(false);
6185 $mail->Body = "\n$messagetext\n";
6188 if ($attachment && $attachname) {
6189 if (preg_match( "~\\.\\.~" , $attachment )) {
6190 // Security check for ".." in dir path.
6191 $supportuser = core_user::get_support_user();
6192 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6193 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6194 } else {
6195 require_once($CFG->libdir.'/filelib.php');
6196 $mimetype = mimeinfo('type', $attachname);
6198 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6199 // The absolute (real) path is also fetched to ensure that comparisons to allowed paths are compared equally.
6200 $attachpath = str_replace('\\', '/', realpath($attachment));
6202 // Build an array of all filepaths from which attachments can be added (normalised slashes, absolute/real path).
6203 $allowedpaths = array_map(function(string $path): string {
6204 return str_replace('\\', '/', realpath($path));
6205 }, [
6206 $CFG->cachedir,
6207 $CFG->dataroot,
6208 $CFG->dirroot,
6209 $CFG->localcachedir,
6210 $CFG->tempdir,
6211 $CFG->localrequestdir,
6214 // Set addpath to true.
6215 $addpath = true;
6217 // Check if attachment includes one of the allowed paths.
6218 foreach (array_filter($allowedpaths) as $allowedpath) {
6219 // Set addpath to false if the attachment includes one of the allowed paths.
6220 if (strpos($attachpath, $allowedpath) === 0) {
6221 $addpath = false;
6222 break;
6226 // If the attachment is a full path to a file in the multiple allowed paths, use it as is,
6227 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6228 if ($addpath == true) {
6229 $attachment = $CFG->dataroot . '/' . $attachment;
6232 $mail->addAttachment($attachment, $attachname, 'base64', $mimetype);
6236 // Check if the email should be sent in an other charset then the default UTF-8.
6237 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6239 // Use the defined site mail charset or eventually the one preferred by the recipient.
6240 $charset = $CFG->sitemailcharset;
6241 if (!empty($CFG->allowusermailcharset)) {
6242 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6243 $charset = $useremailcharset;
6247 // Convert all the necessary strings if the charset is supported.
6248 $charsets = get_list_of_charsets();
6249 unset($charsets['UTF-8']);
6250 if (in_array($charset, $charsets)) {
6251 $mail->CharSet = $charset;
6252 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6253 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6254 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6255 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6257 foreach ($temprecipients as $key => $values) {
6258 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6260 foreach ($tempreplyto as $key => $values) {
6261 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6266 foreach ($temprecipients as $values) {
6267 $mail->addAddress($values[0], $values[1]);
6269 foreach ($tempreplyto as $values) {
6270 $mail->addReplyTo($values[0], $values[1]);
6273 if (!empty($CFG->emaildkimselector)) {
6274 $domain = substr(strrchr($mail->From, "@"), 1);
6275 $pempath = "{$CFG->dataroot}/dkim/{$domain}/{$CFG->emaildkimselector}.private";
6276 if (file_exists($pempath)) {
6277 $mail->DKIM_domain = $domain;
6278 $mail->DKIM_private = $pempath;
6279 $mail->DKIM_selector = $CFG->emaildkimselector;
6280 $mail->DKIM_identity = $mail->From;
6281 } else {
6282 debugging("Email DKIM selector chosen due to {$mail->From} but no certificate found at $pempath", DEBUG_DEVELOPER);
6286 if ($mail->send()) {
6287 set_send_count($user);
6288 if (!empty($mail->SMTPDebug)) {
6289 echo '</pre>';
6291 return true;
6292 } else {
6293 // Trigger event for failing to send email.
6294 $event = \core\event\email_failed::create(array(
6295 'context' => context_system::instance(),
6296 'userid' => $from->id,
6297 'relateduserid' => $user->id,
6298 'other' => array(
6299 'subject' => $subject,
6300 'message' => $messagetext,
6301 'errorinfo' => $mail->ErrorInfo
6304 $event->trigger();
6305 if (CLI_SCRIPT) {
6306 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6308 if (!empty($mail->SMTPDebug)) {
6309 echo '</pre>';
6311 return false;
6316 * Check to see if a user's real email address should be used for the "From" field.
6318 * @param object $from The user object for the user we are sending the email from.
6319 * @param object $user The user object that we are sending the email to.
6320 * @param array $unused No longer used.
6321 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6323 function can_send_from_real_email_address($from, $user, $unused = null) {
6324 global $CFG;
6325 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6326 return false;
6328 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6329 // Email is in the list of allowed domains for sending email,
6330 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6331 // in a course with the sender.
6332 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6333 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6334 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6335 && enrol_get_shared_courses($user, $from, false, true)))) {
6336 return true;
6338 return false;
6342 * Generate a signoff for emails based on support settings
6344 * @return string
6346 function generate_email_signoff() {
6347 global $CFG;
6349 $signoff = "\n";
6350 if (!empty($CFG->supportname)) {
6351 $signoff .= $CFG->supportname."\n";
6353 if (!empty($CFG->supportemail)) {
6354 $signoff .= $CFG->supportemail."\n";
6356 if (!empty($CFG->supportpage)) {
6357 $signoff .= $CFG->supportpage."\n";
6359 return $signoff;
6363 * Sets specified user's password and send the new password to the user via email.
6365 * @param stdClass $user A {@link $USER} object
6366 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6367 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6369 function setnew_password_and_mail($user, $fasthash = false) {
6370 global $CFG, $DB;
6372 // We try to send the mail in language the user understands,
6373 // unfortunately the filter_string() does not support alternative langs yet
6374 // so multilang will not work properly for site->fullname.
6375 $lang = empty($user->lang) ? get_newuser_language() : $user->lang;
6377 $site = get_site();
6379 $supportuser = core_user::get_support_user();
6381 $newpassword = generate_password();
6383 update_internal_user_password($user, $newpassword, $fasthash);
6385 $a = new stdClass();
6386 $a->firstname = fullname($user, true);
6387 $a->sitename = format_string($site->fullname);
6388 $a->username = $user->username;
6389 $a->newpassword = $newpassword;
6390 $a->link = $CFG->wwwroot .'/login/?lang='.$lang;
6391 $a->signoff = generate_email_signoff();
6393 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6395 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6397 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6398 return email_to_user($user, $supportuser, $subject, $message);
6403 * Resets specified user's password and send the new password to the user via email.
6405 * @param stdClass $user A {@link $USER} object
6406 * @return bool Returns true if mail was sent OK and false if there was an error.
6408 function reset_password_and_mail($user) {
6409 global $CFG;
6411 $site = get_site();
6412 $supportuser = core_user::get_support_user();
6414 $userauth = get_auth_plugin($user->auth);
6415 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6416 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6417 return false;
6420 $newpassword = generate_password();
6422 if (!$userauth->user_update_password($user, $newpassword)) {
6423 print_error("cannotsetpassword");
6426 $a = new stdClass();
6427 $a->firstname = $user->firstname;
6428 $a->lastname = $user->lastname;
6429 $a->sitename = format_string($site->fullname);
6430 $a->username = $user->username;
6431 $a->newpassword = $newpassword;
6432 $a->link = $CFG->wwwroot .'/login/change_password.php';
6433 $a->signoff = generate_email_signoff();
6435 $message = get_string('newpasswordtext', '', $a);
6437 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6439 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6441 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6442 return email_to_user($user, $supportuser, $subject, $message);
6446 * Send email to specified user with confirmation text and activation link.
6448 * @param stdClass $user A {@link $USER} object
6449 * @param string $confirmationurl user confirmation URL
6450 * @return bool Returns true if mail was sent OK and false if there was an error.
6452 function send_confirmation_email($user, $confirmationurl = null) {
6453 global $CFG;
6455 $site = get_site();
6456 $supportuser = core_user::get_support_user();
6458 $data = new stdClass();
6459 $data->sitename = format_string($site->fullname);
6460 $data->admin = generate_email_signoff();
6462 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6464 if (empty($confirmationurl)) {
6465 $confirmationurl = '/login/confirm.php';
6468 $confirmationurl = new moodle_url($confirmationurl);
6469 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6470 $confirmationurl->remove_params('data');
6471 $confirmationpath = $confirmationurl->out(false);
6473 // We need to custom encode the username to include trailing dots in the link.
6474 // Because of this custom encoding we can't use moodle_url directly.
6475 // Determine if a query string is present in the confirmation url.
6476 $hasquerystring = strpos($confirmationpath, '?') !== false;
6477 // Perform normal url encoding of the username first.
6478 $username = urlencode($user->username);
6479 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6480 $username = str_replace('.', '%2E', $username);
6482 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6484 $message = get_string('emailconfirmation', '', $data);
6485 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6487 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6488 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6492 * Sends a password change confirmation email.
6494 * @param stdClass $user A {@link $USER} object
6495 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6496 * @return bool Returns true if mail was sent OK and false if there was an error.
6498 function send_password_change_confirmation_email($user, $resetrecord) {
6499 global $CFG;
6501 $site = get_site();
6502 $supportuser = core_user::get_support_user();
6503 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6505 $data = new stdClass();
6506 $data->firstname = $user->firstname;
6507 $data->lastname = $user->lastname;
6508 $data->username = $user->username;
6509 $data->sitename = format_string($site->fullname);
6510 $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6511 $data->admin = generate_email_signoff();
6512 $data->resetminutes = $pwresetmins;
6514 $message = get_string('emailresetconfirmation', '', $data);
6515 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6517 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6518 return email_to_user($user, $supportuser, $subject, $message);
6523 * Sends an email containing information on how to change your password.
6525 * @param stdClass $user A {@link $USER} object
6526 * @return bool Returns true if mail was sent OK and false if there was an error.
6528 function send_password_change_info($user) {
6529 $site = get_site();
6530 $supportuser = core_user::get_support_user();
6532 $data = new stdClass();
6533 $data->firstname = $user->firstname;
6534 $data->lastname = $user->lastname;
6535 $data->username = $user->username;
6536 $data->sitename = format_string($site->fullname);
6537 $data->admin = generate_email_signoff();
6539 if (!is_enabled_auth($user->auth)) {
6540 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6541 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6542 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6543 return email_to_user($user, $supportuser, $subject, $message);
6546 $userauth = get_auth_plugin($user->auth);
6547 ['subject' => $subject, 'message' => $message] = $userauth->get_password_change_info($user);
6549 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6550 return email_to_user($user, $supportuser, $subject, $message);
6554 * Check that an email is allowed. It returns an error message if there was a problem.
6556 * @param string $email Content of email
6557 * @return string|false
6559 function email_is_not_allowed($email) {
6560 global $CFG;
6562 // Comparing lowercase domains.
6563 $email = strtolower($email);
6564 if (!empty($CFG->allowemailaddresses)) {
6565 $allowed = explode(' ', strtolower($CFG->allowemailaddresses));
6566 foreach ($allowed as $allowedpattern) {
6567 $allowedpattern = trim($allowedpattern);
6568 if (!$allowedpattern) {
6569 continue;
6571 if (strpos($allowedpattern, '.') === 0) {
6572 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6573 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6574 return false;
6577 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6578 return false;
6581 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6583 } else if (!empty($CFG->denyemailaddresses)) {
6584 $denied = explode(' ', strtolower($CFG->denyemailaddresses));
6585 foreach ($denied as $deniedpattern) {
6586 $deniedpattern = trim($deniedpattern);
6587 if (!$deniedpattern) {
6588 continue;
6590 if (strpos($deniedpattern, '.') === 0) {
6591 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6592 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6593 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6596 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6597 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6602 return false;
6605 // FILE HANDLING.
6608 * Returns local file storage instance
6610 * @return file_storage
6612 function get_file_storage($reset = false) {
6613 global $CFG;
6615 static $fs = null;
6617 if ($reset) {
6618 $fs = null;
6619 return;
6622 if ($fs) {
6623 return $fs;
6626 require_once("$CFG->libdir/filelib.php");
6628 $fs = new file_storage();
6630 return $fs;
6634 * Returns local file storage instance
6636 * @return file_browser
6638 function get_file_browser() {
6639 global $CFG;
6641 static $fb = null;
6643 if ($fb) {
6644 return $fb;
6647 require_once("$CFG->libdir/filelib.php");
6649 $fb = new file_browser();
6651 return $fb;
6655 * Returns file packer
6657 * @param string $mimetype default application/zip
6658 * @return file_packer
6660 function get_file_packer($mimetype='application/zip') {
6661 global $CFG;
6663 static $fp = array();
6665 if (isset($fp[$mimetype])) {
6666 return $fp[$mimetype];
6669 switch ($mimetype) {
6670 case 'application/zip':
6671 case 'application/vnd.moodle.profiling':
6672 $classname = 'zip_packer';
6673 break;
6675 case 'application/x-gzip' :
6676 $classname = 'tgz_packer';
6677 break;
6679 case 'application/vnd.moodle.backup':
6680 $classname = 'mbz_packer';
6681 break;
6683 default:
6684 return false;
6687 require_once("$CFG->libdir/filestorage/$classname.php");
6688 $fp[$mimetype] = new $classname();
6690 return $fp[$mimetype];
6694 * Returns current name of file on disk if it exists.
6696 * @param string $newfile File to be verified
6697 * @return string Current name of file on disk if true
6699 function valid_uploaded_file($newfile) {
6700 if (empty($newfile)) {
6701 return '';
6703 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6704 return $newfile['tmp_name'];
6705 } else {
6706 return '';
6711 * Returns the maximum size for uploading files.
6713 * There are seven possible upload limits:
6714 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6715 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6716 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6717 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6718 * 5. by the Moodle admin in $CFG->maxbytes
6719 * 6. by the teacher in the current course $course->maxbytes
6720 * 7. by the teacher for the current module, eg $assignment->maxbytes
6722 * These last two are passed to this function as arguments (in bytes).
6723 * Anything defined as 0 is ignored.
6724 * The smallest of all the non-zero numbers is returned.
6726 * @todo Finish documenting this function
6728 * @param int $sitebytes Set maximum size
6729 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6730 * @param int $modulebytes Current module ->maxbytes (in bytes)
6731 * @param bool $unused This parameter has been deprecated and is not used any more.
6732 * @return int The maximum size for uploading files.
6734 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6736 if (! $filesize = ini_get('upload_max_filesize')) {
6737 $filesize = '5M';
6739 $minimumsize = get_real_size($filesize);
6741 if ($postsize = ini_get('post_max_size')) {
6742 $postsize = get_real_size($postsize);
6743 if ($postsize < $minimumsize) {
6744 $minimumsize = $postsize;
6748 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6749 $minimumsize = $sitebytes;
6752 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6753 $minimumsize = $coursebytes;
6756 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6757 $minimumsize = $modulebytes;
6760 return $minimumsize;
6764 * Returns the maximum size for uploading files for the current user
6766 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6768 * @param context $context The context in which to check user capabilities
6769 * @param int $sitebytes Set maximum size
6770 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6771 * @param int $modulebytes Current module ->maxbytes (in bytes)
6772 * @param stdClass $user The user
6773 * @param bool $unused This parameter has been deprecated and is not used any more.
6774 * @return int The maximum size for uploading files.
6776 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6777 $unused = false) {
6778 global $USER;
6780 if (empty($user)) {
6781 $user = $USER;
6784 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6785 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6788 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6792 * Returns an array of possible sizes in local language
6794 * Related to {@link get_max_upload_file_size()} - this function returns an
6795 * array of possible sizes in an array, translated to the
6796 * local language.
6798 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6800 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6801 * with the value set to 0. This option will be the first in the list.
6803 * @uses SORT_NUMERIC
6804 * @param int $sitebytes Set maximum size
6805 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6806 * @param int $modulebytes Current module ->maxbytes (in bytes)
6807 * @param int|array $custombytes custom upload size/s which will be added to list,
6808 * Only value/s smaller then maxsize will be added to list.
6809 * @return array
6811 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6812 global $CFG;
6814 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6815 return array();
6818 if ($sitebytes == 0) {
6819 // Will get the minimum of upload_max_filesize or post_max_size.
6820 $sitebytes = get_max_upload_file_size();
6823 $filesize = array();
6824 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6825 5242880, 10485760, 20971520, 52428800, 104857600,
6826 262144000, 524288000, 786432000, 1073741824,
6827 2147483648, 4294967296, 8589934592);
6829 // If custombytes is given and is valid then add it to the list.
6830 if (is_number($custombytes) and $custombytes > 0) {
6831 $custombytes = (int)$custombytes;
6832 if (!in_array($custombytes, $sizelist)) {
6833 $sizelist[] = $custombytes;
6835 } else if (is_array($custombytes)) {
6836 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6839 // Allow maxbytes to be selected if it falls outside the above boundaries.
6840 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6841 // Note: get_real_size() is used in order to prevent problems with invalid values.
6842 $sizelist[] = get_real_size($CFG->maxbytes);
6845 foreach ($sizelist as $sizebytes) {
6846 if ($sizebytes < $maxsize && $sizebytes > 0) {
6847 $filesize[(string)intval($sizebytes)] = display_size($sizebytes, 0);
6851 $limitlevel = '';
6852 $displaysize = '';
6853 if ($modulebytes &&
6854 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6855 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6856 $limitlevel = get_string('activity', 'core');
6857 $displaysize = display_size($modulebytes, 0);
6858 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6860 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6861 $limitlevel = get_string('course', 'core');
6862 $displaysize = display_size($coursebytes, 0);
6863 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6865 } else if ($sitebytes) {
6866 $limitlevel = get_string('site', 'core');
6867 $displaysize = display_size($sitebytes, 0);
6868 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6871 krsort($filesize, SORT_NUMERIC);
6872 if ($limitlevel) {
6873 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6874 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6877 return $filesize;
6881 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6883 * If excludefiles is defined, then that file/directory is ignored
6884 * If getdirs is true, then (sub)directories are included in the output
6885 * If getfiles is true, then files are included in the output
6886 * (at least one of these must be true!)
6888 * @todo Finish documenting this function. Add examples of $excludefile usage.
6890 * @param string $rootdir A given root directory to start from
6891 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6892 * @param bool $descend If true then subdirectories are recursed as well
6893 * @param bool $getdirs If true then (sub)directories are included in the output
6894 * @param bool $getfiles If true then files are included in the output
6895 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6897 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6899 $dirs = array();
6901 if (!$getdirs and !$getfiles) { // Nothing to show.
6902 return $dirs;
6905 if (!is_dir($rootdir)) { // Must be a directory.
6906 return $dirs;
6909 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6910 return $dirs;
6913 if (!is_array($excludefiles)) {
6914 $excludefiles = array($excludefiles);
6917 while (false !== ($file = readdir($dir))) {
6918 $firstchar = substr($file, 0, 1);
6919 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6920 continue;
6922 $fullfile = $rootdir .'/'. $file;
6923 if (filetype($fullfile) == 'dir') {
6924 if ($getdirs) {
6925 $dirs[] = $file;
6927 if ($descend) {
6928 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6929 foreach ($subdirs as $subdir) {
6930 $dirs[] = $file .'/'. $subdir;
6933 } else if ($getfiles) {
6934 $dirs[] = $file;
6937 closedir($dir);
6939 asort($dirs);
6941 return $dirs;
6946 * Adds up all the files in a directory and works out the size.
6948 * @param string $rootdir The directory to start from
6949 * @param string $excludefile A file to exclude when summing directory size
6950 * @return int The summed size of all files and subfiles within the root directory
6952 function get_directory_size($rootdir, $excludefile='') {
6953 global $CFG;
6955 // Do it this way if we can, it's much faster.
6956 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6957 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6958 $output = null;
6959 $return = null;
6960 exec($command, $output, $return);
6961 if (is_array($output)) {
6962 // We told it to return k.
6963 return get_real_size(intval($output[0]).'k');
6967 if (!is_dir($rootdir)) {
6968 // Must be a directory.
6969 return 0;
6972 if (!$dir = @opendir($rootdir)) {
6973 // Can't open it for some reason.
6974 return 0;
6977 $size = 0;
6979 while (false !== ($file = readdir($dir))) {
6980 $firstchar = substr($file, 0, 1);
6981 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6982 continue;
6984 $fullfile = $rootdir .'/'. $file;
6985 if (filetype($fullfile) == 'dir') {
6986 $size += get_directory_size($fullfile, $excludefile);
6987 } else {
6988 $size += filesize($fullfile);
6991 closedir($dir);
6993 return $size;
6997 * Converts bytes into display form
6999 * @param int $size The size to convert to human readable form
7000 * @param int $decimalplaces If specified, uses fixed number of decimal places
7001 * @param string $fixedunits If specified, uses fixed units (e.g. 'KB')
7002 * @return string Display version of size
7004 function display_size($size, int $decimalplaces = 1, string $fixedunits = ''): string {
7006 static $units;
7008 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
7009 return get_string('unlimited');
7012 if (empty($units)) {
7013 $units[] = get_string('sizeb');
7014 $units[] = get_string('sizekb');
7015 $units[] = get_string('sizemb');
7016 $units[] = get_string('sizegb');
7017 $units[] = get_string('sizetb');
7018 $units[] = get_string('sizepb');
7021 switch ($fixedunits) {
7022 case 'PB' :
7023 $magnitude = 5;
7024 break;
7025 case 'TB' :
7026 $magnitude = 4;
7027 break;
7028 case 'GB' :
7029 $magnitude = 3;
7030 break;
7031 case 'MB' :
7032 $magnitude = 2;
7033 break;
7034 case 'KB' :
7035 $magnitude = 1;
7036 break;
7037 case 'B' :
7038 $magnitude = 0;
7039 break;
7040 case '':
7041 $magnitude = floor(log($size, 1024));
7042 $magnitude = max(0, min(5, $magnitude));
7043 break;
7044 default:
7045 throw new coding_exception('Unknown fixed units value: ' . $fixedunits);
7048 // Special case for magnitude 0 (bytes) - never use decimal places.
7049 $nbsp = "\xc2\xa0";
7050 if ($magnitude === 0) {
7051 return round($size) . $nbsp . $units[$magnitude];
7054 // Convert to specified units.
7055 $sizeinunit = $size / 1024 ** $magnitude;
7057 // Fixed decimal places.
7058 return sprintf('%.' . $decimalplaces . 'f', $sizeinunit) . $nbsp . $units[$magnitude];
7062 * Cleans a given filename by removing suspicious or troublesome characters
7064 * @see clean_param()
7065 * @param string $string file name
7066 * @return string cleaned file name
7068 function clean_filename($string) {
7069 return clean_param($string, PARAM_FILE);
7072 // STRING TRANSLATION.
7075 * Returns the code for the current language
7077 * @category string
7078 * @return string
7080 function current_language() {
7081 global $CFG, $USER, $SESSION, $COURSE;
7083 if (!empty($SESSION->forcelang)) {
7084 // Allows overriding course-forced language (useful for admins to check
7085 // issues in courses whose language they don't understand).
7086 // Also used by some code to temporarily get language-related information in a
7087 // specific language (see force_current_language()).
7088 $return = $SESSION->forcelang;
7090 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
7091 // Course language can override all other settings for this page.
7092 $return = $COURSE->lang;
7094 } else if (!empty($SESSION->lang)) {
7095 // Session language can override other settings.
7096 $return = $SESSION->lang;
7098 } else if (!empty($USER->lang)) {
7099 $return = $USER->lang;
7101 } else if (isset($CFG->lang)) {
7102 $return = $CFG->lang;
7104 } else {
7105 $return = 'en';
7108 // Just in case this slipped in from somewhere by accident.
7109 $return = str_replace('_utf8', '', $return);
7111 return $return;
7115 * Returns parent language of current active language if defined
7117 * @category string
7118 * @param string $lang null means current language
7119 * @return string
7121 function get_parent_language($lang=null) {
7123 $parentlang = get_string_manager()->get_string('parentlanguage', 'langconfig', null, $lang);
7125 if ($parentlang === 'en') {
7126 $parentlang = '';
7129 return $parentlang;
7133 * Force the current language to get strings and dates localised in the given language.
7135 * After calling this function, all strings will be provided in the given language
7136 * until this function is called again, or equivalent code is run.
7138 * @param string $language
7139 * @return string previous $SESSION->forcelang value
7141 function force_current_language($language) {
7142 global $SESSION;
7143 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
7144 if ($language !== $sessionforcelang) {
7145 // Seting forcelang to null or an empty string disables it's effect.
7146 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
7147 $SESSION->forcelang = $language;
7148 moodle_setlocale();
7151 return $sessionforcelang;
7155 * Returns current string_manager instance.
7157 * The param $forcereload is needed for CLI installer only where the string_manager instance
7158 * must be replaced during the install.php script life time.
7160 * @category string
7161 * @param bool $forcereload shall the singleton be released and new instance created instead?
7162 * @return core_string_manager
7164 function get_string_manager($forcereload=false) {
7165 global $CFG;
7167 static $singleton = null;
7169 if ($forcereload) {
7170 $singleton = null;
7172 if ($singleton === null) {
7173 if (empty($CFG->early_install_lang)) {
7175 $transaliases = array();
7176 if (empty($CFG->langlist)) {
7177 $translist = array();
7178 } else {
7179 $translist = explode(',', $CFG->langlist);
7180 $translist = array_map('trim', $translist);
7181 // Each language in the $CFG->langlist can has an "alias" that would substitute the default language name.
7182 foreach ($translist as $i => $value) {
7183 $parts = preg_split('/\s*\|\s*/', $value, 2);
7184 if (count($parts) == 2) {
7185 $transaliases[$parts[0]] = $parts[1];
7186 $translist[$i] = $parts[0];
7191 if (!empty($CFG->config_php_settings['customstringmanager'])) {
7192 $classname = $CFG->config_php_settings['customstringmanager'];
7194 if (class_exists($classname)) {
7195 $implements = class_implements($classname);
7197 if (isset($implements['core_string_manager'])) {
7198 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7199 return $singleton;
7201 } else {
7202 debugging('Unable to instantiate custom string manager: class '.$classname.
7203 ' does not implement the core_string_manager interface.');
7206 } else {
7207 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7211 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7213 } else {
7214 $singleton = new core_string_manager_install();
7218 return $singleton;
7222 * Returns a localized string.
7224 * Returns the translated string specified by $identifier as
7225 * for $module. Uses the same format files as STphp.
7226 * $a is an object, string or number that can be used
7227 * within translation strings
7229 * eg 'hello {$a->firstname} {$a->lastname}'
7230 * or 'hello {$a}'
7232 * If you would like to directly echo the localized string use
7233 * the function {@link print_string()}
7235 * Example usage of this function involves finding the string you would
7236 * like a local equivalent of and using its identifier and module information
7237 * to retrieve it.<br/>
7238 * If you open moodle/lang/en/moodle.php and look near line 278
7239 * you will find a string to prompt a user for their word for 'course'
7240 * <code>
7241 * $string['course'] = 'Course';
7242 * </code>
7243 * So if you want to display the string 'Course'
7244 * in any language that supports it on your site
7245 * you just need to use the identifier 'course'
7246 * <code>
7247 * $mystring = '<strong>'. get_string('course') .'</strong>';
7248 * or
7249 * </code>
7250 * If the string you want is in another file you'd take a slightly
7251 * different approach. Looking in moodle/lang/en/calendar.php you find
7252 * around line 75:
7253 * <code>
7254 * $string['typecourse'] = 'Course event';
7255 * </code>
7256 * If you want to display the string "Course event" in any language
7257 * supported you would use the identifier 'typecourse' and the module 'calendar'
7258 * (because it is in the file calendar.php):
7259 * <code>
7260 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7261 * </code>
7263 * As a last resort, should the identifier fail to map to a string
7264 * the returned string will be [[ $identifier ]]
7266 * In Moodle 2.3 there is a new argument to this function $lazyload.
7267 * Setting $lazyload to true causes get_string to return a lang_string object
7268 * rather than the string itself. The fetching of the string is then put off until
7269 * the string object is first used. The object can be used by calling it's out
7270 * method or by casting the object to a string, either directly e.g.
7271 * (string)$stringobject
7272 * or indirectly by using the string within another string or echoing it out e.g.
7273 * echo $stringobject
7274 * return "<p>{$stringobject}</p>";
7275 * It is worth noting that using $lazyload and attempting to use the string as an
7276 * array key will cause a fatal error as objects cannot be used as array keys.
7277 * But you should never do that anyway!
7278 * For more information {@link lang_string}
7280 * @category string
7281 * @param string $identifier The key identifier for the localized string
7282 * @param string $component The module where the key identifier is stored,
7283 * usually expressed as the filename in the language pack without the
7284 * .php on the end but can also be written as mod/forum or grade/export/xls.
7285 * If none is specified then moodle.php is used.
7286 * @param string|object|array $a An object, string or number that can be used
7287 * within translation strings
7288 * @param bool $lazyload If set to true a string object is returned instead of
7289 * the string itself. The string then isn't calculated until it is first used.
7290 * @return string The localized string.
7291 * @throws coding_exception
7293 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7294 global $CFG;
7296 // If the lazy load argument has been supplied return a lang_string object
7297 // instead.
7298 // We need to make sure it is true (and a bool) as you will see below there
7299 // used to be a forth argument at one point.
7300 if ($lazyload === true) {
7301 return new lang_string($identifier, $component, $a);
7304 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7305 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7308 // There is now a forth argument again, this time it is a boolean however so
7309 // we can still check for the old extralocations parameter.
7310 if (!is_bool($lazyload) && !empty($lazyload)) {
7311 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7314 if (strpos($component, '/') !== false) {
7315 debugging('The module name you passed to get_string is the deprecated format ' .
7316 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7317 $componentpath = explode('/', $component);
7319 switch ($componentpath[0]) {
7320 case 'mod':
7321 $component = $componentpath[1];
7322 break;
7323 case 'blocks':
7324 case 'block':
7325 $component = 'block_'.$componentpath[1];
7326 break;
7327 case 'enrol':
7328 $component = 'enrol_'.$componentpath[1];
7329 break;
7330 case 'format':
7331 $component = 'format_'.$componentpath[1];
7332 break;
7333 case 'grade':
7334 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7335 break;
7339 $result = get_string_manager()->get_string($identifier, $component, $a);
7341 // Debugging feature lets you display string identifier and component.
7342 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7343 $result .= ' {' . $identifier . '/' . $component . '}';
7345 return $result;
7349 * Converts an array of strings to their localized value.
7351 * @param array $array An array of strings
7352 * @param string $component The language module that these strings can be found in.
7353 * @return stdClass translated strings.
7355 function get_strings($array, $component = '') {
7356 $string = new stdClass;
7357 foreach ($array as $item) {
7358 $string->$item = get_string($item, $component);
7360 return $string;
7364 * Prints out a translated string.
7366 * Prints out a translated string using the return value from the {@link get_string()} function.
7368 * Example usage of this function when the string is in the moodle.php file:<br/>
7369 * <code>
7370 * echo '<strong>';
7371 * print_string('course');
7372 * echo '</strong>';
7373 * </code>
7375 * Example usage of this function when the string is not in the moodle.php file:<br/>
7376 * <code>
7377 * echo '<h1>';
7378 * print_string('typecourse', 'calendar');
7379 * echo '</h1>';
7380 * </code>
7382 * @category string
7383 * @param string $identifier The key identifier for the localized string
7384 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7385 * @param string|object|array $a An object, string or number that can be used within translation strings
7387 function print_string($identifier, $component = '', $a = null) {
7388 echo get_string($identifier, $component, $a);
7392 * Returns a list of charset codes
7394 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7395 * (checking that such charset is supported by the texlib library!)
7397 * @return array And associative array with contents in the form of charset => charset
7399 function get_list_of_charsets() {
7401 $charsets = array(
7402 'EUC-JP' => 'EUC-JP',
7403 'ISO-2022-JP'=> 'ISO-2022-JP',
7404 'ISO-8859-1' => 'ISO-8859-1',
7405 'SHIFT-JIS' => 'SHIFT-JIS',
7406 'GB2312' => 'GB2312',
7407 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7408 'UTF-8' => 'UTF-8');
7410 asort($charsets);
7412 return $charsets;
7416 * Returns a list of valid and compatible themes
7418 * @return array
7420 function get_list_of_themes() {
7421 global $CFG;
7423 $themes = array();
7425 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7426 $themelist = explode(',', $CFG->themelist);
7427 } else {
7428 $themelist = array_keys(core_component::get_plugin_list("theme"));
7431 foreach ($themelist as $key => $themename) {
7432 $theme = theme_config::load($themename);
7433 $themes[$themename] = $theme;
7436 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7438 return $themes;
7442 * Factory function for emoticon_manager
7444 * @return emoticon_manager singleton
7446 function get_emoticon_manager() {
7447 static $singleton = null;
7449 if (is_null($singleton)) {
7450 $singleton = new emoticon_manager();
7453 return $singleton;
7457 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7459 * Whenever this manager mentiones 'emoticon object', the following data
7460 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7461 * altidentifier and altcomponent
7463 * @see admin_setting_emoticons
7465 * @copyright 2010 David Mudrak
7466 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7468 class emoticon_manager {
7471 * Returns the currently enabled emoticons
7473 * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
7474 * @return array of emoticon objects
7476 public function get_emoticons($selectable = false) {
7477 global $CFG;
7478 $notselectable = ['martin', 'egg'];
7480 if (empty($CFG->emoticons)) {
7481 return array();
7484 $emoticons = $this->decode_stored_config($CFG->emoticons);
7486 if (!is_array($emoticons)) {
7487 // Something is wrong with the format of stored setting.
7488 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7489 return array();
7491 if ($selectable) {
7492 foreach ($emoticons as $index => $emote) {
7493 if (in_array($emote->altidentifier, $notselectable)) {
7494 // Skip this one.
7495 unset($emoticons[$index]);
7500 return $emoticons;
7504 * Converts emoticon object into renderable pix_emoticon object
7506 * @param stdClass $emoticon emoticon object
7507 * @param array $attributes explicit HTML attributes to set
7508 * @return pix_emoticon
7510 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7511 $stringmanager = get_string_manager();
7512 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7513 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7514 } else {
7515 $alt = s($emoticon->text);
7517 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7521 * Encodes the array of emoticon objects into a string storable in config table
7523 * @see self::decode_stored_config()
7524 * @param array $emoticons array of emtocion objects
7525 * @return string
7527 public function encode_stored_config(array $emoticons) {
7528 return json_encode($emoticons);
7532 * Decodes the string into an array of emoticon objects
7534 * @see self::encode_stored_config()
7535 * @param string $encoded
7536 * @return string|null
7538 public function decode_stored_config($encoded) {
7539 $decoded = json_decode($encoded);
7540 if (!is_array($decoded)) {
7541 return null;
7543 return $decoded;
7547 * Returns default set of emoticons supported by Moodle
7549 * @return array of sdtClasses
7551 public function default_emoticons() {
7552 return array(
7553 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7554 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7555 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7556 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7557 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7558 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7559 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7560 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7561 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7562 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7563 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7564 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7565 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7566 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7567 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7568 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7569 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7570 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7571 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7572 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7573 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7574 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7575 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7576 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7577 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7578 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7579 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7580 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7581 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7582 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7587 * Helper method preparing the stdClass with the emoticon properties
7589 * @param string|array $text or array of strings
7590 * @param string $imagename to be used by {@link pix_emoticon}
7591 * @param string $altidentifier alternative string identifier, null for no alt
7592 * @param string $altcomponent where the alternative string is defined
7593 * @param string $imagecomponent to be used by {@link pix_emoticon}
7594 * @return stdClass
7596 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7597 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7598 return (object)array(
7599 'text' => $text,
7600 'imagename' => $imagename,
7601 'imagecomponent' => $imagecomponent,
7602 'altidentifier' => $altidentifier,
7603 'altcomponent' => $altcomponent,
7608 // ENCRYPTION.
7611 * rc4encrypt
7613 * @param string $data Data to encrypt.
7614 * @return string The now encrypted data.
7616 function rc4encrypt($data) {
7617 return endecrypt(get_site_identifier(), $data, '');
7621 * rc4decrypt
7623 * @param string $data Data to decrypt.
7624 * @return string The now decrypted data.
7626 function rc4decrypt($data) {
7627 return endecrypt(get_site_identifier(), $data, 'de');
7631 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7633 * @todo Finish documenting this function
7635 * @param string $pwd The password to use when encrypting or decrypting
7636 * @param string $data The data to be decrypted/encrypted
7637 * @param string $case Either 'de' for decrypt or '' for encrypt
7638 * @return string
7640 function endecrypt ($pwd, $data, $case) {
7642 if ($case == 'de') {
7643 $data = urldecode($data);
7646 $key[] = '';
7647 $box[] = '';
7648 $pwdlength = strlen($pwd);
7650 for ($i = 0; $i <= 255; $i++) {
7651 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7652 $box[$i] = $i;
7655 $x = 0;
7657 for ($i = 0; $i <= 255; $i++) {
7658 $x = ($x + $box[$i] + $key[$i]) % 256;
7659 $tempswap = $box[$i];
7660 $box[$i] = $box[$x];
7661 $box[$x] = $tempswap;
7664 $cipher = '';
7666 $a = 0;
7667 $j = 0;
7669 for ($i = 0; $i < strlen($data); $i++) {
7670 $a = ($a + 1) % 256;
7671 $j = ($j + $box[$a]) % 256;
7672 $temp = $box[$a];
7673 $box[$a] = $box[$j];
7674 $box[$j] = $temp;
7675 $k = $box[(($box[$a] + $box[$j]) % 256)];
7676 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7677 $cipher .= chr($cipherby);
7680 if ($case == 'de') {
7681 $cipher = urldecode(urlencode($cipher));
7682 } else {
7683 $cipher = urlencode($cipher);
7686 return $cipher;
7689 // ENVIRONMENT CHECKING.
7692 * This method validates a plug name. It is much faster than calling clean_param.
7694 * @param string $name a string that might be a plugin name.
7695 * @return bool if this string is a valid plugin name.
7697 function is_valid_plugin_name($name) {
7698 // This does not work for 'mod', bad luck, use any other type.
7699 return core_component::is_valid_plugin_name('tool', $name);
7703 * Get a list of all the plugins of a given type that define a certain API function
7704 * in a certain file. The plugin component names and function names are returned.
7706 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7707 * @param string $function the part of the name of the function after the
7708 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7709 * names like report_courselist_hook.
7710 * @param string $file the name of file within the plugin that defines the
7711 * function. Defaults to lib.php.
7712 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7713 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7715 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7716 global $CFG;
7718 // We don't include here as all plugin types files would be included.
7719 $plugins = get_plugins_with_function($function, $file, false);
7721 if (empty($plugins[$plugintype])) {
7722 return array();
7725 $allplugins = core_component::get_plugin_list($plugintype);
7727 // Reformat the array and include the files.
7728 $pluginfunctions = array();
7729 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7731 // Check that it has not been removed and the file is still available.
7732 if (!empty($allplugins[$pluginname])) {
7734 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7735 if (file_exists($filepath)) {
7736 include_once($filepath);
7738 // Now that the file is loaded, we must verify the function still exists.
7739 if (function_exists($functionname)) {
7740 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7741 } else {
7742 // Invalidate the cache for next run.
7743 \cache_helper::invalidate_by_definition('core', 'plugin_functions');
7749 return $pluginfunctions;
7753 * Get a list of all the plugins that define a certain API function in a certain file.
7755 * @param string $function the part of the name of the function after the
7756 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7757 * names like report_courselist_hook.
7758 * @param string $file the name of file within the plugin that defines the
7759 * function. Defaults to lib.php.
7760 * @param bool $include Whether to include the files that contain the functions or not.
7761 * @return array with [plugintype][plugin] = functionname
7763 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7764 global $CFG;
7766 if (during_initial_install() || isset($CFG->upgraderunning)) {
7767 // API functions _must not_ be called during an installation or upgrade.
7768 return [];
7771 $cache = \cache::make('core', 'plugin_functions');
7773 // Including both although I doubt that we will find two functions definitions with the same name.
7774 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7775 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7776 $pluginfunctions = $cache->get($key);
7777 $dirty = false;
7779 // Use the plugin manager to check that plugins are currently installed.
7780 $pluginmanager = \core_plugin_manager::instance();
7782 if ($pluginfunctions !== false) {
7784 // Checking that the files are still available.
7785 foreach ($pluginfunctions as $plugintype => $plugins) {
7787 $allplugins = \core_component::get_plugin_list($plugintype);
7788 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7789 foreach ($plugins as $plugin => $function) {
7790 if (!isset($installedplugins[$plugin])) {
7791 // Plugin code is still present on disk but it is not installed.
7792 $dirty = true;
7793 break 2;
7796 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7797 if (empty($allplugins[$plugin])) {
7798 $dirty = true;
7799 break 2;
7802 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7803 if ($include && $fileexists) {
7804 // Include the files if it was requested.
7805 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7806 } else if (!$fileexists) {
7807 // If the file is not available any more it should not be returned.
7808 $dirty = true;
7809 break 2;
7812 // Check if the function still exists in the file.
7813 if ($include && !function_exists($function)) {
7814 $dirty = true;
7815 break 2;
7820 // If the cache is dirty, we should fall through and let it rebuild.
7821 if (!$dirty) {
7822 return $pluginfunctions;
7826 $pluginfunctions = array();
7828 // To fill the cached. Also, everything should continue working with cache disabled.
7829 $plugintypes = \core_component::get_plugin_types();
7830 foreach ($plugintypes as $plugintype => $unused) {
7832 // We need to include files here.
7833 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7834 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7835 foreach ($pluginswithfile as $plugin => $notused) {
7837 if (!isset($installedplugins[$plugin])) {
7838 continue;
7841 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7843 $pluginfunction = false;
7844 if (function_exists($fullfunction)) {
7845 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7846 $pluginfunction = $fullfunction;
7848 } else if ($plugintype === 'mod') {
7849 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7850 $shortfunction = $plugin . '_' . $function;
7851 if (function_exists($shortfunction)) {
7852 $pluginfunction = $shortfunction;
7856 if ($pluginfunction) {
7857 if (empty($pluginfunctions[$plugintype])) {
7858 $pluginfunctions[$plugintype] = array();
7860 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7865 $cache->set($key, $pluginfunctions);
7867 return $pluginfunctions;
7872 * Lists plugin-like directories within specified directory
7874 * This function was originally used for standard Moodle plugins, please use
7875 * new core_component::get_plugin_list() now.
7877 * This function is used for general directory listing and backwards compatility.
7879 * @param string $directory relative directory from root
7880 * @param string $exclude dir name to exclude from the list (defaults to none)
7881 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7882 * @return array Sorted array of directory names found under the requested parameters
7884 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7885 global $CFG;
7887 $plugins = array();
7889 if (empty($basedir)) {
7890 $basedir = $CFG->dirroot .'/'. $directory;
7892 } else {
7893 $basedir = $basedir .'/'. $directory;
7896 if ($CFG->debugdeveloper and empty($exclude)) {
7897 // Make sure devs do not use this to list normal plugins,
7898 // this is intended for general directories that are not plugins!
7900 $subtypes = core_component::get_plugin_types();
7901 if (in_array($basedir, $subtypes)) {
7902 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7904 unset($subtypes);
7907 $ignorelist = array_flip(array_filter([
7908 'CVS',
7909 '_vti_cnf',
7910 'amd',
7911 'classes',
7912 'simpletest',
7913 'tests',
7914 'templates',
7915 'yui',
7916 $exclude,
7917 ]));
7919 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7920 if (!$dirhandle = opendir($basedir)) {
7921 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7922 return array();
7924 while (false !== ($dir = readdir($dirhandle))) {
7925 if (strpos($dir, '.') === 0) {
7926 // Ignore directories starting with .
7927 // These are treated as hidden directories.
7928 continue;
7930 if (array_key_exists($dir, $ignorelist)) {
7931 // This directory features on the ignore list.
7932 continue;
7934 if (filetype($basedir .'/'. $dir) != 'dir') {
7935 continue;
7937 $plugins[] = $dir;
7939 closedir($dirhandle);
7941 if ($plugins) {
7942 asort($plugins);
7944 return $plugins;
7948 * Invoke plugin's callback functions
7950 * @param string $type plugin type e.g. 'mod'
7951 * @param string $name plugin name
7952 * @param string $feature feature name
7953 * @param string $action feature's action
7954 * @param array $params parameters of callback function, should be an array
7955 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7956 * @return mixed
7958 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7960 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7961 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7965 * Invoke component's callback functions
7967 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7968 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7969 * @param array $params parameters of callback function
7970 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7971 * @return mixed
7973 function component_callback($component, $function, array $params = array(), $default = null) {
7975 $functionname = component_callback_exists($component, $function);
7977 if ($params && (array_keys($params) !== range(0, count($params) - 1))) {
7978 // PHP 8 allows to have associative arrays in the call_user_func_array() parameters but
7979 // PHP 7 does not. Using associative arrays can result in different behavior in different PHP versions.
7980 // See https://php.watch/versions/8.0/named-parameters#named-params-call_user_func_array
7981 // This check can be removed when minimum PHP version for Moodle is raised to 8.
7982 debugging('Parameters array can not be an associative array while Moodle supports both PHP 7 and PHP 8.',
7983 DEBUG_DEVELOPER);
7984 $params = array_values($params);
7987 if ($functionname) {
7988 // Function exists, so just return function result.
7989 $ret = call_user_func_array($functionname, $params);
7990 if (is_null($ret)) {
7991 return $default;
7992 } else {
7993 return $ret;
7996 return $default;
8000 * Determine if a component callback exists and return the function name to call. Note that this
8001 * function will include the required library files so that the functioname returned can be
8002 * called directly.
8004 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
8005 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
8006 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
8007 * @throws coding_exception if invalid component specfied
8009 function component_callback_exists($component, $function) {
8010 global $CFG; // This is needed for the inclusions.
8012 $cleancomponent = clean_param($component, PARAM_COMPONENT);
8013 if (empty($cleancomponent)) {
8014 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8016 $component = $cleancomponent;
8018 list($type, $name) = core_component::normalize_component($component);
8019 $component = $type . '_' . $name;
8021 $oldfunction = $name.'_'.$function;
8022 $function = $component.'_'.$function;
8024 $dir = core_component::get_component_directory($component);
8025 if (empty($dir)) {
8026 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8029 // Load library and look for function.
8030 if (file_exists($dir.'/lib.php')) {
8031 require_once($dir.'/lib.php');
8034 if (!function_exists($function) and function_exists($oldfunction)) {
8035 if ($type !== 'mod' and $type !== 'core') {
8036 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
8038 $function = $oldfunction;
8041 if (function_exists($function)) {
8042 return $function;
8044 return false;
8048 * Call the specified callback method on the provided class.
8050 * If the callback returns null, then the default value is returned instead.
8051 * If the class does not exist, then the default value is returned.
8053 * @param string $classname The name of the class to call upon.
8054 * @param string $methodname The name of the staticically defined method on the class.
8055 * @param array $params The arguments to pass into the method.
8056 * @param mixed $default The default value.
8057 * @return mixed The return value.
8059 function component_class_callback($classname, $methodname, array $params, $default = null) {
8060 if (!class_exists($classname)) {
8061 return $default;
8064 if (!method_exists($classname, $methodname)) {
8065 return $default;
8068 $fullfunction = $classname . '::' . $methodname;
8069 $result = call_user_func_array($fullfunction, $params);
8071 if (null === $result) {
8072 return $default;
8073 } else {
8074 return $result;
8079 * Checks whether a plugin supports a specified feature.
8081 * @param string $type Plugin type e.g. 'mod'
8082 * @param string $name Plugin name e.g. 'forum'
8083 * @param string $feature Feature code (FEATURE_xx constant)
8084 * @param mixed $default default value if feature support unknown
8085 * @return mixed Feature result (false if not supported, null if feature is unknown,
8086 * otherwise usually true but may have other feature-specific value such as array)
8087 * @throws coding_exception
8089 function plugin_supports($type, $name, $feature, $default = null) {
8090 global $CFG;
8092 if ($type === 'mod' and $name === 'NEWMODULE') {
8093 // Somebody forgot to rename the module template.
8094 return false;
8097 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
8098 if (empty($component)) {
8099 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8102 $function = null;
8104 if ($type === 'mod') {
8105 // We need this special case because we support subplugins in modules,
8106 // otherwise it would end up in infinite loop.
8107 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8108 include_once("$CFG->dirroot/mod/$name/lib.php");
8109 $function = $component.'_supports';
8110 if (!function_exists($function)) {
8111 // Legacy non-frankenstyle function name.
8112 $function = $name.'_supports';
8116 } else {
8117 if (!$path = core_component::get_plugin_directory($type, $name)) {
8118 // Non existent plugin type.
8119 return false;
8121 if (file_exists("$path/lib.php")) {
8122 include_once("$path/lib.php");
8123 $function = $component.'_supports';
8127 if ($function and function_exists($function)) {
8128 $supports = $function($feature);
8129 if (is_null($supports)) {
8130 // Plugin does not know - use default.
8131 return $default;
8132 } else {
8133 return $supports;
8137 // Plugin does not care, so use default.
8138 return $default;
8142 * Returns true if the current version of PHP is greater that the specified one.
8144 * @todo Check PHP version being required here is it too low?
8146 * @param string $version The version of php being tested.
8147 * @return bool
8149 function check_php_version($version='5.2.4') {
8150 return (version_compare(phpversion(), $version) >= 0);
8154 * Determine if moodle installation requires update.
8156 * Checks version numbers of main code and all plugins to see
8157 * if there are any mismatches.
8159 * @return bool
8161 function moodle_needs_upgrading() {
8162 global $CFG;
8164 if (empty($CFG->version)) {
8165 return true;
8168 // There is no need to purge plugininfo caches here because
8169 // these caches are not used during upgrade and they are purged after
8170 // every upgrade.
8172 if (empty($CFG->allversionshash)) {
8173 return true;
8176 $hash = core_component::get_all_versions_hash();
8178 return ($hash !== $CFG->allversionshash);
8182 * Returns the major version of this site
8184 * Moodle version numbers consist of three numbers separated by a dot, for
8185 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
8186 * called major version. This function extracts the major version from either
8187 * $CFG->release (default) or eventually from the $release variable defined in
8188 * the main version.php.
8190 * @param bool $fromdisk should the version if source code files be used
8191 * @return string|false the major version like '2.3', false if could not be determined
8193 function moodle_major_version($fromdisk = false) {
8194 global $CFG;
8196 if ($fromdisk) {
8197 $release = null;
8198 require($CFG->dirroot.'/version.php');
8199 if (empty($release)) {
8200 return false;
8203 } else {
8204 if (empty($CFG->release)) {
8205 return false;
8207 $release = $CFG->release;
8210 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8211 return $matches[0];
8212 } else {
8213 return false;
8217 // MISCELLANEOUS.
8220 * Gets the system locale
8222 * @return string Retuns the current locale.
8224 function moodle_getlocale() {
8225 global $CFG;
8227 // Fetch the correct locale based on ostype.
8228 if ($CFG->ostype == 'WINDOWS') {
8229 $stringtofetch = 'localewin';
8230 } else {
8231 $stringtofetch = 'locale';
8234 if (!empty($CFG->locale)) { // Override locale for all language packs.
8235 return $CFG->locale;
8238 return get_string($stringtofetch, 'langconfig');
8242 * Sets the system locale
8244 * @category string
8245 * @param string $locale Can be used to force a locale
8247 function moodle_setlocale($locale='') {
8248 global $CFG;
8250 static $currentlocale = ''; // Last locale caching.
8252 $oldlocale = $currentlocale;
8254 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8255 if (!empty($locale)) {
8256 $currentlocale = $locale;
8257 } else {
8258 $currentlocale = moodle_getlocale();
8261 // Do nothing if locale already set up.
8262 if ($oldlocale == $currentlocale) {
8263 return;
8266 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8267 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8268 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8270 // Get current values.
8271 $monetary= setlocale (LC_MONETARY, 0);
8272 $numeric = setlocale (LC_NUMERIC, 0);
8273 $ctype = setlocale (LC_CTYPE, 0);
8274 if ($CFG->ostype != 'WINDOWS') {
8275 $messages= setlocale (LC_MESSAGES, 0);
8277 // Set locale to all.
8278 $result = setlocale (LC_ALL, $currentlocale);
8279 // If setting of locale fails try the other utf8 or utf-8 variant,
8280 // some operating systems support both (Debian), others just one (OSX).
8281 if ($result === false) {
8282 if (stripos($currentlocale, '.UTF-8') !== false) {
8283 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8284 setlocale (LC_ALL, $newlocale);
8285 } else if (stripos($currentlocale, '.UTF8') !== false) {
8286 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8287 setlocale (LC_ALL, $newlocale);
8290 // Set old values.
8291 setlocale (LC_MONETARY, $monetary);
8292 setlocale (LC_NUMERIC, $numeric);
8293 if ($CFG->ostype != 'WINDOWS') {
8294 setlocale (LC_MESSAGES, $messages);
8296 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8297 // To workaround a well-known PHP problem with Turkish letter Ii.
8298 setlocale (LC_CTYPE, $ctype);
8303 * Count words in a string.
8305 * Words are defined as things between whitespace.
8307 * @category string
8308 * @param string $string The text to be searched for words. May be HTML.
8309 * @return int The count of words in the specified string
8311 function count_words($string) {
8312 // Before stripping tags, add a space after the close tag of anything that is not obviously inline.
8313 // Also, br is a special case because it definitely delimits a word, but has no close tag.
8314 $string = preg_replace('~
8315 ( # Capture the tag we match.
8316 </ # Start of close tag.
8317 (?! # Do not match any of these specific close tag names.
8318 a> | b> | del> | em> | i> |
8319 ins> | s> | small> |
8320 strong> | sub> | sup> | u>
8322 \w+ # But, apart from those execptions, match any tag name.
8323 > # End of close tag.
8325 <br> | <br\s*/> # Special cases that are not close tags.
8327 ~x', '$1 ', $string); // Add a space after the close tag.
8328 // Now remove HTML tags.
8329 $string = strip_tags($string);
8330 // Decode HTML entities.
8331 $string = html_entity_decode($string);
8333 // Now, the word count is the number of blocks of characters separated
8334 // by any sort of space. That seems to be the definition used by all other systems.
8335 // To be precise about what is considered to separate words:
8336 // * Anything that Unicode considers a 'Separator'
8337 // * Anything that Unicode considers a 'Control character'
8338 // * An em- or en- dash.
8339 return count(preg_split('~[\p{Z}\p{Cc}—–]+~u', $string, -1, PREG_SPLIT_NO_EMPTY));
8343 * Count letters in a string.
8345 * Letters are defined as chars not in tags and different from whitespace.
8347 * @category string
8348 * @param string $string The text to be searched for letters. May be HTML.
8349 * @return int The count of letters in the specified text.
8351 function count_letters($string) {
8352 $string = strip_tags($string); // Tags are out now.
8353 $string = html_entity_decode($string);
8354 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8356 return core_text::strlen($string);
8360 * Generate and return a random string of the specified length.
8362 * @param int $length The length of the string to be created.
8363 * @return string
8365 function random_string($length=15) {
8366 $randombytes = random_bytes_emulate($length);
8367 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8368 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8369 $pool .= '0123456789';
8370 $poollen = strlen($pool);
8371 $string = '';
8372 for ($i = 0; $i < $length; $i++) {
8373 $rand = ord($randombytes[$i]);
8374 $string .= substr($pool, ($rand%($poollen)), 1);
8376 return $string;
8380 * Generate a complex random string (useful for md5 salts)
8382 * This function is based on the above {@link random_string()} however it uses a
8383 * larger pool of characters and generates a string between 24 and 32 characters
8385 * @param int $length Optional if set generates a string to exactly this length
8386 * @return string
8388 function complex_random_string($length=null) {
8389 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8390 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8391 $poollen = strlen($pool);
8392 if ($length===null) {
8393 $length = floor(rand(24, 32));
8395 $randombytes = random_bytes_emulate($length);
8396 $string = '';
8397 for ($i = 0; $i < $length; $i++) {
8398 $rand = ord($randombytes[$i]);
8399 $string .= $pool[($rand%$poollen)];
8401 return $string;
8405 * Try to generates cryptographically secure pseudo-random bytes.
8407 * Note this is achieved by fallbacking between:
8408 * - PHP 7 random_bytes().
8409 * - OpenSSL openssl_random_pseudo_bytes().
8410 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8412 * @param int $length requested length in bytes
8413 * @return string binary data
8415 function random_bytes_emulate($length) {
8416 global $CFG;
8417 if ($length <= 0) {
8418 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8419 return '';
8421 if (function_exists('random_bytes')) {
8422 // Use PHP 7 goodness.
8423 $hash = @random_bytes($length);
8424 if ($hash !== false) {
8425 return $hash;
8428 if (function_exists('openssl_random_pseudo_bytes')) {
8429 // If you have the openssl extension enabled.
8430 $hash = openssl_random_pseudo_bytes($length);
8431 if ($hash !== false) {
8432 return $hash;
8436 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8437 $staticdata = serialize($CFG) . serialize($_SERVER);
8438 $hash = '';
8439 do {
8440 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8441 } while (strlen($hash) < $length);
8443 return substr($hash, 0, $length);
8447 * Given some text (which may contain HTML) and an ideal length,
8448 * this function truncates the text neatly on a word boundary if possible
8450 * @category string
8451 * @param string $text text to be shortened
8452 * @param int $ideal ideal string length
8453 * @param boolean $exact if false, $text will not be cut mid-word
8454 * @param string $ending The string to append if the passed string is truncated
8455 * @return string $truncate shortened string
8457 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8458 // If the plain text is shorter than the maximum length, return the whole text.
8459 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8460 return $text;
8463 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8464 // and only tag in its 'line'.
8465 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8467 $totallength = core_text::strlen($ending);
8468 $truncate = '';
8470 // This array stores information about open and close tags and their position
8471 // in the truncated string. Each item in the array is an object with fields
8472 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8473 // (byte position in truncated text).
8474 $tagdetails = array();
8476 foreach ($lines as $linematchings) {
8477 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8478 if (!empty($linematchings[1])) {
8479 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8480 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8481 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8482 // Record closing tag.
8483 $tagdetails[] = (object) array(
8484 'open' => false,
8485 'tag' => core_text::strtolower($tagmatchings[1]),
8486 'pos' => core_text::strlen($truncate),
8489 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8490 // Record opening tag.
8491 $tagdetails[] = (object) array(
8492 'open' => true,
8493 'tag' => core_text::strtolower($tagmatchings[1]),
8494 'pos' => core_text::strlen($truncate),
8496 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8497 $tagdetails[] = (object) array(
8498 'open' => true,
8499 'tag' => core_text::strtolower('if'),
8500 'pos' => core_text::strlen($truncate),
8502 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8503 $tagdetails[] = (object) array(
8504 'open' => false,
8505 'tag' => core_text::strtolower('if'),
8506 'pos' => core_text::strlen($truncate),
8510 // Add html-tag to $truncate'd text.
8511 $truncate .= $linematchings[1];
8514 // Calculate the length of the plain text part of the line; handle entities as one character.
8515 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8516 if ($totallength + $contentlength > $ideal) {
8517 // The number of characters which are left.
8518 $left = $ideal - $totallength;
8519 $entitieslength = 0;
8520 // Search for html entities.
8521 if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $linematchings[2], $entities, PREG_OFFSET_CAPTURE)) {
8522 // Calculate the real length of all entities in the legal range.
8523 foreach ($entities[0] as $entity) {
8524 if ($entity[1]+1-$entitieslength <= $left) {
8525 $left--;
8526 $entitieslength += core_text::strlen($entity[0]);
8527 } else {
8528 // No more characters left.
8529 break;
8533 $breakpos = $left + $entitieslength;
8535 // If the words shouldn't be cut in the middle...
8536 if (!$exact) {
8537 // Search the last occurence of a space.
8538 for (; $breakpos > 0; $breakpos--) {
8539 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8540 if ($char === '.' or $char === ' ') {
8541 $breakpos += 1;
8542 break;
8543 } else if (strlen($char) > 2) {
8544 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8545 $breakpos += 1;
8546 break;
8551 if ($breakpos == 0) {
8552 // This deals with the test_shorten_text_no_spaces case.
8553 $breakpos = $left + $entitieslength;
8554 } else if ($breakpos > $left + $entitieslength) {
8555 // This deals with the previous for loop breaking on the first char.
8556 $breakpos = $left + $entitieslength;
8559 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8560 // Maximum length is reached, so get off the loop.
8561 break;
8562 } else {
8563 $truncate .= $linematchings[2];
8564 $totallength += $contentlength;
8567 // If the maximum length is reached, get off the loop.
8568 if ($totallength >= $ideal) {
8569 break;
8573 // Add the defined ending to the text.
8574 $truncate .= $ending;
8576 // Now calculate the list of open html tags based on the truncate position.
8577 $opentags = array();
8578 foreach ($tagdetails as $taginfo) {
8579 if ($taginfo->open) {
8580 // Add tag to the beginning of $opentags list.
8581 array_unshift($opentags, $taginfo->tag);
8582 } else {
8583 // Can have multiple exact same open tags, close the last one.
8584 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8585 if ($pos !== false) {
8586 unset($opentags[$pos]);
8591 // Close all unclosed html-tags.
8592 foreach ($opentags as $tag) {
8593 if ($tag === 'if') {
8594 $truncate .= '<!--<![endif]-->';
8595 } else {
8596 $truncate .= '</' . $tag . '>';
8600 return $truncate;
8604 * Shortens a given filename by removing characters positioned after the ideal string length.
8605 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8606 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8608 * @param string $filename file name
8609 * @param int $length ideal string length
8610 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8611 * @return string $shortened shortened file name
8613 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8614 $shortened = $filename;
8615 // Extract a part of the filename if it's char size exceeds the ideal string length.
8616 if (core_text::strlen($filename) > $length) {
8617 // Exclude extension if present in filename.
8618 $mimetypes = get_mimetypes_array();
8619 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8620 if ($extension && !empty($mimetypes[$extension])) {
8621 $basename = pathinfo($filename, PATHINFO_FILENAME);
8622 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8623 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8624 $shortened .= '.' . $extension;
8625 } else {
8626 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8627 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8630 return $shortened;
8634 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8636 * @param array $path The paths to reduce the length.
8637 * @param int $length Ideal string length
8638 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8639 * @return array $result Shortened paths in array.
8641 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8642 $result = null;
8644 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8645 $carry[] = shorten_filename($singlepath, $length, $includehash);
8646 return $carry;
8647 }, []);
8649 return $result;
8653 * Given dates in seconds, how many weeks is the date from startdate
8654 * The first week is 1, the second 2 etc ...
8656 * @param int $startdate Timestamp for the start date
8657 * @param int $thedate Timestamp for the end date
8658 * @return string
8660 function getweek ($startdate, $thedate) {
8661 if ($thedate < $startdate) {
8662 return 0;
8665 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8669 * Returns a randomly generated password of length $maxlen. inspired by
8671 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8672 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8674 * @param int $maxlen The maximum size of the password being generated.
8675 * @return string
8677 function generate_password($maxlen=10) {
8678 global $CFG;
8680 if (empty($CFG->passwordpolicy)) {
8681 $fillers = PASSWORD_DIGITS;
8682 $wordlist = file($CFG->wordlist);
8683 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8684 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8685 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8686 $password = $word1 . $filler1 . $word2;
8687 } else {
8688 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8689 $digits = $CFG->minpassworddigits;
8690 $lower = $CFG->minpasswordlower;
8691 $upper = $CFG->minpasswordupper;
8692 $nonalphanum = $CFG->minpasswordnonalphanum;
8693 $total = $lower + $upper + $digits + $nonalphanum;
8694 // Var minlength should be the greater one of the two ( $minlen and $total ).
8695 $minlen = $minlen < $total ? $total : $minlen;
8696 // Var maxlen can never be smaller than minlen.
8697 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8698 $additional = $maxlen - $total;
8700 // Make sure we have enough characters to fulfill
8701 // complexity requirements.
8702 $passworddigits = PASSWORD_DIGITS;
8703 while ($digits > strlen($passworddigits)) {
8704 $passworddigits .= PASSWORD_DIGITS;
8706 $passwordlower = PASSWORD_LOWER;
8707 while ($lower > strlen($passwordlower)) {
8708 $passwordlower .= PASSWORD_LOWER;
8710 $passwordupper = PASSWORD_UPPER;
8711 while ($upper > strlen($passwordupper)) {
8712 $passwordupper .= PASSWORD_UPPER;
8714 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8715 while ($nonalphanum > strlen($passwordnonalphanum)) {
8716 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8719 // Now mix and shuffle it all.
8720 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8721 substr(str_shuffle ($passwordupper), 0, $upper) .
8722 substr(str_shuffle ($passworddigits), 0, $digits) .
8723 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8724 substr(str_shuffle ($passwordlower .
8725 $passwordupper .
8726 $passworddigits .
8727 $passwordnonalphanum), 0 , $additional));
8730 return substr ($password, 0, $maxlen);
8734 * Given a float, prints it nicely.
8735 * Localized floats must not be used in calculations!
8737 * The stripzeros feature is intended for making numbers look nicer in small
8738 * areas where it is not necessary to indicate the degree of accuracy by showing
8739 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8740 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8742 * @param float $float The float to print
8743 * @param int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision).
8744 * @param bool $localized use localized decimal separator
8745 * @param bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after
8746 * the decimal point are always striped if $decimalpoints is -1.
8747 * @return string locale float
8749 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8750 if (is_null($float)) {
8751 return '';
8753 if ($localized) {
8754 $separator = get_string('decsep', 'langconfig');
8755 } else {
8756 $separator = '.';
8758 if ($decimalpoints == -1) {
8759 // The following counts the number of decimals.
8760 // It is safe as both floatval() and round() functions have same behaviour when non-numeric values are provided.
8761 $floatval = floatval($float);
8762 for ($decimalpoints = 0; $floatval != round($float, $decimalpoints); $decimalpoints++);
8765 $result = number_format($float, $decimalpoints, $separator, '');
8766 if ($stripzeros && $decimalpoints > 0) {
8767 // Remove zeros and final dot if not needed.
8768 // However, only do this if there is a decimal point!
8769 $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
8771 return $result;
8775 * Converts locale specific floating point/comma number back to standard PHP float value
8776 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8778 * @param string $localefloat locale aware float representation
8779 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8780 * @return mixed float|bool - false or the parsed float.
8782 function unformat_float($localefloat, $strict = false) {
8783 $localefloat = trim($localefloat);
8785 if ($localefloat == '') {
8786 return null;
8789 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8790 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8792 if ($strict && !is_numeric($localefloat)) {
8793 return false;
8796 return (float)$localefloat;
8800 * Given a simple array, this shuffles it up just like shuffle()
8801 * Unlike PHP's shuffle() this function works on any machine.
8803 * @param array $array The array to be rearranged
8804 * @return array
8806 function swapshuffle($array) {
8808 $last = count($array) - 1;
8809 for ($i = 0; $i <= $last; $i++) {
8810 $from = rand(0, $last);
8811 $curr = $array[$i];
8812 $array[$i] = $array[$from];
8813 $array[$from] = $curr;
8815 return $array;
8819 * Like {@link swapshuffle()}, but works on associative arrays
8821 * @param array $array The associative array to be rearranged
8822 * @return array
8824 function swapshuffle_assoc($array) {
8826 $newarray = array();
8827 $newkeys = swapshuffle(array_keys($array));
8829 foreach ($newkeys as $newkey) {
8830 $newarray[$newkey] = $array[$newkey];
8832 return $newarray;
8836 * Given an arbitrary array, and a number of draws,
8837 * this function returns an array with that amount
8838 * of items. The indexes are retained.
8840 * @todo Finish documenting this function
8842 * @param array $array
8843 * @param int $draws
8844 * @return array
8846 function draw_rand_array($array, $draws) {
8848 $return = array();
8850 $last = count($array);
8852 if ($draws > $last) {
8853 $draws = $last;
8856 while ($draws > 0) {
8857 $last--;
8859 $keys = array_keys($array);
8860 $rand = rand(0, $last);
8862 $return[$keys[$rand]] = $array[$keys[$rand]];
8863 unset($array[$keys[$rand]]);
8865 $draws--;
8868 return $return;
8872 * Calculate the difference between two microtimes
8874 * @param string $a The first Microtime
8875 * @param string $b The second Microtime
8876 * @return string
8878 function microtime_diff($a, $b) {
8879 list($adec, $asec) = explode(' ', $a);
8880 list($bdec, $bsec) = explode(' ', $b);
8881 return $bsec - $asec + $bdec - $adec;
8885 * Given a list (eg a,b,c,d,e) this function returns
8886 * an array of 1->a, 2->b, 3->c etc
8888 * @param string $list The string to explode into array bits
8889 * @param string $separator The separator used within the list string
8890 * @return array The now assembled array
8892 function make_menu_from_list($list, $separator=',') {
8894 $array = array_reverse(explode($separator, $list), true);
8895 foreach ($array as $key => $item) {
8896 $outarray[$key+1] = trim($item);
8898 return $outarray;
8902 * Creates an array that represents all the current grades that
8903 * can be chosen using the given grading type.
8905 * Negative numbers
8906 * are scales, zero is no grade, and positive numbers are maximum
8907 * grades.
8909 * @todo Finish documenting this function or better deprecated this completely!
8911 * @param int $gradingtype
8912 * @return array
8914 function make_grades_menu($gradingtype) {
8915 global $DB;
8917 $grades = array();
8918 if ($gradingtype < 0) {
8919 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8920 return make_menu_from_list($scale->scale);
8922 } else if ($gradingtype > 0) {
8923 for ($i=$gradingtype; $i>=0; $i--) {
8924 $grades[$i] = $i .' / '. $gradingtype;
8926 return $grades;
8928 return $grades;
8932 * make_unique_id_code
8934 * @todo Finish documenting this function
8936 * @uses $_SERVER
8937 * @param string $extra Extra string to append to the end of the code
8938 * @return string
8940 function make_unique_id_code($extra = '') {
8942 $hostname = 'unknownhost';
8943 if (!empty($_SERVER['HTTP_HOST'])) {
8944 $hostname = $_SERVER['HTTP_HOST'];
8945 } else if (!empty($_ENV['HTTP_HOST'])) {
8946 $hostname = $_ENV['HTTP_HOST'];
8947 } else if (!empty($_SERVER['SERVER_NAME'])) {
8948 $hostname = $_SERVER['SERVER_NAME'];
8949 } else if (!empty($_ENV['SERVER_NAME'])) {
8950 $hostname = $_ENV['SERVER_NAME'];
8953 $date = gmdate("ymdHis");
8955 $random = random_string(6);
8957 if ($extra) {
8958 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8959 } else {
8960 return $hostname .'+'. $date .'+'. $random;
8966 * Function to check the passed address is within the passed subnet
8968 * The parameter is a comma separated string of subnet definitions.
8969 * Subnet strings can be in one of three formats:
8970 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8971 * 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)
8972 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8973 * Code for type 1 modified from user posted comments by mediator at
8974 * {@link http://au.php.net/manual/en/function.ip2long.php}
8976 * @param string $addr The address you are checking
8977 * @param string $subnetstr The string of subnet addresses
8978 * @return bool
8980 function address_in_subnet($addr, $subnetstr) {
8982 if ($addr == '0.0.0.0') {
8983 return false;
8985 $subnets = explode(',', $subnetstr);
8986 $found = false;
8987 $addr = trim($addr);
8988 $addr = cleanremoteaddr($addr, false); // Normalise.
8989 if ($addr === null) {
8990 return false;
8992 $addrparts = explode(':', $addr);
8994 $ipv6 = strpos($addr, ':');
8996 foreach ($subnets as $subnet) {
8997 $subnet = trim($subnet);
8998 if ($subnet === '') {
8999 continue;
9002 if (strpos($subnet, '/') !== false) {
9003 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
9004 list($ip, $mask) = explode('/', $subnet);
9005 $mask = trim($mask);
9006 if (!is_number($mask)) {
9007 continue; // Incorect mask number, eh?
9009 $ip = cleanremoteaddr($ip, false); // Normalise.
9010 if ($ip === null) {
9011 continue;
9013 if (strpos($ip, ':') !== false) {
9014 // IPv6.
9015 if (!$ipv6) {
9016 continue;
9018 if ($mask > 128 or $mask < 0) {
9019 continue; // Nonsense.
9021 if ($mask == 0) {
9022 return true; // Any address.
9024 if ($mask == 128) {
9025 if ($ip === $addr) {
9026 return true;
9028 continue;
9030 $ipparts = explode(':', $ip);
9031 $modulo = $mask % 16;
9032 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
9033 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
9034 if (implode(':', $ipnet) === implode(':', $addrnet)) {
9035 if ($modulo == 0) {
9036 return true;
9038 $pos = ($mask-$modulo)/16;
9039 $ipnet = hexdec($ipparts[$pos]);
9040 $addrnet = hexdec($addrparts[$pos]);
9041 $mask = 0xffff << (16 - $modulo);
9042 if (($addrnet & $mask) == ($ipnet & $mask)) {
9043 return true;
9047 } else {
9048 // IPv4.
9049 if ($ipv6) {
9050 continue;
9052 if ($mask > 32 or $mask < 0) {
9053 continue; // Nonsense.
9055 if ($mask == 0) {
9056 return true;
9058 if ($mask == 32) {
9059 if ($ip === $addr) {
9060 return true;
9062 continue;
9064 $mask = 0xffffffff << (32 - $mask);
9065 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
9066 return true;
9070 } else if (strpos($subnet, '-') !== false) {
9071 // 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.
9072 $parts = explode('-', $subnet);
9073 if (count($parts) != 2) {
9074 continue;
9077 if (strpos($subnet, ':') !== false) {
9078 // IPv6.
9079 if (!$ipv6) {
9080 continue;
9082 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9083 if ($ipstart === null) {
9084 continue;
9086 $ipparts = explode(':', $ipstart);
9087 $start = hexdec(array_pop($ipparts));
9088 $ipparts[] = trim($parts[1]);
9089 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
9090 if ($ipend === null) {
9091 continue;
9093 $ipparts[7] = '';
9094 $ipnet = implode(':', $ipparts);
9095 if (strpos($addr, $ipnet) !== 0) {
9096 continue;
9098 $ipparts = explode(':', $ipend);
9099 $end = hexdec($ipparts[7]);
9101 $addrend = hexdec($addrparts[7]);
9103 if (($addrend >= $start) and ($addrend <= $end)) {
9104 return true;
9107 } else {
9108 // IPv4.
9109 if ($ipv6) {
9110 continue;
9112 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9113 if ($ipstart === null) {
9114 continue;
9116 $ipparts = explode('.', $ipstart);
9117 $ipparts[3] = trim($parts[1]);
9118 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
9119 if ($ipend === null) {
9120 continue;
9123 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9124 return true;
9128 } else {
9129 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9130 if (strpos($subnet, ':') !== false) {
9131 // IPv6.
9132 if (!$ipv6) {
9133 continue;
9135 $parts = explode(':', $subnet);
9136 $count = count($parts);
9137 if ($parts[$count-1] === '') {
9138 unset($parts[$count-1]); // Trim trailing :'s.
9139 $count--;
9140 $subnet = implode('.', $parts);
9142 $isip = cleanremoteaddr($subnet, false); // Normalise.
9143 if ($isip !== null) {
9144 if ($isip === $addr) {
9145 return true;
9147 continue;
9148 } else if ($count > 8) {
9149 continue;
9151 $zeros = array_fill(0, 8-$count, '0');
9152 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9153 if (address_in_subnet($addr, $subnet)) {
9154 return true;
9157 } else {
9158 // IPv4.
9159 if ($ipv6) {
9160 continue;
9162 $parts = explode('.', $subnet);
9163 $count = count($parts);
9164 if ($parts[$count-1] === '') {
9165 unset($parts[$count-1]); // Trim trailing .
9166 $count--;
9167 $subnet = implode('.', $parts);
9169 if ($count == 4) {
9170 $subnet = cleanremoteaddr($subnet, false); // Normalise.
9171 if ($subnet === $addr) {
9172 return true;
9174 continue;
9175 } else if ($count > 4) {
9176 continue;
9178 $zeros = array_fill(0, 4-$count, '0');
9179 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9180 if (address_in_subnet($addr, $subnet)) {
9181 return true;
9187 return false;
9191 * For outputting debugging info
9193 * @param string $string The string to write
9194 * @param string $eol The end of line char(s) to use
9195 * @param string $sleep Period to make the application sleep
9196 * This ensures any messages have time to display before redirect
9198 function mtrace($string, $eol="\n", $sleep=0) {
9199 global $CFG;
9201 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
9202 $fn = $CFG->mtrace_wrapper;
9203 $fn($string, $eol);
9204 return;
9205 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
9206 // We must explicitly call the add_line function here.
9207 // Uses of fwrite to STDOUT are not picked up by ob_start.
9208 if ($output = \core\task\logmanager::add_line("{$string}{$eol}")) {
9209 fwrite(STDOUT, $output);
9211 } else {
9212 echo $string . $eol;
9215 // Flush again.
9216 flush();
9218 // Delay to keep message on user's screen in case of subsequent redirect.
9219 if ($sleep) {
9220 sleep($sleep);
9225 * Replace 1 or more slashes or backslashes to 1 slash
9227 * @param string $path The path to strip
9228 * @return string the path with double slashes removed
9230 function cleardoubleslashes ($path) {
9231 return preg_replace('/(\/|\\\){1,}/', '/', $path);
9235 * Is the current ip in a given list?
9237 * @param string $list
9238 * @return bool
9240 function remoteip_in_list($list) {
9241 $clientip = getremoteaddr(null);
9243 if (!$clientip) {
9244 // Ensure access on cli.
9245 return true;
9247 return \core\ip_utils::is_ip_in_subnet_list($clientip, $list);
9251 * Returns most reliable client address
9253 * @param string $default If an address can't be determined, then return this
9254 * @return string The remote IP address
9256 function getremoteaddr($default='0.0.0.0') {
9257 global $CFG;
9259 if (!isset($CFG->getremoteaddrconf)) {
9260 // This will happen, for example, before just after the upgrade, as the
9261 // user is redirected to the admin screen.
9262 $variablestoskip = GETREMOTEADDR_SKIP_DEFAULT;
9263 } else {
9264 $variablestoskip = $CFG->getremoteaddrconf;
9266 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
9267 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9268 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9269 return $address ? $address : $default;
9272 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
9273 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9274 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9276 $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
9277 global $CFG;
9278 return !\core\ip_utils::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore ?? '', ',');
9281 // Multiple proxies can append values to this header including an
9282 // untrusted original request header so we must only trust the last ip.
9283 $address = end($forwardedaddresses);
9285 if (substr_count($address, ":") > 1) {
9286 // Remove port and brackets from IPv6.
9287 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9288 $address = $matches[1];
9290 } else {
9291 // Remove port from IPv4.
9292 if (substr_count($address, ":") == 1) {
9293 $parts = explode(":", $address);
9294 $address = $parts[0];
9298 $address = cleanremoteaddr($address);
9299 return $address ? $address : $default;
9302 if (!empty($_SERVER['REMOTE_ADDR'])) {
9303 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9304 return $address ? $address : $default;
9305 } else {
9306 return $default;
9311 * Cleans an ip address. Internal addresses are now allowed.
9312 * (Originally local addresses were not allowed.)
9314 * @param string $addr IPv4 or IPv6 address
9315 * @param bool $compress use IPv6 address compression
9316 * @return string normalised ip address string, null if error
9318 function cleanremoteaddr($addr, $compress=false) {
9319 $addr = trim($addr);
9321 if (strpos($addr, ':') !== false) {
9322 // Can be only IPv6.
9323 $parts = explode(':', $addr);
9324 $count = count($parts);
9326 if (strpos($parts[$count-1], '.') !== false) {
9327 // Legacy ipv4 notation.
9328 $last = array_pop($parts);
9329 $ipv4 = cleanremoteaddr($last, true);
9330 if ($ipv4 === null) {
9331 return null;
9333 $bits = explode('.', $ipv4);
9334 $parts[] = dechex($bits[0]).dechex($bits[1]);
9335 $parts[] = dechex($bits[2]).dechex($bits[3]);
9336 $count = count($parts);
9337 $addr = implode(':', $parts);
9340 if ($count < 3 or $count > 8) {
9341 return null; // Severly malformed.
9344 if ($count != 8) {
9345 if (strpos($addr, '::') === false) {
9346 return null; // Malformed.
9348 // Uncompress.
9349 $insertat = array_search('', $parts, true);
9350 $missing = array_fill(0, 1 + 8 - $count, '0');
9351 array_splice($parts, $insertat, 1, $missing);
9352 foreach ($parts as $key => $part) {
9353 if ($part === '') {
9354 $parts[$key] = '0';
9359 $adr = implode(':', $parts);
9360 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9361 return null; // Incorrect format - sorry.
9364 // Normalise 0s and case.
9365 $parts = array_map('hexdec', $parts);
9366 $parts = array_map('dechex', $parts);
9368 $result = implode(':', $parts);
9370 if (!$compress) {
9371 return $result;
9374 if ($result === '0:0:0:0:0:0:0:0') {
9375 return '::'; // All addresses.
9378 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9379 if ($compressed !== $result) {
9380 return $compressed;
9383 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9384 if ($compressed !== $result) {
9385 return $compressed;
9388 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9389 if ($compressed !== $result) {
9390 return $compressed;
9393 return $result;
9396 // First get all things that look like IPv4 addresses.
9397 $parts = array();
9398 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9399 return null;
9401 unset($parts[0]);
9403 foreach ($parts as $key => $match) {
9404 if ($match > 255) {
9405 return null;
9407 $parts[$key] = (int)$match; // Normalise 0s.
9410 return implode('.', $parts);
9415 * Is IP address a public address?
9417 * @param string $ip The ip to check
9418 * @return bool true if the ip is public
9420 function ip_is_public($ip) {
9421 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9425 * This function will make a complete copy of anything it's given,
9426 * regardless of whether it's an object or not.
9428 * @param mixed $thing Something you want cloned
9429 * @return mixed What ever it is you passed it
9431 function fullclone($thing) {
9432 return unserialize(serialize($thing));
9436 * Used to make sure that $min <= $value <= $max
9438 * Make sure that value is between min, and max
9440 * @param int $min The minimum value
9441 * @param int $value The value to check
9442 * @param int $max The maximum value
9443 * @return int
9445 function bounded_number($min, $value, $max) {
9446 if ($value < $min) {
9447 return $min;
9449 if ($value > $max) {
9450 return $max;
9452 return $value;
9456 * Check if there is a nested array within the passed array
9458 * @param array $array
9459 * @return bool true if there is a nested array false otherwise
9461 function array_is_nested($array) {
9462 foreach ($array as $value) {
9463 if (is_array($value)) {
9464 return true;
9467 return false;
9471 * get_performance_info() pairs up with init_performance_info()
9472 * loaded in setup.php. Returns an array with 'html' and 'txt'
9473 * values ready for use, and each of the individual stats provided
9474 * separately as well.
9476 * @return array
9478 function get_performance_info() {
9479 global $CFG, $PERF, $DB, $PAGE;
9481 $info = array();
9482 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9484 $info['html'] = '';
9485 if (!empty($CFG->themedesignermode)) {
9486 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9487 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9489 $info['html'] .= '<ul class="list-unstyled row mx-md-0">'; // Holds userfriendly HTML representation.
9491 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9493 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9494 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9496 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9497 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9499 if (function_exists('memory_get_usage')) {
9500 $info['memory_total'] = memory_get_usage();
9501 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9502 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9503 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9504 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9507 if (function_exists('memory_get_peak_usage')) {
9508 $info['memory_peak'] = memory_get_peak_usage();
9509 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9510 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9513 $info['html'] .= '</ul><ul class="list-unstyled row mx-md-0">';
9514 $inc = get_included_files();
9515 $info['includecount'] = count($inc);
9516 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9517 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9519 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9520 // We can not track more performance before installation or before PAGE init, sorry.
9521 return $info;
9524 $filtermanager = filter_manager::instance();
9525 if (method_exists($filtermanager, 'get_performance_summary')) {
9526 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9527 $info = array_merge($filterinfo, $info);
9528 foreach ($filterinfo as $key => $value) {
9529 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9530 $info['txt'] .= "$key: $value ";
9534 $stringmanager = get_string_manager();
9535 if (method_exists($stringmanager, 'get_performance_summary')) {
9536 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9537 $info = array_merge($filterinfo, $info);
9538 foreach ($filterinfo as $key => $value) {
9539 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9540 $info['txt'] .= "$key: $value ";
9544 if (!empty($PERF->logwrites)) {
9545 $info['logwrites'] = $PERF->logwrites;
9546 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9547 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9550 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9551 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9552 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9554 if ($DB->want_read_slave()) {
9555 $info['dbreads_slave'] = $DB->perf_get_reads_slave();
9556 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads from slave: '.$info['dbreads_slave'].'</li> ';
9557 $info['txt'] .= 'db reads from slave: '.$info['dbreads_slave'].' ';
9560 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9561 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9562 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9564 if (function_exists('posix_times')) {
9565 $ptimes = posix_times();
9566 if (is_array($ptimes)) {
9567 foreach ($ptimes as $key => $val) {
9568 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9570 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9571 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9572 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9576 // Grab the load average for the last minute.
9577 // /proc will only work under some linux configurations
9578 // while uptime is there under MacOSX/Darwin and other unices.
9579 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9580 list($serverload) = explode(' ', $loadavg[0]);
9581 unset($loadavg);
9582 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9583 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9584 $serverload = $matches[1];
9585 } else {
9586 trigger_error('Could not parse uptime output!');
9589 if (!empty($serverload)) {
9590 $info['serverload'] = $serverload;
9591 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9592 $info['txt'] .= "serverload: {$info['serverload']} ";
9595 // Display size of session if session started.
9596 if ($si = \core\session\manager::get_performance_info()) {
9597 $info['sessionsize'] = $si['size'];
9598 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9599 $info['txt'] .= $si['txt'];
9602 $info['html'] .= '</ul>';
9603 $html = '';
9604 if ($stats = cache_helper::get_stats()) {
9606 $table = new html_table();
9607 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9608 $table->head = ['Mode', 'Cache item', 'Static', 'H', 'M', get_string('mappingprimary', 'cache'), 'H', 'M', 'S', 'I/O'];
9609 $table->data = [];
9610 $table->align = ['left', 'left', 'left', 'right', 'right', 'left', 'right', 'right', 'right', 'right'];
9612 $text = 'Caches used (hits/misses/sets): ';
9613 $hits = 0;
9614 $misses = 0;
9615 $sets = 0;
9616 $maxstores = 0;
9618 // We want to align static caches into their own column.
9619 $hasstatic = false;
9620 foreach ($stats as $definition => $details) {
9621 $numstores = count($details['stores']);
9622 $first = key($details['stores']);
9623 if ($first !== cache_store::STATIC_ACCEL) {
9624 $numstores++; // Add a blank space for the missing static store.
9626 $maxstores = max($maxstores, $numstores);
9629 $storec = 0;
9631 while ($storec++ < ($maxstores - 2)) {
9632 if ($storec == ($maxstores - 2)) {
9633 $table->head[] = get_string('mappingfinal', 'cache');
9634 } else {
9635 $table->head[] = "Store $storec";
9637 $table->align[] = 'left';
9638 $table->align[] = 'right';
9639 $table->align[] = 'right';
9640 $table->align[] = 'right';
9641 $table->align[] = 'right';
9642 $table->head[] = 'H';
9643 $table->head[] = 'M';
9644 $table->head[] = 'S';
9645 $table->head[] = 'I/O';
9648 ksort($stats);
9650 foreach ($stats as $definition => $details) {
9651 switch ($details['mode']) {
9652 case cache_store::MODE_APPLICATION:
9653 $modeclass = 'application';
9654 $mode = ' <span title="application cache">App</span>';
9655 break;
9656 case cache_store::MODE_SESSION:
9657 $modeclass = 'session';
9658 $mode = ' <span title="session cache">Ses</span>';
9659 break;
9660 case cache_store::MODE_REQUEST:
9661 $modeclass = 'request';
9662 $mode = ' <span title="request cache">Req</span>';
9663 break;
9665 $row = [$mode, $definition];
9667 $text .= "$definition {";
9669 $storec = 0;
9670 foreach ($details['stores'] as $store => $data) {
9672 if ($storec == 0 && $store !== cache_store::STATIC_ACCEL) {
9673 $row[] = '';
9674 $row[] = '';
9675 $row[] = '';
9676 $storec++;
9679 $hits += $data['hits'];
9680 $misses += $data['misses'];
9681 $sets += $data['sets'];
9682 if ($data['hits'] == 0 and $data['misses'] > 0) {
9683 $cachestoreclass = 'nohits bg-danger';
9684 } else if ($data['hits'] < $data['misses']) {
9685 $cachestoreclass = 'lowhits bg-warning text-dark';
9686 } else {
9687 $cachestoreclass = 'hihits';
9689 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9690 $cell = new html_table_cell($store);
9691 $cell->attributes = ['class' => $cachestoreclass];
9692 $row[] = $cell;
9693 $cell = new html_table_cell($data['hits']);
9694 $cell->attributes = ['class' => $cachestoreclass];
9695 $row[] = $cell;
9696 $cell = new html_table_cell($data['misses']);
9697 $cell->attributes = ['class' => $cachestoreclass];
9698 $row[] = $cell;
9700 if ($store !== cache_store::STATIC_ACCEL) {
9701 // The static cache is never set.
9702 $cell = new html_table_cell($data['sets']);
9703 $cell->attributes = ['class' => $cachestoreclass];
9704 $row[] = $cell;
9706 if ($data['hits'] || $data['sets']) {
9707 if ($data['iobytes'] === cache_store::IO_BYTES_NOT_SUPPORTED) {
9708 $size = '-';
9709 } else {
9710 $size = display_size($data['iobytes'], 1, 'KB');
9711 if ($data['iobytes'] >= 10 * 1024) {
9712 $cachestoreclass = ' bg-warning text-dark';
9715 } else {
9716 $size = '';
9718 $cell = new html_table_cell($size);
9719 $cell->attributes = ['class' => $cachestoreclass];
9720 $row[] = $cell;
9722 $storec++;
9724 while ($storec++ < $maxstores) {
9725 $row[] = '';
9726 $row[] = '';
9727 $row[] = '';
9728 $row[] = '';
9729 $row[] = '';
9731 $text .= '} ';
9733 $table->data[] = $row;
9736 $html .= html_writer::table($table);
9738 // Now lets also show sub totals for each cache store.
9739 $storetotals = [];
9740 $storetotal = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9741 foreach ($stats as $definition => $details) {
9742 foreach ($details['stores'] as $store => $data) {
9743 if (!array_key_exists($store, $storetotals)) {
9744 $storetotals[$store] = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9746 $storetotals[$store]['class'] = $data['class'];
9747 $storetotals[$store]['hits'] += $data['hits'];
9748 $storetotals[$store]['misses'] += $data['misses'];
9749 $storetotals[$store]['sets'] += $data['sets'];
9750 $storetotal['hits'] += $data['hits'];
9751 $storetotal['misses'] += $data['misses'];
9752 $storetotal['sets'] += $data['sets'];
9753 if ($data['iobytes'] !== cache_store::IO_BYTES_NOT_SUPPORTED) {
9754 $storetotals[$store]['iobytes'] += $data['iobytes'];
9755 $storetotal['iobytes'] += $data['iobytes'];
9760 $table = new html_table();
9761 $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9762 $table->head = [get_string('storename', 'cache'), get_string('type_cachestore', 'plugin'), 'H', 'M', 'S', 'I/O'];
9763 $table->data = [];
9764 $table->align = ['left', 'left', 'right', 'right', 'right', 'right'];
9766 ksort($storetotals);
9768 foreach ($storetotals as $store => $data) {
9769 $row = [];
9770 if ($data['hits'] == 0 and $data['misses'] > 0) {
9771 $cachestoreclass = 'nohits bg-danger';
9772 } else if ($data['hits'] < $data['misses']) {
9773 $cachestoreclass = 'lowhits bg-warning text-dark';
9774 } else {
9775 $cachestoreclass = 'hihits';
9777 $cell = new html_table_cell($store);
9778 $cell->attributes = ['class' => $cachestoreclass];
9779 $row[] = $cell;
9780 $cell = new html_table_cell($data['class']);
9781 $cell->attributes = ['class' => $cachestoreclass];
9782 $row[] = $cell;
9783 $cell = new html_table_cell($data['hits']);
9784 $cell->attributes = ['class' => $cachestoreclass];
9785 $row[] = $cell;
9786 $cell = new html_table_cell($data['misses']);
9787 $cell->attributes = ['class' => $cachestoreclass];
9788 $row[] = $cell;
9789 $cell = new html_table_cell($data['sets']);
9790 $cell->attributes = ['class' => $cachestoreclass];
9791 $row[] = $cell;
9792 if ($data['hits'] || $data['sets']) {
9793 if ($data['iobytes']) {
9794 $size = display_size($data['iobytes'], 1, 'KB');
9795 } else {
9796 $size = '-';
9798 } else {
9799 $size = '';
9801 $cell = new html_table_cell($size);
9802 $cell->attributes = ['class' => $cachestoreclass];
9803 $row[] = $cell;
9804 $table->data[] = $row;
9806 if (!empty($storetotal['iobytes'])) {
9807 $size = display_size($storetotal['iobytes'], 1, 'KB');
9808 } else if (!empty($storetotal['hits']) || !empty($storetotal['sets'])) {
9809 $size = '-';
9810 } else {
9811 $size = '';
9813 $row = [
9814 get_string('total'),
9816 $storetotal['hits'],
9817 $storetotal['misses'],
9818 $storetotal['sets'],
9819 $size,
9821 $table->data[] = $row;
9823 $html .= html_writer::table($table);
9825 $info['cachesused'] = "$hits / $misses / $sets";
9826 $info['html'] .= $html;
9827 $info['txt'] .= $text.'. ';
9828 } else {
9829 $info['cachesused'] = '0 / 0 / 0';
9830 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9831 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9834 $info['html'] = '<div class="performanceinfo siteinfo container-fluid px-md-0 overflow-auto pt-3">'.$info['html'].'</div>';
9835 return $info;
9839 * Renames a file or directory to a unique name within the same directory.
9841 * This function is designed to avoid any potential race conditions, and select an unused name.
9843 * @param string $filepath Original filepath
9844 * @param string $prefix Prefix to use for the temporary name
9845 * @return string|bool New file path or false if failed
9846 * @since Moodle 3.10
9848 function rename_to_unused_name(string $filepath, string $prefix = '_temp_') {
9849 $dir = dirname($filepath);
9850 $basename = $dir . '/' . $prefix;
9851 $limit = 0;
9852 while ($limit < 100) {
9853 // Select a new name based on a random number.
9854 $newfilepath = $basename . md5(mt_rand());
9856 // Attempt a rename to that new name.
9857 if (@rename($filepath, $newfilepath)) {
9858 return $newfilepath;
9861 // The first time, do some sanity checks, maybe it is failing for a good reason and there
9862 // is no point trying 100 times if so.
9863 if ($limit === 0 && (!file_exists($filepath) || !is_writable($dir))) {
9864 return false;
9866 $limit++;
9868 return false;
9872 * Delete directory or only its content
9874 * @param string $dir directory path
9875 * @param bool $contentonly
9876 * @return bool success, true also if dir does not exist
9878 function remove_dir($dir, $contentonly=false) {
9879 if (!is_dir($dir)) {
9880 // Nothing to do.
9881 return true;
9884 if (!$contentonly) {
9885 // Start by renaming the directory; this will guarantee that other processes don't write to it
9886 // while it is in the process of being deleted.
9887 $tempdir = rename_to_unused_name($dir);
9888 if ($tempdir) {
9889 // If the rename was successful then delete the $tempdir instead.
9890 $dir = $tempdir;
9892 // If the rename fails, we will continue through and attempt to delete the directory
9893 // without renaming it since that is likely to at least delete most of the files.
9896 if (!$handle = opendir($dir)) {
9897 return false;
9899 $result = true;
9900 while (false!==($item = readdir($handle))) {
9901 if ($item != '.' && $item != '..') {
9902 if (is_dir($dir.'/'.$item)) {
9903 $result = remove_dir($dir.'/'.$item) && $result;
9904 } else {
9905 $result = unlink($dir.'/'.$item) && $result;
9909 closedir($handle);
9910 if ($contentonly) {
9911 clearstatcache(); // Make sure file stat cache is properly invalidated.
9912 return $result;
9914 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9915 clearstatcache(); // Make sure file stat cache is properly invalidated.
9916 return $result;
9920 * Detect if an object or a class contains a given property
9921 * will take an actual object or the name of a class
9923 * @param mix $obj Name of class or real object to test
9924 * @param string $property name of property to find
9925 * @return bool true if property exists
9927 function object_property_exists( $obj, $property ) {
9928 if (is_string( $obj )) {
9929 $properties = get_class_vars( $obj );
9930 } else {
9931 $properties = get_object_vars( $obj );
9933 return array_key_exists( $property, $properties );
9937 * Converts an object into an associative array
9939 * This function converts an object into an associative array by iterating
9940 * over its public properties. Because this function uses the foreach
9941 * construct, Iterators are respected. It works recursively on arrays of objects.
9942 * Arrays and simple values are returned as is.
9944 * If class has magic properties, it can implement IteratorAggregate
9945 * and return all available properties in getIterator()
9947 * @param mixed $var
9948 * @return array
9950 function convert_to_array($var) {
9951 $result = array();
9953 // Loop over elements/properties.
9954 foreach ($var as $key => $value) {
9955 // Recursively convert objects.
9956 if (is_object($value) || is_array($value)) {
9957 $result[$key] = convert_to_array($value);
9958 } else {
9959 // Simple values are untouched.
9960 $result[$key] = $value;
9963 return $result;
9967 * Detect a custom script replacement in the data directory that will
9968 * replace an existing moodle script
9970 * @return string|bool full path name if a custom script exists, false if no custom script exists
9972 function custom_script_path() {
9973 global $CFG, $SCRIPT;
9975 if ($SCRIPT === null) {
9976 // Probably some weird external script.
9977 return false;
9980 $scriptpath = $CFG->customscripts . $SCRIPT;
9982 // Check the custom script exists.
9983 if (file_exists($scriptpath) and is_file($scriptpath)) {
9984 return $scriptpath;
9985 } else {
9986 return false;
9991 * Returns whether or not the user object is a remote MNET user. This function
9992 * is in moodlelib because it does not rely on loading any of the MNET code.
9994 * @param object $user A valid user object
9995 * @return bool True if the user is from a remote Moodle.
9997 function is_mnet_remote_user($user) {
9998 global $CFG;
10000 if (!isset($CFG->mnet_localhost_id)) {
10001 include_once($CFG->dirroot . '/mnet/lib.php');
10002 $env = new mnet_environment();
10003 $env->init();
10004 unset($env);
10007 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
10011 * This function will search for browser prefereed languages, setting Moodle
10012 * to use the best one available if $SESSION->lang is undefined
10014 function setup_lang_from_browser() {
10015 global $CFG, $SESSION, $USER;
10017 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
10018 // Lang is defined in session or user profile, nothing to do.
10019 return;
10022 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
10023 return;
10026 // Extract and clean langs from headers.
10027 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
10028 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
10029 $rawlangs = explode(',', $rawlangs); // Convert to array.
10030 $langs = array();
10032 $order = 1.0;
10033 foreach ($rawlangs as $lang) {
10034 if (strpos($lang, ';') === false) {
10035 $langs[(string)$order] = $lang;
10036 $order = $order-0.01;
10037 } else {
10038 $parts = explode(';', $lang);
10039 $pos = strpos($parts[1], '=');
10040 $langs[substr($parts[1], $pos+1)] = $parts[0];
10043 krsort($langs, SORT_NUMERIC);
10045 // Look for such langs under standard locations.
10046 foreach ($langs as $lang) {
10047 // Clean it properly for include.
10048 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
10049 if (get_string_manager()->translation_exists($lang, false)) {
10050 // Lang exists, set it in session.
10051 $SESSION->lang = $lang;
10052 // We have finished. Go out.
10053 break;
10056 return;
10060 * Check if $url matches anything in proxybypass list
10062 * Any errors just result in the proxy being used (least bad)
10064 * @param string $url url to check
10065 * @return boolean true if we should bypass the proxy
10067 function is_proxybypass( $url ) {
10068 global $CFG;
10070 // Sanity check.
10071 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
10072 return false;
10075 // Get the host part out of the url.
10076 if (!$host = parse_url( $url, PHP_URL_HOST )) {
10077 return false;
10080 // Get the possible bypass hosts into an array.
10081 $matches = explode( ',', $CFG->proxybypass );
10083 // Check for a match.
10084 // (IPs need to match the left hand side and hosts the right of the url,
10085 // but we can recklessly check both as there can't be a false +ve).
10086 foreach ($matches as $match) {
10087 $match = trim($match);
10089 // Try for IP match (Left side).
10090 $lhs = substr($host, 0, strlen($match));
10091 if (strcasecmp($match, $lhs)==0) {
10092 return true;
10095 // Try for host match (Right side).
10096 $rhs = substr($host, -strlen($match));
10097 if (strcasecmp($match, $rhs)==0) {
10098 return true;
10102 // Nothing matched.
10103 return false;
10107 * Check if the passed navigation is of the new style
10109 * @param mixed $navigation
10110 * @return bool true for yes false for no
10112 function is_newnav($navigation) {
10113 if (is_array($navigation) && !empty($navigation['newnav'])) {
10114 return true;
10115 } else {
10116 return false;
10121 * Checks whether the given variable name is defined as a variable within the given object.
10123 * This will NOT work with stdClass objects, which have no class variables.
10125 * @param string $var The variable name
10126 * @param object $object The object to check
10127 * @return boolean
10129 function in_object_vars($var, $object) {
10130 $classvars = get_class_vars(get_class($object));
10131 $classvars = array_keys($classvars);
10132 return in_array($var, $classvars);
10136 * Returns an array without repeated objects.
10137 * This function is similar to array_unique, but for arrays that have objects as values
10139 * @param array $array
10140 * @param bool $keepkeyassoc
10141 * @return array
10143 function object_array_unique($array, $keepkeyassoc = true) {
10144 $duplicatekeys = array();
10145 $tmp = array();
10147 foreach ($array as $key => $val) {
10148 // Convert objects to arrays, in_array() does not support objects.
10149 if (is_object($val)) {
10150 $val = (array)$val;
10153 if (!in_array($val, $tmp)) {
10154 $tmp[] = $val;
10155 } else {
10156 $duplicatekeys[] = $key;
10160 foreach ($duplicatekeys as $key) {
10161 unset($array[$key]);
10164 return $keepkeyassoc ? $array : array_values($array);
10168 * Is a userid the primary administrator?
10170 * @param int $userid int id of user to check
10171 * @return boolean
10173 function is_primary_admin($userid) {
10174 $primaryadmin = get_admin();
10176 if ($userid == $primaryadmin->id) {
10177 return true;
10178 } else {
10179 return false;
10184 * Returns the site identifier
10186 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
10188 function get_site_identifier() {
10189 global $CFG;
10190 // Check to see if it is missing. If so, initialise it.
10191 if (empty($CFG->siteidentifier)) {
10192 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
10194 // Return it.
10195 return $CFG->siteidentifier;
10199 * Check whether the given password has no more than the specified
10200 * number of consecutive identical characters.
10202 * @param string $password password to be checked against the password policy
10203 * @param integer $maxchars maximum number of consecutive identical characters
10204 * @return bool
10206 function check_consecutive_identical_characters($password, $maxchars) {
10208 if ($maxchars < 1) {
10209 return true; // Zero 0 is to disable this check.
10211 if (strlen($password) <= $maxchars) {
10212 return true; // Too short to fail this test.
10215 $previouschar = '';
10216 $consecutivecount = 1;
10217 foreach (str_split($password) as $char) {
10218 if ($char != $previouschar) {
10219 $consecutivecount = 1;
10220 } else {
10221 $consecutivecount++;
10222 if ($consecutivecount > $maxchars) {
10223 return false; // Check failed already.
10227 $previouschar = $char;
10230 return true;
10234 * Helper function to do partial function binding.
10235 * so we can use it for preg_replace_callback, for example
10236 * this works with php functions, user functions, static methods and class methods
10237 * it returns you a callback that you can pass on like so:
10239 * $callback = partial('somefunction', $arg1, $arg2);
10240 * or
10241 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
10242 * or even
10243 * $obj = new someclass();
10244 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
10246 * and then the arguments that are passed through at calltime are appended to the argument list.
10248 * @param mixed $function a php callback
10249 * @param mixed $arg1,... $argv arguments to partially bind with
10250 * @return array Array callback
10252 function partial() {
10253 if (!class_exists('partial')) {
10255 * Used to manage function binding.
10256 * @copyright 2009 Penny Leach
10257 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10259 class partial{
10260 /** @var array */
10261 public $values = array();
10262 /** @var string The function to call as a callback. */
10263 public $func;
10265 * Constructor
10266 * @param string $func
10267 * @param array $args
10269 public function __construct($func, $args) {
10270 $this->values = $args;
10271 $this->func = $func;
10274 * Calls the callback function.
10275 * @return mixed
10277 public function method() {
10278 $args = func_get_args();
10279 return call_user_func_array($this->func, array_merge($this->values, $args));
10283 $args = func_get_args();
10284 $func = array_shift($args);
10285 $p = new partial($func, $args);
10286 return array($p, 'method');
10290 * helper function to load up and initialise the mnet environment
10291 * this must be called before you use mnet functions.
10293 * @return mnet_environment the equivalent of old $MNET global
10295 function get_mnet_environment() {
10296 global $CFG;
10297 require_once($CFG->dirroot . '/mnet/lib.php');
10298 static $instance = null;
10299 if (empty($instance)) {
10300 $instance = new mnet_environment();
10301 $instance->init();
10303 return $instance;
10307 * during xmlrpc server code execution, any code wishing to access
10308 * information about the remote peer must use this to get it.
10310 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
10312 function get_mnet_remote_client() {
10313 if (!defined('MNET_SERVER')) {
10314 debugging(get_string('notinxmlrpcserver', 'mnet'));
10315 return false;
10317 global $MNET_REMOTE_CLIENT;
10318 if (isset($MNET_REMOTE_CLIENT)) {
10319 return $MNET_REMOTE_CLIENT;
10321 return false;
10325 * during the xmlrpc server code execution, this will be called
10326 * to setup the object returned by {@link get_mnet_remote_client}
10328 * @param mnet_remote_client $client the client to set up
10329 * @throws moodle_exception
10331 function set_mnet_remote_client($client) {
10332 if (!defined('MNET_SERVER')) {
10333 throw new moodle_exception('notinxmlrpcserver', 'mnet');
10335 global $MNET_REMOTE_CLIENT;
10336 $MNET_REMOTE_CLIENT = $client;
10340 * return the jump url for a given remote user
10341 * this is used for rewriting forum post links in emails, etc
10343 * @param stdclass $user the user to get the idp url for
10345 function mnet_get_idp_jump_url($user) {
10346 global $CFG;
10348 static $mnetjumps = array();
10349 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
10350 $idp = mnet_get_peer_host($user->mnethostid);
10351 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
10352 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
10354 return $mnetjumps[$user->mnethostid];
10358 * Gets the homepage to use for the current user
10360 * @return int One of HOMEPAGE_*
10362 function get_home_page() {
10363 global $CFG;
10365 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
10366 // If dashboard is disabled, home will be set to default page.
10367 $defaultpage = get_default_home_page();
10368 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
10369 if (!empty($CFG->enabledashboard)) {
10370 return HOMEPAGE_MY;
10371 } else {
10372 return $defaultpage;
10374 } else if ($CFG->defaulthomepage == HOMEPAGE_MYCOURSES) {
10375 return HOMEPAGE_MYCOURSES;
10376 } else {
10377 $userhomepage = (int) get_user_preferences('user_home_page_preference', $defaultpage);
10378 if (empty($CFG->enabledashboard) && $userhomepage == HOMEPAGE_MY) {
10379 // If the user was using the dashboard but it's disabled, return the default home page.
10380 $userhomepage = $defaultpage;
10382 return $userhomepage;
10385 return HOMEPAGE_SITE;
10389 * Returns the default home page to display if current one is not defined or can't be applied.
10390 * The default behaviour is to return Dashboard if it's enabled or My courses page if it isn't.
10392 * @return int The default home page.
10394 function get_default_home_page(): int {
10395 global $CFG;
10397 return !empty($CFG->enabledashboard) ? HOMEPAGE_MY : HOMEPAGE_MYCOURSES;
10401 * Gets the name of a course to be displayed when showing a list of courses.
10402 * By default this is just $course->fullname but user can configure it. The
10403 * result of this function should be passed through print_string.
10404 * @param stdClass|core_course_list_element $course Moodle course object
10405 * @return string Display name of course (either fullname or short + fullname)
10407 function get_course_display_name_for_list($course) {
10408 global $CFG;
10409 if (!empty($CFG->courselistshortnames)) {
10410 if (!($course instanceof stdClass)) {
10411 $course = (object)convert_to_array($course);
10413 return get_string('courseextendednamedisplay', '', $course);
10414 } else {
10415 return $course->fullname;
10420 * Safe analogue of unserialize() that can only parse arrays
10422 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
10423 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
10424 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
10426 * @param string $expression
10427 * @return array|bool either parsed array or false if parsing was impossible.
10429 function unserialize_array($expression) {
10430 $subs = [];
10431 // Find nested arrays, parse them and store in $subs , substitute with special string.
10432 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
10433 $key = '--SUB' . count($subs) . '--';
10434 $subs[$key] = unserialize_array($matches[2]);
10435 if ($subs[$key] === false) {
10436 return false;
10438 $expression = str_replace($matches[2], $key . ';', $expression);
10441 // Check the expression is an array.
10442 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
10443 return false;
10445 // Get the size and elements of an array (key;value;key;value;....).
10446 $parts = explode(';', $matches1[2]);
10447 $size = intval($matches1[1]);
10448 if (count($parts) < $size * 2 + 1) {
10449 return false;
10451 // Analyze each part and make sure it is an integer or string or a substitute.
10452 $value = [];
10453 for ($i = 0; $i < $size * 2; $i++) {
10454 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
10455 $parts[$i] = (int)$matches2[1];
10456 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
10457 $parts[$i] = $matches3[2];
10458 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
10459 $parts[$i] = $subs[$parts[$i]];
10460 } else {
10461 return false;
10464 // Combine keys and values.
10465 for ($i = 0; $i < $size * 2; $i += 2) {
10466 $value[$parts[$i]] = $parts[$i+1];
10468 return $value;
10472 * Safe method for unserializing given input that is expected to contain only a serialized instance of an stdClass object
10474 * If any class type other than stdClass is included in the input string, it will not be instantiated and will be cast to an
10475 * stdClass object. The initial cast to array, then back to object is to ensure we are always returning the correct type,
10476 * otherwise we would return an instances of {@see __PHP_Incomplete_class} for malformed strings
10478 * @param string $input
10479 * @return stdClass
10481 function unserialize_object(string $input): stdClass {
10482 $instance = (array) unserialize($input, ['allowed_classes' => [stdClass::class]]);
10483 return (object) $instance;
10487 * The lang_string class
10489 * This special class is used to create an object representation of a string request.
10490 * It is special because processing doesn't occur until the object is first used.
10491 * The class was created especially to aid performance in areas where strings were
10492 * required to be generated but were not necessarily used.
10493 * As an example the admin tree when generated uses over 1500 strings, of which
10494 * normally only 1/3 are ever actually printed at any time.
10495 * The performance advantage is achieved by not actually processing strings that
10496 * arn't being used, as such reducing the processing required for the page.
10498 * How to use the lang_string class?
10499 * There are two methods of using the lang_string class, first through the
10500 * forth argument of the get_string function, and secondly directly.
10501 * The following are examples of both.
10502 * 1. Through get_string calls e.g.
10503 * $string = get_string($identifier, $component, $a, true);
10504 * $string = get_string('yes', 'moodle', null, true);
10505 * 2. Direct instantiation
10506 * $string = new lang_string($identifier, $component, $a, $lang);
10507 * $string = new lang_string('yes');
10509 * How do I use a lang_string object?
10510 * The lang_string object makes use of a magic __toString method so that you
10511 * are able to use the object exactly as you would use a string in most cases.
10512 * This means you are able to collect it into a variable and then directly
10513 * echo it, or concatenate it into another string, or similar.
10514 * The other thing you can do is manually get the string by calling the
10515 * lang_strings out method e.g.
10516 * $string = new lang_string('yes');
10517 * $string->out();
10518 * Also worth noting is that the out method can take one argument, $lang which
10519 * allows the developer to change the language on the fly.
10521 * When should I use a lang_string object?
10522 * The lang_string object is designed to be used in any situation where a
10523 * string may not be needed, but needs to be generated.
10524 * The admin tree is a good example of where lang_string objects should be
10525 * used.
10526 * A more practical example would be any class that requries strings that may
10527 * not be printed (after all classes get renderer by renderers and who knows
10528 * what they will do ;))
10530 * When should I not use a lang_string object?
10531 * Don't use lang_strings when you are going to use a string immediately.
10532 * There is no need as it will be processed immediately and there will be no
10533 * advantage, and in fact perhaps a negative hit as a class has to be
10534 * instantiated for a lang_string object, however get_string won't require
10535 * that.
10537 * Limitations:
10538 * 1. You cannot use a lang_string object as an array offset. Doing so will
10539 * result in PHP throwing an error. (You can use it as an object property!)
10541 * @package core
10542 * @category string
10543 * @copyright 2011 Sam Hemelryk
10544 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10546 class lang_string {
10548 /** @var string The strings identifier */
10549 protected $identifier;
10550 /** @var string The strings component. Default '' */
10551 protected $component = '';
10552 /** @var array|stdClass Any arguments required for the string. Default null */
10553 protected $a = null;
10554 /** @var string The language to use when processing the string. Default null */
10555 protected $lang = null;
10557 /** @var string The processed string (once processed) */
10558 protected $string = null;
10561 * A special boolean. If set to true then the object has been woken up and
10562 * cannot be regenerated. If this is set then $this->string MUST be used.
10563 * @var bool
10565 protected $forcedstring = false;
10568 * Constructs a lang_string object
10570 * This function should do as little processing as possible to ensure the best
10571 * performance for strings that won't be used.
10573 * @param string $identifier The strings identifier
10574 * @param string $component The strings component
10575 * @param stdClass|array $a Any arguments the string requires
10576 * @param string $lang The language to use when processing the string.
10577 * @throws coding_exception
10579 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10580 if (empty($component)) {
10581 $component = 'moodle';
10584 $this->identifier = $identifier;
10585 $this->component = $component;
10586 $this->lang = $lang;
10588 // We MUST duplicate $a to ensure that it if it changes by reference those
10589 // changes are not carried across.
10590 // To do this we always ensure $a or its properties/values are strings
10591 // and that any properties/values that arn't convertable are forgotten.
10592 if ($a !== null) {
10593 if (is_scalar($a)) {
10594 $this->a = $a;
10595 } else if ($a instanceof lang_string) {
10596 $this->a = $a->out();
10597 } else if (is_object($a) or is_array($a)) {
10598 $a = (array)$a;
10599 $this->a = array();
10600 foreach ($a as $key => $value) {
10601 // Make sure conversion errors don't get displayed (results in '').
10602 if (is_array($value)) {
10603 $this->a[$key] = '';
10604 } else if (is_object($value)) {
10605 if (method_exists($value, '__toString')) {
10606 $this->a[$key] = $value->__toString();
10607 } else {
10608 $this->a[$key] = '';
10610 } else {
10611 $this->a[$key] = (string)$value;
10617 if (debugging(false, DEBUG_DEVELOPER)) {
10618 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10619 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10621 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10622 throw new coding_exception('Invalid string compontent. Please check your string definition');
10624 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10625 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10631 * Processes the string.
10633 * This function actually processes the string, stores it in the string property
10634 * and then returns it.
10635 * You will notice that this function is VERY similar to the get_string method.
10636 * That is because it is pretty much doing the same thing.
10637 * However as this function is an upgrade it isn't as tolerant to backwards
10638 * compatibility.
10640 * @return string
10641 * @throws coding_exception
10643 protected function get_string() {
10644 global $CFG;
10646 // Check if we need to process the string.
10647 if ($this->string === null) {
10648 // Check the quality of the identifier.
10649 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10650 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);
10653 // Process the string.
10654 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10655 // Debugging feature lets you display string identifier and component.
10656 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10657 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10660 // Return the string.
10661 return $this->string;
10665 * Returns the string
10667 * @param string $lang The langauge to use when processing the string
10668 * @return string
10670 public function out($lang = null) {
10671 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10672 if ($this->forcedstring) {
10673 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10674 return $this->get_string();
10676 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10677 return $translatedstring->out();
10679 return $this->get_string();
10683 * Magic __toString method for printing a string
10685 * @return string
10687 public function __toString() {
10688 return $this->get_string();
10692 * Magic __set_state method used for var_export
10694 * @param array $array
10695 * @return self
10697 public static function __set_state(array $array): self {
10698 $tmp = new lang_string($array['identifier'], $array['component'], $array['a'], $array['lang']);
10699 $tmp->string = $array['string'];
10700 $tmp->forcedstring = $array['forcedstring'];
10701 return $tmp;
10705 * Prepares the lang_string for sleep and stores only the forcedstring and
10706 * string properties... the string cannot be regenerated so we need to ensure
10707 * it is generated for this.
10709 * @return string
10711 public function __sleep() {
10712 $this->get_string();
10713 $this->forcedstring = true;
10714 return array('forcedstring', 'string', 'lang');
10718 * Returns the identifier.
10720 * @return string
10722 public function get_identifier() {
10723 return $this->identifier;
10727 * Returns the component.
10729 * @return string
10731 public function get_component() {
10732 return $this->component;
10737 * Get human readable name describing the given callable.
10739 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10740 * It does not check if the callable actually exists.
10742 * @param callable|string|array $callable
10743 * @return string|bool Human readable name of callable, or false if not a valid callable.
10745 function get_callable_name($callable) {
10747 if (!is_callable($callable, true, $name)) {
10748 return false;
10750 } else {
10751 return $name;
10756 * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10757 * Never put your faith on this function and rely on its accuracy as there might be false positives.
10758 * It just performs some simple checks, and mainly is used for places where we want to hide some options
10759 * such as site registration when $CFG->wwwroot is not publicly accessible.
10760 * Good thing is there is no false negative.
10761 * Note that it's possible to force the result of this check by specifying $CFG->site_is_public in config.php
10763 * @return bool
10765 function site_is_public() {
10766 global $CFG;
10768 // Return early if site admin has forced this setting.
10769 if (isset($CFG->site_is_public)) {
10770 return (bool)$CFG->site_is_public;
10773 $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
10775 if ($host === 'localhost' || preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10776 $ispublic = false;
10777 } else if (\core\ip_utils::is_ip_address($host) && !ip_is_public($host)) {
10778 $ispublic = false;
10779 } else if (($address = \core\ip_utils::get_ip_address($host)) && !ip_is_public($address)) {
10780 $ispublic = false;
10781 } else {
10782 $ispublic = true;
10785 return $ispublic;