MDL-67585 core_course: add content_item_service class
[moodle.git] / lib / moodlelib.php
blob078190be003be15217ae9316134b64bca4c41b6c
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 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 and letters only.
88 define('PARAM_ALPHANUM', 'alphanum');
90 /**
91 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
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 // Blog access level constant declaration.
370 define ('BLOG_USER_LEVEL', 1);
371 define ('BLOG_GROUP_LEVEL', 2);
372 define ('BLOG_COURSE_LEVEL', 3);
373 define ('BLOG_SITE_LEVEL', 4);
374 define ('BLOG_GLOBAL_LEVEL', 5);
377 // Tag constants.
379 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
380 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
381 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
383 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
385 define('TAG_MAX_LENGTH', 50);
387 // Password policy constants.
388 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
389 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
390 define ('PASSWORD_DIGITS', '0123456789');
391 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
393 // Feature constants.
394 // Used for plugin_supports() to report features that are, or are not, supported by a module.
396 /** True if module can provide a grade */
397 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
398 /** True if module supports outcomes */
399 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
400 /** True if module supports advanced grading methods */
401 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
402 /** True if module controls the grade visibility over the gradebook */
403 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
404 /** True if module supports plagiarism plugins */
405 define('FEATURE_PLAGIARISM', 'plagiarism');
407 /** True if module has code to track whether somebody viewed it */
408 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
409 /** True if module has custom completion rules */
410 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
412 /** True if module has no 'view' page (like label) */
413 define('FEATURE_NO_VIEW_LINK', 'viewlink');
414 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
415 define('FEATURE_IDNUMBER', 'idnumber');
416 /** True if module supports groups */
417 define('FEATURE_GROUPS', 'groups');
418 /** True if module supports groupings */
419 define('FEATURE_GROUPINGS', 'groupings');
421 * True if module supports groupmembersonly (which no longer exists)
422 * @deprecated Since Moodle 2.8
424 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
426 /** Type of module */
427 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
428 /** True if module supports intro editor */
429 define('FEATURE_MOD_INTRO', 'mod_intro');
430 /** True if module has default completion */
431 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
433 define('FEATURE_COMMENT', 'comment');
435 define('FEATURE_RATE', 'rate');
436 /** True if module supports backup/restore of moodle2 format */
437 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
439 /** True if module can show description on course main page */
440 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
442 /** True if module uses the question bank */
443 define('FEATURE_USES_QUESTIONS', 'usesquestions');
446 * Maximum filename char size
448 define('MAX_FILENAME_SIZE', 100);
450 /** Unspecified module archetype */
451 define('MOD_ARCHETYPE_OTHER', 0);
452 /** Resource-like type module */
453 define('MOD_ARCHETYPE_RESOURCE', 1);
454 /** Assignment module archetype */
455 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
456 /** System (not user-addable) module archetype */
457 define('MOD_ARCHETYPE_SYSTEM', 3);
460 * Security token used for allowing access
461 * from external application such as web services.
462 * Scripts do not use any session, performance is relatively
463 * low because we need to load access info in each request.
464 * Scripts are executed in parallel.
466 define('EXTERNAL_TOKEN_PERMANENT', 0);
469 * Security token used for allowing access
470 * of embedded applications, the code is executed in the
471 * active user session. Token is invalidated after user logs out.
472 * Scripts are executed serially - normal session locking is used.
474 define('EXTERNAL_TOKEN_EMBEDDED', 1);
477 * The home page should be the site home
479 define('HOMEPAGE_SITE', 0);
481 * The home page should be the users my page
483 define('HOMEPAGE_MY', 1);
485 * The home page can be chosen by the user
487 define('HOMEPAGE_USER', 2);
490 * URL of the Moodle sites registration portal.
492 defined('HUB_MOODLEORGHUBURL') || define('HUB_MOODLEORGHUBURL', 'https://stats.moodle.org');
495 * Moodle mobile app service name
497 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
500 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
502 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
505 * Course display settings: display all sections on one page.
507 define('COURSE_DISPLAY_SINGLEPAGE', 0);
509 * Course display settings: split pages into a page per section.
511 define('COURSE_DISPLAY_MULTIPAGE', 1);
514 * Authentication constant: String used in password field when password is not stored.
516 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
519 * Email from header to never include via information.
521 define('EMAIL_VIA_NEVER', 0);
524 * Email from header to always include via information.
526 define('EMAIL_VIA_ALWAYS', 1);
529 * Email from header to only include via information if the address is no-reply.
531 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
533 // PARAMETER HANDLING.
536 * Returns a particular value for the named variable, taken from
537 * POST or GET. If the parameter doesn't exist then an error is
538 * thrown because we require this variable.
540 * This function should be used to initialise all required values
541 * in a script that are based on parameters. Usually it will be
542 * used like this:
543 * $id = required_param('id', PARAM_INT);
545 * Please note the $type parameter is now required and the value can not be array.
547 * @param string $parname the name of the page parameter we want
548 * @param string $type expected type of parameter
549 * @return mixed
550 * @throws coding_exception
552 function required_param($parname, $type) {
553 if (func_num_args() != 2 or empty($parname) or empty($type)) {
554 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
556 // POST has precedence.
557 if (isset($_POST[$parname])) {
558 $param = $_POST[$parname];
559 } else if (isset($_GET[$parname])) {
560 $param = $_GET[$parname];
561 } else {
562 print_error('missingparam', '', '', $parname);
565 if (is_array($param)) {
566 debugging('Invalid array parameter detected in required_param(): '.$parname);
567 // TODO: switch to fatal error in Moodle 2.3.
568 return required_param_array($parname, $type);
571 return clean_param($param, $type);
575 * Returns a particular array value for the named variable, taken from
576 * POST or GET. If the parameter doesn't exist then an error is
577 * thrown because we require this variable.
579 * This function should be used to initialise all required values
580 * in a script that are based on parameters. Usually it will be
581 * used like this:
582 * $ids = required_param_array('ids', PARAM_INT);
584 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
586 * @param string $parname the name of the page parameter we want
587 * @param string $type expected type of parameter
588 * @return array
589 * @throws coding_exception
591 function required_param_array($parname, $type) {
592 if (func_num_args() != 2 or empty($parname) or empty($type)) {
593 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
595 // POST has precedence.
596 if (isset($_POST[$parname])) {
597 $param = $_POST[$parname];
598 } else if (isset($_GET[$parname])) {
599 $param = $_GET[$parname];
600 } else {
601 print_error('missingparam', '', '', $parname);
603 if (!is_array($param)) {
604 print_error('missingparam', '', '', $parname);
607 $result = array();
608 foreach ($param as $key => $value) {
609 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
610 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
611 continue;
613 $result[$key] = clean_param($value, $type);
616 return $result;
620 * Returns a particular value for the named variable, taken from
621 * POST or GET, otherwise returning a given default.
623 * This function should be used to initialise all optional values
624 * in a script that are based on parameters. Usually it will be
625 * used like this:
626 * $name = optional_param('name', 'Fred', PARAM_TEXT);
628 * Please note the $type parameter is now required and the value can not be array.
630 * @param string $parname the name of the page parameter we want
631 * @param mixed $default the default value to return if nothing is found
632 * @param string $type expected type of parameter
633 * @return mixed
634 * @throws coding_exception
636 function optional_param($parname, $default, $type) {
637 if (func_num_args() != 3 or empty($parname) or empty($type)) {
638 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
641 // POST has precedence.
642 if (isset($_POST[$parname])) {
643 $param = $_POST[$parname];
644 } else if (isset($_GET[$parname])) {
645 $param = $_GET[$parname];
646 } else {
647 return $default;
650 if (is_array($param)) {
651 debugging('Invalid array parameter detected in required_param(): '.$parname);
652 // TODO: switch to $default in Moodle 2.3.
653 return optional_param_array($parname, $default, $type);
656 return clean_param($param, $type);
660 * Returns a particular array value for the named variable, taken from
661 * POST or GET, otherwise returning a given default.
663 * This function should be used to initialise all optional values
664 * in a script that are based on parameters. Usually it will be
665 * used like this:
666 * $ids = optional_param('id', array(), PARAM_INT);
668 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
670 * @param string $parname the name of the page parameter we want
671 * @param mixed $default the default value to return if nothing is found
672 * @param string $type expected type of parameter
673 * @return array
674 * @throws coding_exception
676 function optional_param_array($parname, $default, $type) {
677 if (func_num_args() != 3 or empty($parname) or empty($type)) {
678 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
681 // POST has precedence.
682 if (isset($_POST[$parname])) {
683 $param = $_POST[$parname];
684 } else if (isset($_GET[$parname])) {
685 $param = $_GET[$parname];
686 } else {
687 return $default;
689 if (!is_array($param)) {
690 debugging('optional_param_array() expects array parameters only: '.$parname);
691 return $default;
694 $result = array();
695 foreach ($param as $key => $value) {
696 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
697 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
698 continue;
700 $result[$key] = clean_param($value, $type);
703 return $result;
707 * Strict validation of parameter values, the values are only converted
708 * to requested PHP type. Internally it is using clean_param, the values
709 * before and after cleaning must be equal - otherwise
710 * an invalid_parameter_exception is thrown.
711 * Objects and classes are not accepted.
713 * @param mixed $param
714 * @param string $type PARAM_ constant
715 * @param bool $allownull are nulls valid value?
716 * @param string $debuginfo optional debug information
717 * @return mixed the $param value converted to PHP type
718 * @throws invalid_parameter_exception if $param is not of given type
720 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
721 if (is_null($param)) {
722 if ($allownull == NULL_ALLOWED) {
723 return null;
724 } else {
725 throw new invalid_parameter_exception($debuginfo);
728 if (is_array($param) or is_object($param)) {
729 throw new invalid_parameter_exception($debuginfo);
732 $cleaned = clean_param($param, $type);
734 if ($type == PARAM_FLOAT) {
735 // Do not detect precision loss here.
736 if (is_float($param) or is_int($param)) {
737 // These always fit.
738 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
739 throw new invalid_parameter_exception($debuginfo);
741 } else if ((string)$param !== (string)$cleaned) {
742 // Conversion to string is usually lossless.
743 throw new invalid_parameter_exception($debuginfo);
746 return $cleaned;
750 * Makes sure array contains only the allowed types, this function does not validate array key names!
752 * <code>
753 * $options = clean_param($options, PARAM_INT);
754 * </code>
756 * @param array $param the variable array we are cleaning
757 * @param string $type expected format of param after cleaning.
758 * @param bool $recursive clean recursive arrays
759 * @return array
760 * @throws coding_exception
762 function clean_param_array(array $param = null, $type, $recursive = false) {
763 // Convert null to empty array.
764 $param = (array)$param;
765 foreach ($param as $key => $value) {
766 if (is_array($value)) {
767 if ($recursive) {
768 $param[$key] = clean_param_array($value, $type, true);
769 } else {
770 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
772 } else {
773 $param[$key] = clean_param($value, $type);
776 return $param;
780 * Used by {@link optional_param()} and {@link required_param()} to
781 * clean the variables and/or cast to specific types, based on
782 * an options field.
783 * <code>
784 * $course->format = clean_param($course->format, PARAM_ALPHA);
785 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
786 * </code>
788 * @param mixed $param the variable we are cleaning
789 * @param string $type expected format of param after cleaning.
790 * @return mixed
791 * @throws coding_exception
793 function clean_param($param, $type) {
794 global $CFG;
796 if (is_array($param)) {
797 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
798 } else if (is_object($param)) {
799 if (method_exists($param, '__toString')) {
800 $param = $param->__toString();
801 } else {
802 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
806 switch ($type) {
807 case PARAM_RAW:
808 // No cleaning at all.
809 $param = fix_utf8($param);
810 return $param;
812 case PARAM_RAW_TRIMMED:
813 // No cleaning, but strip leading and trailing whitespace.
814 $param = fix_utf8($param);
815 return trim($param);
817 case PARAM_CLEAN:
818 // General HTML cleaning, try to use more specific type if possible this is deprecated!
819 // Please use more specific type instead.
820 if (is_numeric($param)) {
821 return $param;
823 $param = fix_utf8($param);
824 // Sweep for scripts, etc.
825 return clean_text($param);
827 case PARAM_CLEANHTML:
828 // Clean html fragment.
829 $param = fix_utf8($param);
830 // Sweep for scripts, etc.
831 $param = clean_text($param, FORMAT_HTML);
832 return trim($param);
834 case PARAM_INT:
835 // Convert to integer.
836 return (int)$param;
838 case PARAM_FLOAT:
839 // Convert to float.
840 return (float)$param;
842 case PARAM_LOCALISEDFLOAT:
843 // Convert to float.
844 return unformat_float($param, true);
846 case PARAM_ALPHA:
847 // Remove everything not `a-z`.
848 return preg_replace('/[^a-zA-Z]/i', '', $param);
850 case PARAM_ALPHAEXT:
851 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
852 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
854 case PARAM_ALPHANUM:
855 // Remove everything not `a-zA-Z0-9`.
856 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
858 case PARAM_ALPHANUMEXT:
859 // Remove everything not `a-zA-Z0-9_-`.
860 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
862 case PARAM_SEQUENCE:
863 // Remove everything not `0-9,`.
864 return preg_replace('/[^0-9,]/i', '', $param);
866 case PARAM_BOOL:
867 // Convert to 1 or 0.
868 $tempstr = strtolower($param);
869 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
870 $param = 1;
871 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
872 $param = 0;
873 } else {
874 $param = empty($param) ? 0 : 1;
876 return $param;
878 case PARAM_NOTAGS:
879 // Strip all tags.
880 $param = fix_utf8($param);
881 return strip_tags($param);
883 case PARAM_TEXT:
884 // Leave only tags needed for multilang.
885 $param = fix_utf8($param);
886 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
887 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
888 do {
889 if (strpos($param, '</lang>') !== false) {
890 // Old and future mutilang syntax.
891 $param = strip_tags($param, '<lang>');
892 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
893 break;
895 $open = false;
896 foreach ($matches[0] as $match) {
897 if ($match === '</lang>') {
898 if ($open) {
899 $open = false;
900 continue;
901 } else {
902 break 2;
905 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
906 break 2;
907 } else {
908 $open = true;
911 if ($open) {
912 break;
914 return $param;
916 } else if (strpos($param, '</span>') !== false) {
917 // Current problematic multilang syntax.
918 $param = strip_tags($param, '<span>');
919 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
920 break;
922 $open = false;
923 foreach ($matches[0] as $match) {
924 if ($match === '</span>') {
925 if ($open) {
926 $open = false;
927 continue;
928 } else {
929 break 2;
932 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
933 break 2;
934 } else {
935 $open = true;
938 if ($open) {
939 break;
941 return $param;
943 } while (false);
944 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
945 return strip_tags($param);
947 case PARAM_COMPONENT:
948 // We do not want any guessing here, either the name is correct or not
949 // please note only normalised component names are accepted.
950 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
951 return '';
953 if (strpos($param, '__') !== false) {
954 return '';
956 if (strpos($param, 'mod_') === 0) {
957 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
958 if (substr_count($param, '_') != 1) {
959 return '';
962 return $param;
964 case PARAM_PLUGIN:
965 case PARAM_AREA:
966 // We do not want any guessing here, either the name is correct or not.
967 if (!is_valid_plugin_name($param)) {
968 return '';
970 return $param;
972 case PARAM_SAFEDIR:
973 // Remove everything not a-zA-Z0-9_- .
974 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
976 case PARAM_SAFEPATH:
977 // Remove everything not a-zA-Z0-9/_- .
978 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
980 case PARAM_FILE:
981 // Strip all suspicious characters from filename.
982 $param = fix_utf8($param);
983 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
984 if ($param === '.' || $param === '..') {
985 $param = '';
987 return $param;
989 case PARAM_PATH:
990 // Strip all suspicious characters from file path.
991 $param = fix_utf8($param);
992 $param = str_replace('\\', '/', $param);
994 // Explode the path and clean each element using the PARAM_FILE rules.
995 $breadcrumb = explode('/', $param);
996 foreach ($breadcrumb as $key => $crumb) {
997 if ($crumb === '.' && $key === 0) {
998 // Special condition to allow for relative current path such as ./currentdirfile.txt.
999 } else {
1000 $crumb = clean_param($crumb, PARAM_FILE);
1002 $breadcrumb[$key] = $crumb;
1004 $param = implode('/', $breadcrumb);
1006 // Remove multiple current path (./././) and multiple slashes (///).
1007 $param = preg_replace('~//+~', '/', $param);
1008 $param = preg_replace('~/(\./)+~', '/', $param);
1009 return $param;
1011 case PARAM_HOST:
1012 // Allow FQDN or IPv4 dotted quad.
1013 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1014 // Match ipv4 dotted quad.
1015 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1016 // Confirm values are ok.
1017 if ( $match[0] > 255
1018 || $match[1] > 255
1019 || $match[3] > 255
1020 || $match[4] > 255 ) {
1021 // Hmmm, what kind of dotted quad is this?
1022 $param = '';
1024 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1025 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1026 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1028 // All is ok - $param is respected.
1029 } else {
1030 // All is not ok...
1031 $param='';
1033 return $param;
1035 case PARAM_URL:
1036 // Allow safe urls.
1037 $param = fix_utf8($param);
1038 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1039 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1040 // All is ok, param is respected.
1041 } else {
1042 // Not really ok.
1043 $param ='';
1045 return $param;
1047 case PARAM_LOCALURL:
1048 // Allow http absolute, root relative and relative URLs within wwwroot.
1049 $param = clean_param($param, PARAM_URL);
1050 if (!empty($param)) {
1052 if ($param === $CFG->wwwroot) {
1053 // Exact match;
1054 } else if (preg_match(':^/:', $param)) {
1055 // Root-relative, ok!
1056 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1057 // Absolute, and matches our wwwroot.
1058 } else {
1059 // Relative - let's make sure there are no tricks.
1060 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1061 // Looks ok.
1062 } else {
1063 $param = '';
1067 return $param;
1069 case PARAM_PEM:
1070 $param = trim($param);
1071 // PEM formatted strings may contain letters/numbers and the symbols:
1072 // forward slash: /
1073 // plus sign: +
1074 // equal sign: =
1075 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1076 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1077 list($wholething, $body) = $matches;
1078 unset($wholething, $matches);
1079 $b64 = clean_param($body, PARAM_BASE64);
1080 if (!empty($b64)) {
1081 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1082 } else {
1083 return '';
1086 return '';
1088 case PARAM_BASE64:
1089 if (!empty($param)) {
1090 // PEM formatted strings may contain letters/numbers and the symbols
1091 // forward slash: /
1092 // plus sign: +
1093 // equal sign: =.
1094 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1095 return '';
1097 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1098 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1099 // than (or equal to) 64 characters long.
1100 for ($i=0, $j=count($lines); $i < $j; $i++) {
1101 if ($i + 1 == $j) {
1102 if (64 < strlen($lines[$i])) {
1103 return '';
1105 continue;
1108 if (64 != strlen($lines[$i])) {
1109 return '';
1112 return implode("\n", $lines);
1113 } else {
1114 return '';
1117 case PARAM_TAG:
1118 $param = fix_utf8($param);
1119 // Please note it is not safe to use the tag name directly anywhere,
1120 // it must be processed with s(), urlencode() before embedding anywhere.
1121 // Remove some nasties.
1122 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1123 // Convert many whitespace chars into one.
1124 $param = preg_replace('/\s+/u', ' ', $param);
1125 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1126 return $param;
1128 case PARAM_TAGLIST:
1129 $param = fix_utf8($param);
1130 $tags = explode(',', $param);
1131 $result = array();
1132 foreach ($tags as $tag) {
1133 $res = clean_param($tag, PARAM_TAG);
1134 if ($res !== '') {
1135 $result[] = $res;
1138 if ($result) {
1139 return implode(',', $result);
1140 } else {
1141 return '';
1144 case PARAM_CAPABILITY:
1145 if (get_capability_info($param)) {
1146 return $param;
1147 } else {
1148 return '';
1151 case PARAM_PERMISSION:
1152 $param = (int)$param;
1153 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1154 return $param;
1155 } else {
1156 return CAP_INHERIT;
1159 case PARAM_AUTH:
1160 $param = clean_param($param, PARAM_PLUGIN);
1161 if (empty($param)) {
1162 return '';
1163 } else if (exists_auth_plugin($param)) {
1164 return $param;
1165 } else {
1166 return '';
1169 case PARAM_LANG:
1170 $param = clean_param($param, PARAM_SAFEDIR);
1171 if (get_string_manager()->translation_exists($param)) {
1172 return $param;
1173 } else {
1174 // Specified language is not installed or param malformed.
1175 return '';
1178 case PARAM_THEME:
1179 $param = clean_param($param, PARAM_PLUGIN);
1180 if (empty($param)) {
1181 return '';
1182 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1183 return $param;
1184 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1185 return $param;
1186 } else {
1187 // Specified theme is not installed.
1188 return '';
1191 case PARAM_USERNAME:
1192 $param = fix_utf8($param);
1193 $param = trim($param);
1194 // Convert uppercase to lowercase MDL-16919.
1195 $param = core_text::strtolower($param);
1196 if (empty($CFG->extendedusernamechars)) {
1197 $param = str_replace(" " , "", $param);
1198 // Regular expression, eliminate all chars EXCEPT:
1199 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1200 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1202 return $param;
1204 case PARAM_EMAIL:
1205 $param = fix_utf8($param);
1206 if (validate_email($param)) {
1207 return $param;
1208 } else {
1209 return '';
1212 case PARAM_STRINGID:
1213 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1214 return $param;
1215 } else {
1216 return '';
1219 case PARAM_TIMEZONE:
1220 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1221 $param = fix_utf8($param);
1222 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1223 if (preg_match($timezonepattern, $param)) {
1224 return $param;
1225 } else {
1226 return '';
1229 default:
1230 // Doh! throw error, switched parameters in optional_param or another serious problem.
1231 print_error("unknownparamtype", '', '', $type);
1236 * Whether the PARAM_* type is compatible in RTL.
1238 * Being compatible with RTL means that the data they contain can flow
1239 * from right-to-left or left-to-right without compromising the user experience.
1241 * Take URLs for example, they are not RTL compatible as they should always
1242 * flow from the left to the right. This also applies to numbers, email addresses,
1243 * configuration snippets, base64 strings, etc...
1245 * This function tries to best guess which parameters can contain localised strings.
1247 * @param string $paramtype Constant PARAM_*.
1248 * @return bool
1250 function is_rtl_compatible($paramtype) {
1251 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1255 * Makes sure the data is using valid utf8, invalid characters are discarded.
1257 * Note: this function is not intended for full objects with methods and private properties.
1259 * @param mixed $value
1260 * @return mixed with proper utf-8 encoding
1262 function fix_utf8($value) {
1263 if (is_null($value) or $value === '') {
1264 return $value;
1266 } else if (is_string($value)) {
1267 if ((string)(int)$value === $value) {
1268 // Shortcut.
1269 return $value;
1271 // No null bytes expected in our data, so let's remove it.
1272 $value = str_replace("\0", '', $value);
1274 // Note: this duplicates min_fix_utf8() intentionally.
1275 static $buggyiconv = null;
1276 if ($buggyiconv === null) {
1277 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1280 if ($buggyiconv) {
1281 if (function_exists('mb_convert_encoding')) {
1282 $subst = mb_substitute_character();
1283 mb_substitute_character('');
1284 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1285 mb_substitute_character($subst);
1287 } else {
1288 // Warn admins on admin/index.php page.
1289 $result = $value;
1292 } else {
1293 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1296 return $result;
1298 } else if (is_array($value)) {
1299 foreach ($value as $k => $v) {
1300 $value[$k] = fix_utf8($v);
1302 return $value;
1304 } else if (is_object($value)) {
1305 // Do not modify original.
1306 $value = clone($value);
1307 foreach ($value as $k => $v) {
1308 $value->$k = fix_utf8($v);
1310 return $value;
1312 } else {
1313 // This is some other type, no utf-8 here.
1314 return $value;
1319 * Return true if given value is integer or string with integer value
1321 * @param mixed $value String or Int
1322 * @return bool true if number, false if not
1324 function is_number($value) {
1325 if (is_int($value)) {
1326 return true;
1327 } else if (is_string($value)) {
1328 return ((string)(int)$value) === $value;
1329 } else {
1330 return false;
1335 * Returns host part from url.
1337 * @param string $url full url
1338 * @return string host, null if not found
1340 function get_host_from_url($url) {
1341 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1342 if ($matches) {
1343 return $matches[1];
1345 return null;
1349 * Tests whether anything was returned by text editor
1351 * This function is useful for testing whether something you got back from
1352 * the HTML editor actually contains anything. Sometimes the HTML editor
1353 * appear to be empty, but actually you get back a <br> tag or something.
1355 * @param string $string a string containing HTML.
1356 * @return boolean does the string contain any actual content - that is text,
1357 * images, objects, etc.
1359 function html_is_blank($string) {
1360 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1364 * Set a key in global configuration
1366 * Set a key/value pair in both this session's {@link $CFG} global variable
1367 * and in the 'config' database table for future sessions.
1369 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1370 * In that case it doesn't affect $CFG.
1372 * A NULL value will delete the entry.
1374 * NOTE: this function is called from lib/db/upgrade.php
1376 * @param string $name the key to set
1377 * @param string $value the value to set (without magic quotes)
1378 * @param string $plugin (optional) the plugin scope, default null
1379 * @return bool true or exception
1381 function set_config($name, $value, $plugin=null) {
1382 global $CFG, $DB;
1384 if (empty($plugin)) {
1385 if (!array_key_exists($name, $CFG->config_php_settings)) {
1386 // So it's defined for this invocation at least.
1387 if (is_null($value)) {
1388 unset($CFG->$name);
1389 } else {
1390 // Settings from db are always strings.
1391 $CFG->$name = (string)$value;
1395 if ($DB->get_field('config', 'name', array('name' => $name))) {
1396 if ($value === null) {
1397 $DB->delete_records('config', array('name' => $name));
1398 } else {
1399 $DB->set_field('config', 'value', $value, array('name' => $name));
1401 } else {
1402 if ($value !== null) {
1403 $config = new stdClass();
1404 $config->name = $name;
1405 $config->value = $value;
1406 $DB->insert_record('config', $config, false);
1408 // When setting config during a Behat test (in the CLI script, not in the web browser
1409 // requests), remember which ones are set so that we can clear them later.
1410 if (defined('BEHAT_TEST')) {
1411 if (!property_exists($CFG, 'behat_cli_added_config')) {
1412 $CFG->behat_cli_added_config = [];
1414 $CFG->behat_cli_added_config[$name] = true;
1417 if ($name === 'siteidentifier') {
1418 cache_helper::update_site_identifier($value);
1420 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1421 } else {
1422 // Plugin scope.
1423 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1424 if ($value===null) {
1425 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1426 } else {
1427 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1429 } else {
1430 if ($value !== null) {
1431 $config = new stdClass();
1432 $config->plugin = $plugin;
1433 $config->name = $name;
1434 $config->value = $value;
1435 $DB->insert_record('config_plugins', $config, false);
1438 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1441 return true;
1445 * Get configuration values from the global config table
1446 * or the config_plugins table.
1448 * If called with one parameter, it will load all the config
1449 * variables for one plugin, and return them as an object.
1451 * If called with 2 parameters it will return a string single
1452 * value or false if the value is not found.
1454 * NOTE: this function is called from lib/db/upgrade.php
1456 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1457 * that we need only fetch it once per request.
1458 * @param string $plugin full component name
1459 * @param string $name default null
1460 * @return mixed hash-like object or single value, return false no config found
1461 * @throws dml_exception
1463 function get_config($plugin, $name = null) {
1464 global $CFG, $DB;
1466 static $siteidentifier = null;
1468 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1469 $forced =& $CFG->config_php_settings;
1470 $iscore = true;
1471 $plugin = 'core';
1472 } else {
1473 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1474 $forced =& $CFG->forced_plugin_settings[$plugin];
1475 } else {
1476 $forced = array();
1478 $iscore = false;
1481 if ($siteidentifier === null) {
1482 try {
1483 // This may fail during installation.
1484 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1485 // install the database.
1486 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1487 } catch (dml_exception $ex) {
1488 // Set siteidentifier to false. We don't want to trip this continually.
1489 $siteidentifier = false;
1490 throw $ex;
1494 if (!empty($name)) {
1495 if (array_key_exists($name, $forced)) {
1496 return (string)$forced[$name];
1497 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1498 return $siteidentifier;
1502 $cache = cache::make('core', 'config');
1503 $result = $cache->get($plugin);
1504 if ($result === false) {
1505 // The user is after a recordset.
1506 if (!$iscore) {
1507 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1508 } else {
1509 // This part is not really used any more, but anyway...
1510 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1512 $cache->set($plugin, $result);
1515 if (!empty($name)) {
1516 if (array_key_exists($name, $result)) {
1517 return $result[$name];
1519 return false;
1522 if ($plugin === 'core') {
1523 $result['siteidentifier'] = $siteidentifier;
1526 foreach ($forced as $key => $value) {
1527 if (is_null($value) or is_array($value) or is_object($value)) {
1528 // We do not want any extra mess here, just real settings that could be saved in db.
1529 unset($result[$key]);
1530 } else {
1531 // Convert to string as if it went through the DB.
1532 $result[$key] = (string)$value;
1536 return (object)$result;
1540 * Removes a key from global configuration.
1542 * NOTE: this function is called from lib/db/upgrade.php
1544 * @param string $name the key to set
1545 * @param string $plugin (optional) the plugin scope
1546 * @return boolean whether the operation succeeded.
1548 function unset_config($name, $plugin=null) {
1549 global $CFG, $DB;
1551 if (empty($plugin)) {
1552 unset($CFG->$name);
1553 $DB->delete_records('config', array('name' => $name));
1554 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1555 } else {
1556 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1557 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1560 return true;
1564 * Remove all the config variables for a given plugin.
1566 * NOTE: this function is called from lib/db/upgrade.php
1568 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1569 * @return boolean whether the operation succeeded.
1571 function unset_all_config_for_plugin($plugin) {
1572 global $DB;
1573 // Delete from the obvious config_plugins first.
1574 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1575 // Next delete any suspect settings from config.
1576 $like = $DB->sql_like('name', '?', true, true, false, '|');
1577 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1578 $DB->delete_records_select('config', $like, $params);
1579 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1580 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1582 return true;
1586 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1588 * All users are verified if they still have the necessary capability.
1590 * @param string $value the value of the config setting.
1591 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1592 * @param bool $includeadmins include administrators.
1593 * @return array of user objects.
1595 function get_users_from_config($value, $capability, $includeadmins = true) {
1596 if (empty($value) or $value === '$@NONE@$') {
1597 return array();
1600 // We have to make sure that users still have the necessary capability,
1601 // it should be faster to fetch them all first and then test if they are present
1602 // instead of validating them one-by-one.
1603 $users = get_users_by_capability(context_system::instance(), $capability);
1604 if ($includeadmins) {
1605 $admins = get_admins();
1606 foreach ($admins as $admin) {
1607 $users[$admin->id] = $admin;
1611 if ($value === '$@ALL@$') {
1612 return $users;
1615 $result = array(); // Result in correct order.
1616 $allowed = explode(',', $value);
1617 foreach ($allowed as $uid) {
1618 if (isset($users[$uid])) {
1619 $user = $users[$uid];
1620 $result[$user->id] = $user;
1624 return $result;
1629 * Invalidates browser caches and cached data in temp.
1631 * @return void
1633 function purge_all_caches() {
1634 purge_caches();
1638 * Selectively invalidate different types of cache.
1640 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1641 * areas alone or in combination.
1643 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1644 * 'muc' Purge MUC caches?
1645 * 'theme' Purge theme cache?
1646 * 'lang' Purge language string cache?
1647 * 'js' Purge javascript cache?
1648 * 'filter' Purge text filter cache?
1649 * 'other' Purge all other caches?
1651 function purge_caches($options = []) {
1652 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1653 if (empty(array_filter($options))) {
1654 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1655 } else {
1656 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1658 if ($options['muc']) {
1659 cache_helper::purge_all();
1661 if ($options['theme']) {
1662 theme_reset_all_caches();
1664 if ($options['lang']) {
1665 get_string_manager()->reset_caches();
1667 if ($options['js']) {
1668 js_reset_all_caches();
1670 if ($options['template']) {
1671 template_reset_all_caches();
1673 if ($options['filter']) {
1674 reset_text_filters_cache();
1676 if ($options['other']) {
1677 purge_other_caches();
1682 * Purge all non-MUC caches not otherwise purged in purge_caches.
1684 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1685 * {@link phpunit_util::reset_dataroot()}
1687 function purge_other_caches() {
1688 global $DB, $CFG;
1689 core_text::reset_caches();
1690 if (class_exists('core_plugin_manager')) {
1691 core_plugin_manager::reset_caches();
1694 // Bump up cacherev field for all courses.
1695 try {
1696 increment_revision_number('course', 'cacherev', '');
1697 } catch (moodle_exception $e) {
1698 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1701 $DB->reset_caches();
1703 // Purge all other caches: rss, simplepie, etc.
1704 clearstatcache();
1705 remove_dir($CFG->cachedir.'', true);
1707 // Make sure cache dir is writable, throws exception if not.
1708 make_cache_directory('');
1710 // This is the only place where we purge local caches, we are only adding files there.
1711 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1712 remove_dir($CFG->localcachedir, true);
1713 set_config('localcachedirpurged', time());
1714 make_localcache_directory('', true);
1715 \core\task\manager::clear_static_caches();
1719 * Get volatile flags
1721 * @param string $type
1722 * @param int $changedsince default null
1723 * @return array records array
1725 function get_cache_flags($type, $changedsince = null) {
1726 global $DB;
1728 $params = array('type' => $type, 'expiry' => time());
1729 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1730 if ($changedsince !== null) {
1731 $params['changedsince'] = $changedsince;
1732 $sqlwhere .= " AND timemodified > :changedsince";
1734 $cf = array();
1735 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1736 foreach ($flags as $flag) {
1737 $cf[$flag->name] = $flag->value;
1740 return $cf;
1744 * Get volatile flags
1746 * @param string $type
1747 * @param string $name
1748 * @param int $changedsince default null
1749 * @return string|false The cache flag value or false
1751 function get_cache_flag($type, $name, $changedsince=null) {
1752 global $DB;
1754 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1756 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1757 if ($changedsince !== null) {
1758 $params['changedsince'] = $changedsince;
1759 $sqlwhere .= " AND timemodified > :changedsince";
1762 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1766 * Set a volatile flag
1768 * @param string $type the "type" namespace for the key
1769 * @param string $name the key to set
1770 * @param string $value the value to set (without magic quotes) - null will remove the flag
1771 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1772 * @return bool Always returns true
1774 function set_cache_flag($type, $name, $value, $expiry = null) {
1775 global $DB;
1777 $timemodified = time();
1778 if ($expiry === null || $expiry < $timemodified) {
1779 $expiry = $timemodified + 24 * 60 * 60;
1780 } else {
1781 $expiry = (int)$expiry;
1784 if ($value === null) {
1785 unset_cache_flag($type, $name);
1786 return true;
1789 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1790 // This is a potential problem in DEBUG_DEVELOPER.
1791 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1792 return true; // No need to update.
1794 $f->value = $value;
1795 $f->expiry = $expiry;
1796 $f->timemodified = $timemodified;
1797 $DB->update_record('cache_flags', $f);
1798 } else {
1799 $f = new stdClass();
1800 $f->flagtype = $type;
1801 $f->name = $name;
1802 $f->value = $value;
1803 $f->expiry = $expiry;
1804 $f->timemodified = $timemodified;
1805 $DB->insert_record('cache_flags', $f);
1807 return true;
1811 * Removes a single volatile flag
1813 * @param string $type the "type" namespace for the key
1814 * @param string $name the key to set
1815 * @return bool
1817 function unset_cache_flag($type, $name) {
1818 global $DB;
1819 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1820 return true;
1824 * Garbage-collect volatile flags
1826 * @return bool Always returns true
1828 function gc_cache_flags() {
1829 global $DB;
1830 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1831 return true;
1834 // USER PREFERENCE API.
1837 * Refresh user preference cache. This is used most often for $USER
1838 * object that is stored in session, but it also helps with performance in cron script.
1840 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1842 * @package core
1843 * @category preference
1844 * @access public
1845 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1846 * @param int $cachelifetime Cache life time on the current page (in seconds)
1847 * @throws coding_exception
1848 * @return null
1850 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1851 global $DB;
1852 // Static cache, we need to check on each page load, not only every 2 minutes.
1853 static $loadedusers = array();
1855 if (!isset($user->id)) {
1856 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1859 if (empty($user->id) or isguestuser($user->id)) {
1860 // No permanent storage for not-logged-in users and guest.
1861 if (!isset($user->preference)) {
1862 $user->preference = array();
1864 return;
1867 $timenow = time();
1869 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1870 // Already loaded at least once on this page. Are we up to date?
1871 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1872 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1873 return;
1875 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1876 // No change since the lastcheck on this page.
1877 $user->preference['_lastloaded'] = $timenow;
1878 return;
1882 // OK, so we have to reload all preferences.
1883 $loadedusers[$user->id] = true;
1884 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1885 $user->preference['_lastloaded'] = $timenow;
1889 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1891 * NOTE: internal function, do not call from other code.
1893 * @package core
1894 * @access private
1895 * @param integer $userid the user whose prefs were changed.
1897 function mark_user_preferences_changed($userid) {
1898 global $CFG;
1900 if (empty($userid) or isguestuser($userid)) {
1901 // No cache flags for guest and not-logged-in users.
1902 return;
1905 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1909 * Sets a preference for the specified user.
1911 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1913 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1915 * @package core
1916 * @category preference
1917 * @access public
1918 * @param string $name The key to set as preference for the specified user
1919 * @param string $value The value to set for the $name key in the specified user's
1920 * record, null means delete current value.
1921 * @param stdClass|int|null $user A moodle user object or id, null means current user
1922 * @throws coding_exception
1923 * @return bool Always true or exception
1925 function set_user_preference($name, $value, $user = null) {
1926 global $USER, $DB;
1928 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1929 throw new coding_exception('Invalid preference name in set_user_preference() call');
1932 if (is_null($value)) {
1933 // Null means delete current.
1934 return unset_user_preference($name, $user);
1935 } else if (is_object($value)) {
1936 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1937 } else if (is_array($value)) {
1938 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1940 // Value column maximum length is 1333 characters.
1941 $value = (string)$value;
1942 if (core_text::strlen($value) > 1333) {
1943 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1946 if (is_null($user)) {
1947 $user = $USER;
1948 } else if (isset($user->id)) {
1949 // It is a valid object.
1950 } else if (is_numeric($user)) {
1951 $user = (object)array('id' => (int)$user);
1952 } else {
1953 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1956 check_user_preferences_loaded($user);
1958 if (empty($user->id) or isguestuser($user->id)) {
1959 // No permanent storage for not-logged-in users and guest.
1960 $user->preference[$name] = $value;
1961 return true;
1964 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1965 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1966 // Preference already set to this value.
1967 return true;
1969 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1971 } else {
1972 $preference = new stdClass();
1973 $preference->userid = $user->id;
1974 $preference->name = $name;
1975 $preference->value = $value;
1976 $DB->insert_record('user_preferences', $preference);
1979 // Update value in cache.
1980 $user->preference[$name] = $value;
1981 // Update the $USER in case where we've not a direct reference to $USER.
1982 if ($user !== $USER && $user->id == $USER->id) {
1983 $USER->preference[$name] = $value;
1986 // Set reload flag for other sessions.
1987 mark_user_preferences_changed($user->id);
1989 return true;
1993 * Sets a whole array of preferences for the current user
1995 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1997 * @package core
1998 * @category preference
1999 * @access public
2000 * @param array $prefarray An array of key/value pairs to be set
2001 * @param stdClass|int|null $user A moodle user object or id, null means current user
2002 * @return bool Always true or exception
2004 function set_user_preferences(array $prefarray, $user = null) {
2005 foreach ($prefarray as $name => $value) {
2006 set_user_preference($name, $value, $user);
2008 return true;
2012 * Unsets a preference completely by deleting it from the database
2014 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2016 * @package core
2017 * @category preference
2018 * @access public
2019 * @param string $name The key to unset as preference for the specified user
2020 * @param stdClass|int|null $user A moodle user object or id, null means current user
2021 * @throws coding_exception
2022 * @return bool Always true or exception
2024 function unset_user_preference($name, $user = null) {
2025 global $USER, $DB;
2027 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2028 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2031 if (is_null($user)) {
2032 $user = $USER;
2033 } else if (isset($user->id)) {
2034 // It is a valid object.
2035 } else if (is_numeric($user)) {
2036 $user = (object)array('id' => (int)$user);
2037 } else {
2038 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2041 check_user_preferences_loaded($user);
2043 if (empty($user->id) or isguestuser($user->id)) {
2044 // No permanent storage for not-logged-in user and guest.
2045 unset($user->preference[$name]);
2046 return true;
2049 // Delete from DB.
2050 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2052 // Delete the preference from cache.
2053 unset($user->preference[$name]);
2054 // Update the $USER in case where we've not a direct reference to $USER.
2055 if ($user !== $USER && $user->id == $USER->id) {
2056 unset($USER->preference[$name]);
2059 // Set reload flag for other sessions.
2060 mark_user_preferences_changed($user->id);
2062 return true;
2066 * Used to fetch user preference(s)
2068 * If no arguments are supplied this function will return
2069 * all of the current user preferences as an array.
2071 * If a name is specified then this function
2072 * attempts to return that particular preference value. If
2073 * none is found, then the optional value $default is returned,
2074 * otherwise null.
2076 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2078 * @package core
2079 * @category preference
2080 * @access public
2081 * @param string $name Name of the key to use in finding a preference value
2082 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2083 * @param stdClass|int|null $user A moodle user object or id, null means current user
2084 * @throws coding_exception
2085 * @return string|mixed|null A string containing the value of a single preference. An
2086 * array with all of the preferences or null
2088 function get_user_preferences($name = null, $default = null, $user = null) {
2089 global $USER;
2091 if (is_null($name)) {
2092 // All prefs.
2093 } else if (is_numeric($name) or $name === '_lastloaded') {
2094 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2097 if (is_null($user)) {
2098 $user = $USER;
2099 } else if (isset($user->id)) {
2100 // Is a valid object.
2101 } else if (is_numeric($user)) {
2102 if ($USER->id == $user) {
2103 $user = $USER;
2104 } else {
2105 $user = (object)array('id' => (int)$user);
2107 } else {
2108 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2111 check_user_preferences_loaded($user);
2113 if (empty($name)) {
2114 // All values.
2115 return $user->preference;
2116 } else if (isset($user->preference[$name])) {
2117 // The single string value.
2118 return $user->preference[$name];
2119 } else {
2120 // Default value (null if not specified).
2121 return $default;
2125 // FUNCTIONS FOR HANDLING TIME.
2128 * Given Gregorian date parts in user time produce a GMT timestamp.
2130 * @package core
2131 * @category time
2132 * @param int $year The year part to create timestamp of
2133 * @param int $month The month part to create timestamp of
2134 * @param int $day The day part to create timestamp of
2135 * @param int $hour The hour part to create timestamp of
2136 * @param int $minute The minute part to create timestamp of
2137 * @param int $second The second part to create timestamp of
2138 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2139 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2140 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2141 * applied only if timezone is 99 or string.
2142 * @return int GMT timestamp
2144 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2145 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2146 $date->setDate((int)$year, (int)$month, (int)$day);
2147 $date->setTime((int)$hour, (int)$minute, (int)$second);
2149 $time = $date->getTimestamp();
2151 if ($time === false) {
2152 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2153 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2156 // Moodle BC DST stuff.
2157 if (!$applydst) {
2158 $time += dst_offset_on($time, $timezone);
2161 return $time;
2166 * Format a date/time (seconds) as weeks, days, hours etc as needed
2168 * Given an amount of time in seconds, returns string
2169 * formatted nicely as years, days, hours etc as needed
2171 * @package core
2172 * @category time
2173 * @uses MINSECS
2174 * @uses HOURSECS
2175 * @uses DAYSECS
2176 * @uses YEARSECS
2177 * @param int $totalsecs Time in seconds
2178 * @param stdClass $str Should be a time object
2179 * @return string A nicely formatted date/time string
2181 function format_time($totalsecs, $str = null) {
2183 $totalsecs = abs($totalsecs);
2185 if (!$str) {
2186 // Create the str structure the slow way.
2187 $str = new stdClass();
2188 $str->day = get_string('day');
2189 $str->days = get_string('days');
2190 $str->hour = get_string('hour');
2191 $str->hours = get_string('hours');
2192 $str->min = get_string('min');
2193 $str->mins = get_string('mins');
2194 $str->sec = get_string('sec');
2195 $str->secs = get_string('secs');
2196 $str->year = get_string('year');
2197 $str->years = get_string('years');
2200 $years = floor($totalsecs/YEARSECS);
2201 $remainder = $totalsecs - ($years*YEARSECS);
2202 $days = floor($remainder/DAYSECS);
2203 $remainder = $totalsecs - ($days*DAYSECS);
2204 $hours = floor($remainder/HOURSECS);
2205 $remainder = $remainder - ($hours*HOURSECS);
2206 $mins = floor($remainder/MINSECS);
2207 $secs = $remainder - ($mins*MINSECS);
2209 $ss = ($secs == 1) ? $str->sec : $str->secs;
2210 $sm = ($mins == 1) ? $str->min : $str->mins;
2211 $sh = ($hours == 1) ? $str->hour : $str->hours;
2212 $sd = ($days == 1) ? $str->day : $str->days;
2213 $sy = ($years == 1) ? $str->year : $str->years;
2215 $oyears = '';
2216 $odays = '';
2217 $ohours = '';
2218 $omins = '';
2219 $osecs = '';
2221 if ($years) {
2222 $oyears = $years .' '. $sy;
2224 if ($days) {
2225 $odays = $days .' '. $sd;
2227 if ($hours) {
2228 $ohours = $hours .' '. $sh;
2230 if ($mins) {
2231 $omins = $mins .' '. $sm;
2233 if ($secs) {
2234 $osecs = $secs .' '. $ss;
2237 if ($years) {
2238 return trim($oyears .' '. $odays);
2240 if ($days) {
2241 return trim($odays .' '. $ohours);
2243 if ($hours) {
2244 return trim($ohours .' '. $omins);
2246 if ($mins) {
2247 return trim($omins .' '. $osecs);
2249 if ($secs) {
2250 return $osecs;
2252 return get_string('now');
2256 * Returns a formatted string that represents a date in user time.
2258 * @package core
2259 * @category time
2260 * @param int $date the timestamp in UTC, as obtained from the database.
2261 * @param string $format strftime format. You should probably get this using
2262 * get_string('strftime...', 'langconfig');
2263 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2264 * not 99 then daylight saving will not be added.
2265 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2266 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2267 * If false then the leading zero is maintained.
2268 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2269 * @return string the formatted date/time.
2271 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2272 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2273 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2277 * Returns a html "time" tag with both the exact user date with timezone information
2278 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2280 * @package core
2281 * @category time
2282 * @param int $date the timestamp in UTC, as obtained from the database.
2283 * @param string $format strftime format. You should probably get this using
2284 * get_string('strftime...', 'langconfig');
2285 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2286 * not 99 then daylight saving will not be added.
2287 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2288 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2289 * If false then the leading zero is maintained.
2290 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2291 * @return string the formatted date/time.
2293 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2294 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2295 if (CLI_SCRIPT && !PHPUNIT_TEST) {
2296 return $userdatestr;
2298 $machinedate = new DateTime();
2299 $machinedate->setTimestamp(intval($date));
2300 $machinedate->setTimezone(core_date::get_user_timezone_object());
2302 return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2306 * Returns a formatted date ensuring it is UTF-8.
2308 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2309 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2311 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2312 * @param string $format strftime format.
2313 * @param int|float|string $tz the user timezone
2314 * @return string the formatted date/time.
2315 * @since Moodle 2.3.3
2317 function date_format_string($date, $format, $tz = 99) {
2318 global $CFG;
2320 $localewincharset = null;
2321 // Get the calendar type user is using.
2322 if ($CFG->ostype == 'WINDOWS') {
2323 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2324 $localewincharset = $calendartype->locale_win_charset();
2327 if ($localewincharset) {
2328 $format = core_text::convert($format, 'utf-8', $localewincharset);
2331 date_default_timezone_set(core_date::get_user_timezone($tz));
2332 $datestring = strftime($format, $date);
2333 core_date::set_default_server_timezone();
2335 if ($localewincharset) {
2336 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2339 return $datestring;
2343 * Given a $time timestamp in GMT (seconds since epoch),
2344 * returns an array that represents the Gregorian date in user time
2346 * @package core
2347 * @category time
2348 * @param int $time Timestamp in GMT
2349 * @param float|int|string $timezone user timezone
2350 * @return array An array that represents the date in user time
2352 function usergetdate($time, $timezone=99) {
2353 date_default_timezone_set(core_date::get_user_timezone($timezone));
2354 $result = getdate($time);
2355 core_date::set_default_server_timezone();
2357 return $result;
2361 * Given a GMT timestamp (seconds since epoch), offsets it by
2362 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2364 * NOTE: this function does not include DST properly,
2365 * you should use the PHP date stuff instead!
2367 * @package core
2368 * @category time
2369 * @param int $date Timestamp in GMT
2370 * @param float|int|string $timezone user timezone
2371 * @return int
2373 function usertime($date, $timezone=99) {
2374 $userdate = new DateTime('@' . $date);
2375 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2376 $dst = dst_offset_on($date, $timezone);
2378 return $date - $userdate->getOffset() + $dst;
2382 * Get a formatted string representation of an interval between two unix timestamps.
2384 * E.g.
2385 * $intervalstring = get_time_interval_string(12345600, 12345660);
2386 * Will produce the string:
2387 * '0d 0h 1m'
2389 * @param int $time1 unix timestamp
2390 * @param int $time2 unix timestamp
2391 * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2392 * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2394 function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
2395 $dtdate = new DateTime();
2396 $dtdate->setTimeStamp($time1);
2397 $dtdate2 = new DateTime();
2398 $dtdate2->setTimeStamp($time2);
2399 $interval = $dtdate2->diff($dtdate);
2400 $format = empty($format) ? get_string('dateintervaldayshoursmins', 'langconfig') : $format;
2401 return $interval->format($format);
2405 * Given a time, return the GMT timestamp of the most recent midnight
2406 * for the current user.
2408 * @package core
2409 * @category time
2410 * @param int $date Timestamp in GMT
2411 * @param float|int|string $timezone user timezone
2412 * @return int Returns a GMT timestamp
2414 function usergetmidnight($date, $timezone=99) {
2416 $userdate = usergetdate($date, $timezone);
2418 // Time of midnight of this user's day, in GMT.
2419 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2424 * Returns a string that prints the user's timezone
2426 * @package core
2427 * @category time
2428 * @param float|int|string $timezone user timezone
2429 * @return string
2431 function usertimezone($timezone=99) {
2432 $tz = core_date::get_user_timezone($timezone);
2433 return core_date::get_localised_timezone($tz);
2437 * Returns a float or a string which denotes the user's timezone
2438 * 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)
2439 * means that for this timezone there are also DST rules to be taken into account
2440 * Checks various settings and picks the most dominant of those which have a value
2442 * @package core
2443 * @category time
2444 * @param float|int|string $tz timezone to calculate GMT time offset before
2445 * calculating user timezone, 99 is default user timezone
2446 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2447 * @return float|string
2449 function get_user_timezone($tz = 99) {
2450 global $USER, $CFG;
2452 $timezones = array(
2453 $tz,
2454 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2455 isset($USER->timezone) ? $USER->timezone : 99,
2456 isset($CFG->timezone) ? $CFG->timezone : 99,
2459 $tz = 99;
2461 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2462 foreach ($timezones as $nextvalue) {
2463 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2464 $tz = $nextvalue;
2467 return is_numeric($tz) ? (float) $tz : $tz;
2471 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2472 * - Note: Daylight saving only works for string timezones and not for float.
2474 * @package core
2475 * @category time
2476 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2477 * @param int|float|string $strtimezone user timezone
2478 * @return int
2480 function dst_offset_on($time, $strtimezone = null) {
2481 $tz = core_date::get_user_timezone($strtimezone);
2482 $date = new DateTime('@' . $time);
2483 $date->setTimezone(new DateTimeZone($tz));
2484 if ($date->format('I') == '1') {
2485 if ($tz === 'Australia/Lord_Howe') {
2486 return 1800;
2488 return 3600;
2490 return 0;
2494 * Calculates when the day appears in specific month
2496 * @package core
2497 * @category time
2498 * @param int $startday starting day of the month
2499 * @param int $weekday The day when week starts (normally taken from user preferences)
2500 * @param int $month The month whose day is sought
2501 * @param int $year The year of the month whose day is sought
2502 * @return int
2504 function find_day_in_month($startday, $weekday, $month, $year) {
2505 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2507 $daysinmonth = days_in_month($month, $year);
2508 $daysinweek = count($calendartype->get_weekdays());
2510 if ($weekday == -1) {
2511 // Don't care about weekday, so return:
2512 // abs($startday) if $startday != -1
2513 // $daysinmonth otherwise.
2514 return ($startday == -1) ? $daysinmonth : abs($startday);
2517 // From now on we 're looking for a specific weekday.
2518 // Give "end of month" its actual value, since we know it.
2519 if ($startday == -1) {
2520 $startday = -1 * $daysinmonth;
2523 // Starting from day $startday, the sign is the direction.
2524 if ($startday < 1) {
2525 $startday = abs($startday);
2526 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2528 // This is the last such weekday of the month.
2529 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2530 if ($lastinmonth > $daysinmonth) {
2531 $lastinmonth -= $daysinweek;
2534 // Find the first such weekday <= $startday.
2535 while ($lastinmonth > $startday) {
2536 $lastinmonth -= $daysinweek;
2539 return $lastinmonth;
2540 } else {
2541 $indexweekday = dayofweek($startday, $month, $year);
2543 $diff = $weekday - $indexweekday;
2544 if ($diff < 0) {
2545 $diff += $daysinweek;
2548 // This is the first such weekday of the month equal to or after $startday.
2549 $firstfromindex = $startday + $diff;
2551 return $firstfromindex;
2556 * Calculate the number of days in a given month
2558 * @package core
2559 * @category time
2560 * @param int $month The month whose day count is sought
2561 * @param int $year The year of the month whose day count is sought
2562 * @return int
2564 function days_in_month($month, $year) {
2565 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2566 return $calendartype->get_num_days_in_month($year, $month);
2570 * Calculate the position in the week of a specific calendar day
2572 * @package core
2573 * @category time
2574 * @param int $day The day of the date whose position in the week is sought
2575 * @param int $month The month of the date whose position in the week is sought
2576 * @param int $year The year of the date whose position in the week is sought
2577 * @return int
2579 function dayofweek($day, $month, $year) {
2580 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2581 return $calendartype->get_weekday($year, $month, $day);
2584 // USER AUTHENTICATION AND LOGIN.
2587 * Returns full login url.
2589 * Any form submissions for authentication to this URL must include username,
2590 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2592 * @return string login url
2594 function get_login_url() {
2595 global $CFG;
2597 return "$CFG->wwwroot/login/index.php";
2601 * This function checks that the current user is logged in and has the
2602 * required privileges
2604 * This function checks that the current user is logged in, and optionally
2605 * whether they are allowed to be in a particular course and view a particular
2606 * course module.
2607 * If they are not logged in, then it redirects them to the site login unless
2608 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2609 * case they are automatically logged in as guests.
2610 * If $courseid is given and the user is not enrolled in that course then the
2611 * user is redirected to the course enrolment page.
2612 * If $cm is given and the course module is hidden and the user is not a teacher
2613 * in the course then the user is redirected to the course home page.
2615 * When $cm parameter specified, this function sets page layout to 'module'.
2616 * You need to change it manually later if some other layout needed.
2618 * @package core_access
2619 * @category access
2621 * @param mixed $courseorid id of the course or course object
2622 * @param bool $autologinguest default true
2623 * @param object $cm course module object
2624 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2625 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2626 * in order to keep redirects working properly. MDL-14495
2627 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2628 * @return mixed Void, exit, and die depending on path
2629 * @throws coding_exception
2630 * @throws require_login_exception
2631 * @throws moodle_exception
2633 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2634 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2636 // Must not redirect when byteserving already started.
2637 if (!empty($_SERVER['HTTP_RANGE'])) {
2638 $preventredirect = true;
2641 if (AJAX_SCRIPT) {
2642 // We cannot redirect for AJAX scripts either.
2643 $preventredirect = true;
2646 // Setup global $COURSE, themes, language and locale.
2647 if (!empty($courseorid)) {
2648 if (is_object($courseorid)) {
2649 $course = $courseorid;
2650 } else if ($courseorid == SITEID) {
2651 $course = clone($SITE);
2652 } else {
2653 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2655 if ($cm) {
2656 if ($cm->course != $course->id) {
2657 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2659 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2660 if (!($cm instanceof cm_info)) {
2661 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2662 // db queries so this is not really a performance concern, however it is obviously
2663 // better if you use get_fast_modinfo to get the cm before calling this.
2664 $modinfo = get_fast_modinfo($course);
2665 $cm = $modinfo->get_cm($cm->id);
2668 } else {
2669 // Do not touch global $COURSE via $PAGE->set_course(),
2670 // the reasons is we need to be able to call require_login() at any time!!
2671 $course = $SITE;
2672 if ($cm) {
2673 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2677 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2678 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2679 // risk leading the user back to the AJAX request URL.
2680 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2681 $setwantsurltome = false;
2684 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2685 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2686 if ($preventredirect) {
2687 throw new require_login_session_timeout_exception();
2688 } else {
2689 if ($setwantsurltome) {
2690 $SESSION->wantsurl = qualified_me();
2692 redirect(get_login_url());
2696 // If the user is not even logged in yet then make sure they are.
2697 if (!isloggedin()) {
2698 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2699 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2700 // Misconfigured site guest, just redirect to login page.
2701 redirect(get_login_url());
2702 exit; // Never reached.
2704 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2705 complete_user_login($guest);
2706 $USER->autologinguest = true;
2707 $SESSION->lang = $lang;
2708 } else {
2709 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2710 if ($preventredirect) {
2711 throw new require_login_exception('You are not logged in');
2714 if ($setwantsurltome) {
2715 $SESSION->wantsurl = qualified_me();
2718 $referer = get_local_referer(false);
2719 if (!empty($referer)) {
2720 $SESSION->fromurl = $referer;
2723 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2724 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2725 foreach($authsequence as $authname) {
2726 $authplugin = get_auth_plugin($authname);
2727 $authplugin->pre_loginpage_hook();
2728 if (isloggedin()) {
2729 if ($cm) {
2730 $modinfo = get_fast_modinfo($course);
2731 $cm = $modinfo->get_cm($cm->id);
2733 set_access_log_user();
2734 break;
2738 // If we're still not logged in then go to the login page
2739 if (!isloggedin()) {
2740 redirect(get_login_url());
2741 exit; // Never reached.
2746 // Loginas as redirection if needed.
2747 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2748 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2749 if ($USER->loginascontext->instanceid != $course->id) {
2750 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2755 // Check whether the user should be changing password (but only if it is REALLY them).
2756 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2757 $userauth = get_auth_plugin($USER->auth);
2758 if ($userauth->can_change_password() and !$preventredirect) {
2759 if ($setwantsurltome) {
2760 $SESSION->wantsurl = qualified_me();
2762 if ($changeurl = $userauth->change_password_url()) {
2763 // Use plugin custom url.
2764 redirect($changeurl);
2765 } else {
2766 // Use moodle internal method.
2767 redirect($CFG->wwwroot .'/login/change_password.php');
2769 } else if ($userauth->can_change_password()) {
2770 throw new moodle_exception('forcepasswordchangenotice');
2771 } else {
2772 throw new moodle_exception('nopasswordchangeforced', 'auth');
2776 // Check that the user account is properly set up. If we can't redirect to
2777 // edit their profile and this is not a WS request, perform just the lax check.
2778 // It will allow them to use filepicker on the profile edit page.
2780 if ($preventredirect && !WS_SERVER) {
2781 $usernotfullysetup = user_not_fully_set_up($USER, false);
2782 } else {
2783 $usernotfullysetup = user_not_fully_set_up($USER, true);
2786 if ($usernotfullysetup) {
2787 if ($preventredirect) {
2788 throw new moodle_exception('usernotfullysetup');
2790 if ($setwantsurltome) {
2791 $SESSION->wantsurl = qualified_me();
2793 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2796 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2797 sesskey();
2799 if (\core\session\manager::is_loggedinas()) {
2800 // During a "logged in as" session we should force all content to be cleaned because the
2801 // logged in user will be viewing potentially malicious user generated content.
2802 // See MDL-63786 for more details.
2803 $CFG->forceclean = true;
2806 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2808 // Do not bother admins with any formalities, except for activities pending deletion.
2809 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2810 // Set the global $COURSE.
2811 if ($cm) {
2812 $PAGE->set_cm($cm, $course);
2813 $PAGE->set_pagelayout('incourse');
2814 } else if (!empty($courseorid)) {
2815 $PAGE->set_course($course);
2817 // Set accesstime or the user will appear offline which messes up messaging.
2818 // Do not update access time for webservice or ajax requests.
2819 if (!WS_SERVER && !AJAX_SCRIPT) {
2820 user_accesstime_log($course->id);
2823 foreach ($afterlogins as $plugintype => $plugins) {
2824 foreach ($plugins as $pluginfunction) {
2825 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2828 return;
2831 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2832 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2833 if (!defined('NO_SITEPOLICY_CHECK')) {
2834 define('NO_SITEPOLICY_CHECK', false);
2837 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2838 // Do not test if the script explicitly asked for skipping the site policies check.
2839 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2840 $manager = new \core_privacy\local\sitepolicy\manager();
2841 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2842 if ($preventredirect) {
2843 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2845 if ($setwantsurltome) {
2846 $SESSION->wantsurl = qualified_me();
2848 redirect($policyurl);
2852 // Fetch the system context, the course context, and prefetch its child contexts.
2853 $sysctx = context_system::instance();
2854 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2855 if ($cm) {
2856 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2857 } else {
2858 $cmcontext = null;
2861 // If the site is currently under maintenance, then print a message.
2862 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2863 if ($preventredirect) {
2864 throw new require_login_exception('Maintenance in progress');
2866 $PAGE->set_context(null);
2867 print_maintenance_message();
2870 // Make sure the course itself is not hidden.
2871 if ($course->id == SITEID) {
2872 // Frontpage can not be hidden.
2873 } else {
2874 if (is_role_switched($course->id)) {
2875 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2876 } else {
2877 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2878 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2879 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2880 if ($preventredirect) {
2881 throw new require_login_exception('Course is hidden');
2883 $PAGE->set_context(null);
2884 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2885 // the navigation will mess up when trying to find it.
2886 navigation_node::override_active_url(new moodle_url('/'));
2887 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2892 // Is the user enrolled?
2893 if ($course->id == SITEID) {
2894 // Everybody is enrolled on the frontpage.
2895 } else {
2896 if (\core\session\manager::is_loggedinas()) {
2897 // Make sure the REAL person can access this course first.
2898 $realuser = \core\session\manager::get_realuser();
2899 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2900 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2901 if ($preventredirect) {
2902 throw new require_login_exception('Invalid course login-as access');
2904 $PAGE->set_context(null);
2905 echo $OUTPUT->header();
2906 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2910 $access = false;
2912 if (is_role_switched($course->id)) {
2913 // Ok, user had to be inside this course before the switch.
2914 $access = true;
2916 } else if (is_viewing($coursecontext, $USER)) {
2917 // Ok, no need to mess with enrol.
2918 $access = true;
2920 } else {
2921 if (isset($USER->enrol['enrolled'][$course->id])) {
2922 if ($USER->enrol['enrolled'][$course->id] > time()) {
2923 $access = true;
2924 if (isset($USER->enrol['tempguest'][$course->id])) {
2925 unset($USER->enrol['tempguest'][$course->id]);
2926 remove_temp_course_roles($coursecontext);
2928 } else {
2929 // Expired.
2930 unset($USER->enrol['enrolled'][$course->id]);
2933 if (isset($USER->enrol['tempguest'][$course->id])) {
2934 if ($USER->enrol['tempguest'][$course->id] == 0) {
2935 $access = true;
2936 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2937 $access = true;
2938 } else {
2939 // Expired.
2940 unset($USER->enrol['tempguest'][$course->id]);
2941 remove_temp_course_roles($coursecontext);
2945 if (!$access) {
2946 // Cache not ok.
2947 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2948 if ($until !== false) {
2949 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2950 if ($until == 0) {
2951 $until = ENROL_MAX_TIMESTAMP;
2953 $USER->enrol['enrolled'][$course->id] = $until;
2954 $access = true;
2956 } else if (core_course_category::can_view_course_info($course)) {
2957 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2958 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2959 $enrols = enrol_get_plugins(true);
2960 // First ask all enabled enrol instances in course if they want to auto enrol user.
2961 foreach ($instances as $instance) {
2962 if (!isset($enrols[$instance->enrol])) {
2963 continue;
2965 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2966 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2967 if ($until !== false) {
2968 if ($until == 0) {
2969 $until = ENROL_MAX_TIMESTAMP;
2971 $USER->enrol['enrolled'][$course->id] = $until;
2972 $access = true;
2973 break;
2976 // If not enrolled yet try to gain temporary guest access.
2977 if (!$access) {
2978 foreach ($instances as $instance) {
2979 if (!isset($enrols[$instance->enrol])) {
2980 continue;
2982 // Get a duration for the guest access, a timestamp in the future or false.
2983 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2984 if ($until !== false and $until > time()) {
2985 $USER->enrol['tempguest'][$course->id] = $until;
2986 $access = true;
2987 break;
2991 } else {
2992 // User is not enrolled and is not allowed to browse courses here.
2993 if ($preventredirect) {
2994 throw new require_login_exception('Course is not available');
2996 $PAGE->set_context(null);
2997 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2998 // the navigation will mess up when trying to find it.
2999 navigation_node::override_active_url(new moodle_url('/'));
3000 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3005 if (!$access) {
3006 if ($preventredirect) {
3007 throw new require_login_exception('Not enrolled');
3009 if ($setwantsurltome) {
3010 $SESSION->wantsurl = qualified_me();
3012 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3016 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3017 if ($cm && $cm->deletioninprogress) {
3018 if ($preventredirect) {
3019 throw new moodle_exception('activityisscheduledfordeletion');
3021 require_once($CFG->dirroot . '/course/lib.php');
3022 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3025 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3026 if ($cm && !$cm->uservisible) {
3027 if ($preventredirect) {
3028 throw new require_login_exception('Activity is hidden');
3030 // Get the error message that activity is not available and why (if explanation can be shown to the user).
3031 $PAGE->set_course($course);
3032 $renderer = $PAGE->get_renderer('course');
3033 $message = $renderer->course_section_cm_unavailable_error_message($cm);
3034 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
3037 // Set the global $COURSE.
3038 if ($cm) {
3039 $PAGE->set_cm($cm, $course);
3040 $PAGE->set_pagelayout('incourse');
3041 } else if (!empty($courseorid)) {
3042 $PAGE->set_course($course);
3045 foreach ($afterlogins as $plugintype => $plugins) {
3046 foreach ($plugins as $pluginfunction) {
3047 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3051 // Finally access granted, update lastaccess times.
3052 // Do not update access time for webservice or ajax requests.
3053 if (!WS_SERVER && !AJAX_SCRIPT) {
3054 user_accesstime_log($course->id);
3059 * A convenience function for where we must be logged in as admin
3060 * @return void
3062 function require_admin() {
3063 require_login(null, false);
3064 require_capability('moodle/site:config', context_system::instance());
3068 * This function just makes sure a user is logged out.
3070 * @package core_access
3071 * @category access
3073 function require_logout() {
3074 global $USER, $DB;
3076 if (!isloggedin()) {
3077 // This should not happen often, no need for hooks or events here.
3078 \core\session\manager::terminate_current();
3079 return;
3082 // Execute hooks before action.
3083 $authplugins = array();
3084 $authsequence = get_enabled_auth_plugins();
3085 foreach ($authsequence as $authname) {
3086 $authplugins[$authname] = get_auth_plugin($authname);
3087 $authplugins[$authname]->prelogout_hook();
3090 // Store info that gets removed during logout.
3091 $sid = session_id();
3092 $event = \core\event\user_loggedout::create(
3093 array(
3094 'userid' => $USER->id,
3095 'objectid' => $USER->id,
3096 'other' => array('sessionid' => $sid),
3099 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3100 $event->add_record_snapshot('sessions', $session);
3103 // Clone of $USER object to be used by auth plugins.
3104 $user = fullclone($USER);
3106 // Delete session record and drop $_SESSION content.
3107 \core\session\manager::terminate_current();
3109 // Trigger event AFTER action.
3110 $event->trigger();
3112 // Hook to execute auth plugins redirection after event trigger.
3113 foreach ($authplugins as $authplugin) {
3114 $authplugin->postlogout_hook($user);
3119 * Weaker version of require_login()
3121 * This is a weaker version of {@link require_login()} which only requires login
3122 * when called from within a course rather than the site page, unless
3123 * the forcelogin option is turned on.
3124 * @see require_login()
3126 * @package core_access
3127 * @category access
3129 * @param mixed $courseorid The course object or id in question
3130 * @param bool $autologinguest Allow autologin guests if that is wanted
3131 * @param object $cm Course activity module if known
3132 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3133 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3134 * in order to keep redirects working properly. MDL-14495
3135 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3136 * @return void
3137 * @throws coding_exception
3139 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3140 global $CFG, $PAGE, $SITE;
3141 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3142 or (!is_object($courseorid) and $courseorid == SITEID));
3143 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3144 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3145 // db queries so this is not really a performance concern, however it is obviously
3146 // better if you use get_fast_modinfo to get the cm before calling this.
3147 if (is_object($courseorid)) {
3148 $course = $courseorid;
3149 } else {
3150 $course = clone($SITE);
3152 $modinfo = get_fast_modinfo($course);
3153 $cm = $modinfo->get_cm($cm->id);
3155 if (!empty($CFG->forcelogin)) {
3156 // Login required for both SITE and courses.
3157 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3159 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3160 // Always login for hidden activities.
3161 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3163 } else if (isloggedin() && !isguestuser()) {
3164 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3165 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3167 } else if ($issite) {
3168 // Login for SITE not required.
3169 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3170 if (!empty($courseorid)) {
3171 if (is_object($courseorid)) {
3172 $course = $courseorid;
3173 } else {
3174 $course = clone $SITE;
3176 if ($cm) {
3177 if ($cm->course != $course->id) {
3178 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3180 $PAGE->set_cm($cm, $course);
3181 $PAGE->set_pagelayout('incourse');
3182 } else {
3183 $PAGE->set_course($course);
3185 } else {
3186 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3187 $PAGE->set_course($PAGE->course);
3189 // Do not update access time for webservice or ajax requests.
3190 if (!WS_SERVER && !AJAX_SCRIPT) {
3191 user_accesstime_log(SITEID);
3193 return;
3195 } else {
3196 // Course login always required.
3197 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3202 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3204 * @param string $keyvalue the key value
3205 * @param string $script unique script identifier
3206 * @param int $instance instance id
3207 * @return stdClass the key entry in the user_private_key table
3208 * @since Moodle 3.2
3209 * @throws moodle_exception
3211 function validate_user_key($keyvalue, $script, $instance) {
3212 global $DB;
3214 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3215 print_error('invalidkey');
3218 if (!empty($key->validuntil) and $key->validuntil < time()) {
3219 print_error('expiredkey');
3222 if ($key->iprestriction) {
3223 $remoteaddr = getremoteaddr(null);
3224 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3225 print_error('ipmismatch');
3228 return $key;
3232 * Require key login. Function terminates with error if key not found or incorrect.
3234 * @uses NO_MOODLE_COOKIES
3235 * @uses PARAM_ALPHANUM
3236 * @param string $script unique script identifier
3237 * @param int $instance optional instance id
3238 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3239 * @return int Instance ID
3241 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3242 global $DB;
3244 if (!NO_MOODLE_COOKIES) {
3245 print_error('sessioncookiesdisable');
3248 // Extra safety.
3249 \core\session\manager::write_close();
3251 if (null === $keyvalue) {
3252 $keyvalue = required_param('key', PARAM_ALPHANUM);
3255 $key = validate_user_key($keyvalue, $script, $instance);
3257 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3258 print_error('invaliduserid');
3261 core_user::require_active_user($user, true, true);
3263 // Emulate normal session.
3264 enrol_check_plugins($user);
3265 \core\session\manager::set_user($user);
3267 // Note we are not using normal login.
3268 if (!defined('USER_KEY_LOGIN')) {
3269 define('USER_KEY_LOGIN', true);
3272 // Return instance id - it might be empty.
3273 return $key->instance;
3277 * Creates a new private user access key.
3279 * @param string $script unique target identifier
3280 * @param int $userid
3281 * @param int $instance optional instance id
3282 * @param string $iprestriction optional ip restricted access
3283 * @param int $validuntil key valid only until given data
3284 * @return string access key value
3286 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3287 global $DB;
3289 $key = new stdClass();
3290 $key->script = $script;
3291 $key->userid = $userid;
3292 $key->instance = $instance;
3293 $key->iprestriction = $iprestriction;
3294 $key->validuntil = $validuntil;
3295 $key->timecreated = time();
3297 // Something long and unique.
3298 $key->value = md5($userid.'_'.time().random_string(40));
3299 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3300 // Must be unique.
3301 $key->value = md5($userid.'_'.time().random_string(40));
3303 $DB->insert_record('user_private_key', $key);
3304 return $key->value;
3308 * Delete the user's new private user access keys for a particular script.
3310 * @param string $script unique target identifier
3311 * @param int $userid
3312 * @return void
3314 function delete_user_key($script, $userid) {
3315 global $DB;
3316 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3320 * Gets a private user access key (and creates one if one doesn't exist).
3322 * @param string $script unique target identifier
3323 * @param int $userid
3324 * @param int $instance optional instance id
3325 * @param string $iprestriction optional ip restricted access
3326 * @param int $validuntil key valid only until given date
3327 * @return string access key value
3329 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3330 global $DB;
3332 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3333 'instance' => $instance, 'iprestriction' => $iprestriction,
3334 'validuntil' => $validuntil))) {
3335 return $key->value;
3336 } else {
3337 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3343 * Modify the user table by setting the currently logged in user's last login to now.
3345 * @return bool Always returns true
3347 function update_user_login_times() {
3348 global $USER, $DB;
3350 if (isguestuser()) {
3351 // Do not update guest access times/ips for performance.
3352 return true;
3355 $now = time();
3357 $user = new stdClass();
3358 $user->id = $USER->id;
3360 // Make sure all users that logged in have some firstaccess.
3361 if ($USER->firstaccess == 0) {
3362 $USER->firstaccess = $user->firstaccess = $now;
3365 // Store the previous current as lastlogin.
3366 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3368 $USER->currentlogin = $user->currentlogin = $now;
3370 // Function user_accesstime_log() may not update immediately, better do it here.
3371 $USER->lastaccess = $user->lastaccess = $now;
3372 $USER->lastip = $user->lastip = getremoteaddr();
3374 // Note: do not call user_update_user() here because this is part of the login process,
3375 // the login event means that these fields were updated.
3376 $DB->update_record('user', $user);
3377 return true;
3381 * Determines if a user has completed setting up their account.
3383 * The lax mode (with $strict = false) has been introduced for special cases
3384 * only where we want to skip certain checks intentionally. This is valid in
3385 * certain mnet or ajax scenarios when the user cannot / should not be
3386 * redirected to edit their profile. In most cases, you should perform the
3387 * strict check.
3389 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3390 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3391 * @return bool
3393 function user_not_fully_set_up($user, $strict = true) {
3394 global $CFG;
3395 require_once($CFG->dirroot.'/user/profile/lib.php');
3397 if (isguestuser($user)) {
3398 return false;
3401 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3402 return true;
3405 if ($strict) {
3406 if (empty($user->id)) {
3407 // Strict mode can be used with existing accounts only.
3408 return true;
3410 if (!profile_has_required_custom_fields_set($user->id)) {
3411 return true;
3415 return false;
3419 * Check whether the user has exceeded the bounce threshold
3421 * @param stdClass $user A {@link $USER} object
3422 * @return bool true => User has exceeded bounce threshold
3424 function over_bounce_threshold($user) {
3425 global $CFG, $DB;
3427 if (empty($CFG->handlebounces)) {
3428 return false;
3431 if (empty($user->id)) {
3432 // No real (DB) user, nothing to do here.
3433 return false;
3436 // Set sensible defaults.
3437 if (empty($CFG->minbounces)) {
3438 $CFG->minbounces = 10;
3440 if (empty($CFG->bounceratio)) {
3441 $CFG->bounceratio = .20;
3443 $bouncecount = 0;
3444 $sendcount = 0;
3445 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3446 $bouncecount = $bounce->value;
3448 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3449 $sendcount = $send->value;
3451 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3455 * Used to increment or reset email sent count
3457 * @param stdClass $user object containing an id
3458 * @param bool $reset will reset the count to 0
3459 * @return void
3461 function set_send_count($user, $reset=false) {
3462 global $DB;
3464 if (empty($user->id)) {
3465 // No real (DB) user, nothing to do here.
3466 return;
3469 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3470 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3471 $DB->update_record('user_preferences', $pref);
3472 } else if (!empty($reset)) {
3473 // If it's not there and we're resetting, don't bother. Make a new one.
3474 $pref = new stdClass();
3475 $pref->name = 'email_send_count';
3476 $pref->value = 1;
3477 $pref->userid = $user->id;
3478 $DB->insert_record('user_preferences', $pref, false);
3483 * Increment or reset user's email bounce count
3485 * @param stdClass $user object containing an id
3486 * @param bool $reset will reset the count to 0
3488 function set_bounce_count($user, $reset=false) {
3489 global $DB;
3491 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3492 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3493 $DB->update_record('user_preferences', $pref);
3494 } else if (!empty($reset)) {
3495 // If it's not there and we're resetting, don't bother. Make a new one.
3496 $pref = new stdClass();
3497 $pref->name = 'email_bounce_count';
3498 $pref->value = 1;
3499 $pref->userid = $user->id;
3500 $DB->insert_record('user_preferences', $pref, false);
3505 * Determines if the logged in user is currently moving an activity
3507 * @param int $courseid The id of the course being tested
3508 * @return bool
3510 function ismoving($courseid) {
3511 global $USER;
3513 if (!empty($USER->activitycopy)) {
3514 return ($USER->activitycopycourse == $courseid);
3516 return false;
3520 * Returns a persons full name
3522 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3523 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3524 * specify one.
3526 * @param stdClass $user A {@link $USER} object to get full name of.
3527 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3528 * @return string
3530 function fullname($user, $override=false) {
3531 global $CFG, $SESSION;
3533 if (!isset($user->firstname) and !isset($user->lastname)) {
3534 return '';
3537 // Get all of the name fields.
3538 $allnames = get_all_user_name_fields();
3539 if ($CFG->debugdeveloper) {
3540 foreach ($allnames as $allname) {
3541 if (!property_exists($user, $allname)) {
3542 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3543 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3544 // Message has been sent, no point in sending the message multiple times.
3545 break;
3550 if (!$override) {
3551 if (!empty($CFG->forcefirstname)) {
3552 $user->firstname = $CFG->forcefirstname;
3554 if (!empty($CFG->forcelastname)) {
3555 $user->lastname = $CFG->forcelastname;
3559 if (!empty($SESSION->fullnamedisplay)) {
3560 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3563 $template = null;
3564 // If the fullnamedisplay setting is available, set the template to that.
3565 if (isset($CFG->fullnamedisplay)) {
3566 $template = $CFG->fullnamedisplay;
3568 // If the template is empty, or set to language, return the language string.
3569 if ((empty($template) || $template == 'language') && !$override) {
3570 return get_string('fullnamedisplay', null, $user);
3573 // Check to see if we are displaying according to the alternative full name format.
3574 if ($override) {
3575 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3576 // Default to show just the user names according to the fullnamedisplay string.
3577 return get_string('fullnamedisplay', null, $user);
3578 } else {
3579 // If the override is true, then change the template to use the complete name.
3580 $template = $CFG->alternativefullnameformat;
3584 $requirednames = array();
3585 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3586 foreach ($allnames as $allname) {
3587 if (strpos($template, $allname) !== false) {
3588 $requirednames[] = $allname;
3592 $displayname = $template;
3593 // Switch in the actual data into the template.
3594 foreach ($requirednames as $altname) {
3595 if (isset($user->$altname)) {
3596 // Using empty() on the below if statement causes breakages.
3597 if ((string)$user->$altname == '') {
3598 $displayname = str_replace($altname, 'EMPTY', $displayname);
3599 } else {
3600 $displayname = str_replace($altname, $user->$altname, $displayname);
3602 } else {
3603 $displayname = str_replace($altname, 'EMPTY', $displayname);
3606 // Tidy up any misc. characters (Not perfect, but gets most characters).
3607 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3608 // katakana and parenthesis.
3609 $patterns = array();
3610 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3611 // filled in by a user.
3612 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3613 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3614 // This regular expression is to remove any double spaces in the display name.
3615 $patterns[] = '/\s{2,}/u';
3616 foreach ($patterns as $pattern) {
3617 $displayname = preg_replace($pattern, ' ', $displayname);
3620 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3621 $displayname = trim($displayname);
3622 if (empty($displayname)) {
3623 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3624 // people in general feel is a good setting to fall back on.
3625 $displayname = $user->firstname;
3627 return $displayname;
3631 * A centralised location for the all name fields. Returns an array / sql string snippet.
3633 * @param bool $returnsql True for an sql select field snippet.
3634 * @param string $tableprefix table query prefix to use in front of each field.
3635 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3636 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3637 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3638 * @return array|string All name fields.
3640 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3641 // This array is provided in this order because when called by fullname() (above) if firstname is before
3642 // firstnamephonetic str_replace() will change the wrong placeholder.
3643 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3644 'lastnamephonetic' => 'lastnamephonetic',
3645 'middlename' => 'middlename',
3646 'alternatename' => 'alternatename',
3647 'firstname' => 'firstname',
3648 'lastname' => 'lastname');
3650 // Let's add a prefix to the array of user name fields if provided.
3651 if ($prefix) {
3652 foreach ($alternatenames as $key => $altname) {
3653 $alternatenames[$key] = $prefix . $altname;
3657 // If we want the end result to have firstname and lastname at the front / top of the result.
3658 if ($order) {
3659 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3660 for ($i = 0; $i < 2; $i++) {
3661 // Get the last element.
3662 $lastelement = end($alternatenames);
3663 // Remove it from the array.
3664 unset($alternatenames[$lastelement]);
3665 // Put the element back on the top of the array.
3666 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3670 // Create an sql field snippet if requested.
3671 if ($returnsql) {
3672 if ($tableprefix) {
3673 if ($fieldprefix) {
3674 foreach ($alternatenames as $key => $altname) {
3675 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3677 } else {
3678 foreach ($alternatenames as $key => $altname) {
3679 $alternatenames[$key] = $tableprefix . '.' . $altname;
3683 $alternatenames = implode(',', $alternatenames);
3685 return $alternatenames;
3689 * Reduces lines of duplicated code for getting user name fields.
3691 * See also {@link user_picture::unalias()}
3693 * @param object $addtoobject Object to add user name fields to.
3694 * @param object $secondobject Object that contains user name field information.
3695 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3696 * @param array $additionalfields Additional fields to be matched with data in the second object.
3697 * The key can be set to the user table field name.
3698 * @return object User name fields.
3700 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3701 $fields = get_all_user_name_fields(false, null, $prefix);
3702 if ($additionalfields) {
3703 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3704 // the key is a number and then sets the key to the array value.
3705 foreach ($additionalfields as $key => $value) {
3706 if (is_numeric($key)) {
3707 $additionalfields[$value] = $prefix . $value;
3708 unset($additionalfields[$key]);
3709 } else {
3710 $additionalfields[$key] = $prefix . $value;
3713 $fields = array_merge($fields, $additionalfields);
3715 foreach ($fields as $key => $field) {
3716 // Important that we have all of the user name fields present in the object that we are sending back.
3717 $addtoobject->$key = '';
3718 if (isset($secondobject->$field)) {
3719 $addtoobject->$key = $secondobject->$field;
3722 return $addtoobject;
3726 * Returns an array of values in order of occurance in a provided string.
3727 * The key in the result is the character postion in the string.
3729 * @param array $values Values to be found in the string format
3730 * @param string $stringformat The string which may contain values being searched for.
3731 * @return array An array of values in order according to placement in the string format.
3733 function order_in_string($values, $stringformat) {
3734 $valuearray = array();
3735 foreach ($values as $value) {
3736 $pattern = "/$value\b/";
3737 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3738 if (preg_match($pattern, $stringformat)) {
3739 $replacement = "thing";
3740 // Replace the value with something more unique to ensure we get the right position when using strpos().
3741 $newformat = preg_replace($pattern, $replacement, $stringformat);
3742 $position = strpos($newformat, $replacement);
3743 $valuearray[$position] = $value;
3746 ksort($valuearray);
3747 return $valuearray;
3751 * Checks if current user is shown any extra fields when listing users.
3753 * @param object $context Context
3754 * @param array $already Array of fields that we're going to show anyway
3755 * so don't bother listing them
3756 * @return array Array of field names from user table, not including anything
3757 * listed in $already
3759 function get_extra_user_fields($context, $already = array()) {
3760 global $CFG;
3762 // Only users with permission get the extra fields.
3763 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3764 return array();
3767 // Split showuseridentity on comma (filter needed in case the showuseridentity is empty).
3768 $extra = array_filter(explode(',', $CFG->showuseridentity));
3770 foreach ($extra as $key => $field) {
3771 if (in_array($field, $already)) {
3772 unset($extra[$key]);
3776 // If the identity fields are also among hidden fields, make sure the user can see them.
3777 $hiddenfields = array_filter(explode(',', $CFG->hiddenuserfields));
3778 $hiddenidentifiers = array_intersect($extra, $hiddenfields);
3780 if ($hiddenidentifiers) {
3781 if ($context->get_course_context(false)) {
3782 // We are somewhere inside a course.
3783 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3785 } else {
3786 // We are not inside a course.
3787 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
3790 if (!$canviewhiddenuserfields) {
3791 // Remove hidden identifiers from the list.
3792 $extra = array_diff($extra, $hiddenidentifiers);
3796 // Re-index the entries.
3797 $extra = array_values($extra);
3799 return $extra;
3803 * If the current user is to be shown extra user fields when listing or
3804 * selecting users, returns a string suitable for including in an SQL select
3805 * clause to retrieve those fields.
3807 * @param context $context Context
3808 * @param string $alias Alias of user table, e.g. 'u' (default none)
3809 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3810 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3811 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3813 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3814 $fields = get_extra_user_fields($context, $already);
3815 $result = '';
3816 // Add punctuation for alias.
3817 if ($alias !== '') {
3818 $alias .= '.';
3820 foreach ($fields as $field) {
3821 $result .= ', ' . $alias . $field;
3822 if ($prefix) {
3823 $result .= ' AS ' . $prefix . $field;
3826 return $result;
3830 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3831 * @param string $field Field name, e.g. 'phone1'
3832 * @return string Text description taken from language file, e.g. 'Phone number'
3834 function get_user_field_name($field) {
3835 // Some fields have language strings which are not the same as field name.
3836 switch ($field) {
3837 case 'url' : {
3838 return get_string('webpage');
3840 case 'icq' : {
3841 return get_string('icqnumber');
3843 case 'skype' : {
3844 return get_string('skypeid');
3846 case 'aim' : {
3847 return get_string('aimid');
3849 case 'yahoo' : {
3850 return get_string('yahooid');
3852 case 'msn' : {
3853 return get_string('msnid');
3855 case 'picture' : {
3856 return get_string('pictureofuser');
3859 // Otherwise just use the same lang string.
3860 return get_string($field);
3864 * Returns whether a given authentication plugin exists.
3866 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3867 * @return boolean Whether the plugin is available.
3869 function exists_auth_plugin($auth) {
3870 global $CFG;
3872 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3873 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3875 return false;
3879 * Checks if a given plugin is in the list of enabled authentication plugins.
3881 * @param string $auth Authentication plugin.
3882 * @return boolean Whether the plugin is enabled.
3884 function is_enabled_auth($auth) {
3885 if (empty($auth)) {
3886 return false;
3889 $enabled = get_enabled_auth_plugins();
3891 return in_array($auth, $enabled);
3895 * Returns an authentication plugin instance.
3897 * @param string $auth name of authentication plugin
3898 * @return auth_plugin_base An instance of the required authentication plugin.
3900 function get_auth_plugin($auth) {
3901 global $CFG;
3903 // Check the plugin exists first.
3904 if (! exists_auth_plugin($auth)) {
3905 print_error('authpluginnotfound', 'debug', '', $auth);
3908 // Return auth plugin instance.
3909 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3910 $class = "auth_plugin_$auth";
3911 return new $class;
3915 * Returns array of active auth plugins.
3917 * @param bool $fix fix $CFG->auth if needed
3918 * @return array
3920 function get_enabled_auth_plugins($fix=false) {
3921 global $CFG;
3923 $default = array('manual', 'nologin');
3925 if (empty($CFG->auth)) {
3926 $auths = array();
3927 } else {
3928 $auths = explode(',', $CFG->auth);
3931 if ($fix) {
3932 $auths = array_unique($auths);
3933 foreach ($auths as $k => $authname) {
3934 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3935 unset($auths[$k]);
3938 $newconfig = implode(',', $auths);
3939 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3940 set_config('auth', $newconfig);
3944 return (array_merge($default, $auths));
3948 * Returns true if an internal authentication method is being used.
3949 * if method not specified then, global default is assumed
3951 * @param string $auth Form of authentication required
3952 * @return bool
3954 function is_internal_auth($auth) {
3955 // Throws error if bad $auth.
3956 $authplugin = get_auth_plugin($auth);
3957 return $authplugin->is_internal();
3961 * Returns true if the user is a 'restored' one.
3963 * Used in the login process to inform the user and allow him/her to reset the password
3965 * @param string $username username to be checked
3966 * @return bool
3968 function is_restored_user($username) {
3969 global $CFG, $DB;
3971 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3975 * Returns an array of user fields
3977 * @return array User field/column names
3979 function get_user_fieldnames() {
3980 global $DB;
3982 $fieldarray = $DB->get_columns('user');
3983 unset($fieldarray['id']);
3984 $fieldarray = array_keys($fieldarray);
3986 return $fieldarray;
3990 * Creates a bare-bones user record
3992 * @todo Outline auth types and provide code example
3994 * @param string $username New user's username to add to record
3995 * @param string $password New user's password to add to record
3996 * @param string $auth Form of authentication required
3997 * @return stdClass A complete user object
3999 function create_user_record($username, $password, $auth = 'manual') {
4000 global $CFG, $DB;
4001 require_once($CFG->dirroot.'/user/profile/lib.php');
4002 require_once($CFG->dirroot.'/user/lib.php');
4004 // Just in case check text case.
4005 $username = trim(core_text::strtolower($username));
4007 $authplugin = get_auth_plugin($auth);
4008 $customfields = $authplugin->get_custom_user_profile_fields();
4009 $newuser = new stdClass();
4010 if ($newinfo = $authplugin->get_userinfo($username)) {
4011 $newinfo = truncate_userinfo($newinfo);
4012 foreach ($newinfo as $key => $value) {
4013 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
4014 $newuser->$key = $value;
4019 if (!empty($newuser->email)) {
4020 if (email_is_not_allowed($newuser->email)) {
4021 unset($newuser->email);
4025 if (!isset($newuser->city)) {
4026 $newuser->city = '';
4029 $newuser->auth = $auth;
4030 $newuser->username = $username;
4032 // Fix for MDL-8480
4033 // user CFG lang for user if $newuser->lang is empty
4034 // or $user->lang is not an installed language.
4035 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
4036 $newuser->lang = $CFG->lang;
4038 $newuser->confirmed = 1;
4039 $newuser->lastip = getremoteaddr();
4040 $newuser->timecreated = time();
4041 $newuser->timemodified = $newuser->timecreated;
4042 $newuser->mnethostid = $CFG->mnet_localhost_id;
4044 $newuser->id = user_create_user($newuser, false, false);
4046 // Save user profile data.
4047 profile_save_data($newuser);
4049 $user = get_complete_user_data('id', $newuser->id);
4050 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
4051 set_user_preference('auth_forcepasswordchange', 1, $user);
4053 // Set the password.
4054 update_internal_user_password($user, $password);
4056 // Trigger event.
4057 \core\event\user_created::create_from_userid($newuser->id)->trigger();
4059 return $user;
4063 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4065 * @param string $username user's username to update the record
4066 * @return stdClass A complete user object
4068 function update_user_record($username) {
4069 global $DB, $CFG;
4070 // Just in case check text case.
4071 $username = trim(core_text::strtolower($username));
4073 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
4074 return update_user_record_by_id($oldinfo->id);
4078 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4080 * @param int $id user id
4081 * @return stdClass A complete user object
4083 function update_user_record_by_id($id) {
4084 global $DB, $CFG;
4085 require_once($CFG->dirroot."/user/profile/lib.php");
4086 require_once($CFG->dirroot.'/user/lib.php');
4088 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
4089 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
4091 $newuser = array();
4092 $userauth = get_auth_plugin($oldinfo->auth);
4094 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
4095 $newinfo = truncate_userinfo($newinfo);
4096 $customfields = $userauth->get_custom_user_profile_fields();
4098 foreach ($newinfo as $key => $value) {
4099 $iscustom = in_array($key, $customfields);
4100 if (!$iscustom) {
4101 $key = strtolower($key);
4103 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4104 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4105 // Unknown or must not be changed.
4106 continue;
4108 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
4109 continue;
4111 $confval = $userauth->config->{'field_updatelocal_' . $key};
4112 $lockval = $userauth->config->{'field_lock_' . $key};
4113 if ($confval === 'onlogin') {
4114 // MDL-4207 Don't overwrite modified user profile values with
4115 // empty LDAP values when 'unlocked if empty' is set. The purpose
4116 // of the setting 'unlocked if empty' is to allow the user to fill
4117 // in a value for the selected field _if LDAP is giving
4118 // nothing_ for this field. Thus it makes sense to let this value
4119 // stand in until LDAP is giving a value for this field.
4120 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4121 if ($iscustom || (in_array($key, $userauth->userfields) &&
4122 ((string)$oldinfo->$key !== (string)$value))) {
4123 $newuser[$key] = (string)$value;
4128 if ($newuser) {
4129 $newuser['id'] = $oldinfo->id;
4130 $newuser['timemodified'] = time();
4131 user_update_user((object) $newuser, false, false);
4133 // Save user profile data.
4134 profile_save_data((object) $newuser);
4136 // Trigger event.
4137 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4141 return get_complete_user_data('id', $oldinfo->id);
4145 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4147 * @param array $info Array of user properties to truncate if needed
4148 * @return array The now truncated information that was passed in
4150 function truncate_userinfo(array $info) {
4151 // Define the limits.
4152 $limit = array(
4153 'username' => 100,
4154 'idnumber' => 255,
4155 'firstname' => 100,
4156 'lastname' => 100,
4157 'email' => 100,
4158 'icq' => 15,
4159 'phone1' => 20,
4160 'phone2' => 20,
4161 'institution' => 255,
4162 'department' => 255,
4163 'address' => 255,
4164 'city' => 120,
4165 'country' => 2,
4166 'url' => 255,
4169 // Apply where needed.
4170 foreach (array_keys($info) as $key) {
4171 if (!empty($limit[$key])) {
4172 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4176 return $info;
4180 * Marks user deleted in internal user database and notifies the auth plugin.
4181 * Also unenrols user from all roles and does other cleanup.
4183 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4185 * @param stdClass $user full user object before delete
4186 * @return boolean success
4187 * @throws coding_exception if invalid $user parameter detected
4189 function delete_user(stdClass $user) {
4190 global $CFG, $DB, $SESSION;
4191 require_once($CFG->libdir.'/grouplib.php');
4192 require_once($CFG->libdir.'/gradelib.php');
4193 require_once($CFG->dirroot.'/message/lib.php');
4194 require_once($CFG->dirroot.'/user/lib.php');
4196 // Make sure nobody sends bogus record type as parameter.
4197 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4198 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4201 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4202 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4203 debugging('Attempt to delete unknown user account.');
4204 return false;
4207 // There must be always exactly one guest record, originally the guest account was identified by username only,
4208 // now we use $CFG->siteguest for performance reasons.
4209 if ($user->username === 'guest' or isguestuser($user)) {
4210 debugging('Guest user account can not be deleted.');
4211 return false;
4214 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4215 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4216 if ($user->auth === 'manual' and is_siteadmin($user)) {
4217 debugging('Local administrator accounts can not be deleted.');
4218 return false;
4221 // Allow plugins to use this user object before we completely delete it.
4222 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4223 foreach ($pluginsfunction as $plugintype => $plugins) {
4224 foreach ($plugins as $pluginfunction) {
4225 $pluginfunction($user);
4230 // Keep user record before updating it, as we have to pass this to user_deleted event.
4231 $olduser = clone $user;
4233 // Keep a copy of user context, we need it for event.
4234 $usercontext = context_user::instance($user->id);
4236 // Delete all grades - backup is kept in grade_grades_history table.
4237 grade_user_delete($user->id);
4239 // TODO: remove from cohorts using standard API here.
4241 // Remove user tags.
4242 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4244 // Unconditionally unenrol from all courses.
4245 enrol_user_delete($user);
4247 // Unenrol from all roles in all contexts.
4248 // This might be slow but it is really needed - modules might do some extra cleanup!
4249 role_unassign_all(array('userid' => $user->id));
4251 // Notify the competency subsystem.
4252 \core_competency\api::hook_user_deleted($user->id);
4254 // Now do a brute force cleanup.
4256 // Delete all user events and subscription events.
4257 $DB->delete_records_select('event', 'userid = :userid AND subscriptionid IS NOT NULL', ['userid' => $user->id]);
4259 // Now, delete all calendar subscription from the user.
4260 $DB->delete_records('event_subscriptions', ['userid' => $user->id]);
4262 // Remove from all cohorts.
4263 $DB->delete_records('cohort_members', array('userid' => $user->id));
4265 // Remove from all groups.
4266 $DB->delete_records('groups_members', array('userid' => $user->id));
4268 // Brute force unenrol from all courses.
4269 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4271 // Purge user preferences.
4272 $DB->delete_records('user_preferences', array('userid' => $user->id));
4274 // Purge user extra profile info.
4275 $DB->delete_records('user_info_data', array('userid' => $user->id));
4277 // Purge log of previous password hashes.
4278 $DB->delete_records('user_password_history', array('userid' => $user->id));
4280 // Last course access not necessary either.
4281 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4282 // Remove all user tokens.
4283 $DB->delete_records('external_tokens', array('userid' => $user->id));
4285 // Unauthorise the user for all services.
4286 $DB->delete_records('external_services_users', array('userid' => $user->id));
4288 // Remove users private keys.
4289 $DB->delete_records('user_private_key', array('userid' => $user->id));
4291 // Remove users customised pages.
4292 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4294 // Delete user from $SESSION->bulk_users.
4295 if (isset($SESSION->bulk_users[$user->id])) {
4296 unset($SESSION->bulk_users[$user->id]);
4299 // Force logout - may fail if file based sessions used, sorry.
4300 \core\session\manager::kill_user_sessions($user->id);
4302 // Generate username from email address, or a fake email.
4303 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4304 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
4306 // Workaround for bulk deletes of users with the same email address.
4307 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4308 $delname++;
4311 // Mark internal user record as "deleted".
4312 $updateuser = new stdClass();
4313 $updateuser->id = $user->id;
4314 $updateuser->deleted = 1;
4315 $updateuser->username = $delname; // Remember it just in case.
4316 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4317 $updateuser->idnumber = ''; // Clear this field to free it up.
4318 $updateuser->picture = 0;
4319 $updateuser->timemodified = time();
4321 // Don't trigger update event, as user is being deleted.
4322 user_update_user($updateuser, false, false);
4324 // Delete all content associated with the user context, but not the context itself.
4325 $usercontext->delete_content();
4327 // Delete any search data.
4328 \core_search\manager::context_deleted($usercontext);
4330 // Any plugin that needs to cleanup should register this event.
4331 // Trigger event.
4332 $event = \core\event\user_deleted::create(
4333 array(
4334 'objectid' => $user->id,
4335 'relateduserid' => $user->id,
4336 'context' => $usercontext,
4337 'other' => array(
4338 'username' => $user->username,
4339 'email' => $user->email,
4340 'idnumber' => $user->idnumber,
4341 'picture' => $user->picture,
4342 'mnethostid' => $user->mnethostid
4346 $event->add_record_snapshot('user', $olduser);
4347 $event->trigger();
4349 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4350 // should know about this updated property persisted to the user's table.
4351 $user->timemodified = $updateuser->timemodified;
4353 // Notify auth plugin - do not block the delete even when plugin fails.
4354 $authplugin = get_auth_plugin($user->auth);
4355 $authplugin->user_delete($user);
4357 return true;
4361 * Retrieve the guest user object.
4363 * @return stdClass A {@link $USER} object
4365 function guest_user() {
4366 global $CFG, $DB;
4368 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4369 $newuser->confirmed = 1;
4370 $newuser->lang = $CFG->lang;
4371 $newuser->lastip = getremoteaddr();
4374 return $newuser;
4378 * Authenticates a user against the chosen authentication mechanism
4380 * Given a username and password, this function looks them
4381 * up using the currently selected authentication mechanism,
4382 * and if the authentication is successful, it returns a
4383 * valid $user object from the 'user' table.
4385 * Uses auth_ functions from the currently active auth module
4387 * After authenticate_user_login() returns success, you will need to
4388 * log that the user has logged in, and call complete_user_login() to set
4389 * the session up.
4391 * Note: this function works only with non-mnet accounts!
4393 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4394 * @param string $password User's password
4395 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4396 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4397 * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4398 * @return stdClass|false A {@link $USER} object or false if error
4400 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4401 global $CFG, $DB, $PAGE;
4402 require_once("$CFG->libdir/authlib.php");
4404 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4405 // we have found the user
4407 } else if (!empty($CFG->authloginviaemail)) {
4408 if ($email = clean_param($username, PARAM_EMAIL)) {
4409 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4410 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4411 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4412 if (count($users) === 1) {
4413 // Use email for login only if unique.
4414 $user = reset($users);
4415 $user = get_complete_user_data('id', $user->id);
4416 $username = $user->username;
4418 unset($users);
4422 // Make sure this request came from the login form.
4423 if (!\core\session\manager::validate_login_token($logintoken)) {
4424 $failurereason = AUTH_LOGIN_FAILED;
4426 // Trigger login failed event.
4427 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4428 'other' => array('username' => $username, 'reason' => $failurereason)));
4429 $event->trigger();
4430 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4431 return false;
4434 $authsenabled = get_enabled_auth_plugins();
4436 if ($user) {
4437 // Use manual if auth not set.
4438 $auth = empty($user->auth) ? 'manual' : $user->auth;
4440 if (in_array($user->auth, $authsenabled)) {
4441 $authplugin = get_auth_plugin($user->auth);
4442 $authplugin->pre_user_login_hook($user);
4445 if (!empty($user->suspended)) {
4446 $failurereason = AUTH_LOGIN_SUSPENDED;
4448 // Trigger login failed event.
4449 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4450 'other' => array('username' => $username, 'reason' => $failurereason)));
4451 $event->trigger();
4452 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4453 return false;
4455 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4456 // Legacy way to suspend user.
4457 $failurereason = AUTH_LOGIN_SUSPENDED;
4459 // Trigger login failed event.
4460 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4461 'other' => array('username' => $username, 'reason' => $failurereason)));
4462 $event->trigger();
4463 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4464 return false;
4466 $auths = array($auth);
4468 } else {
4469 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4470 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4471 $failurereason = AUTH_LOGIN_NOUSER;
4473 // Trigger login failed event.
4474 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4475 'reason' => $failurereason)));
4476 $event->trigger();
4477 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4478 return false;
4481 // User does not exist.
4482 $auths = $authsenabled;
4483 $user = new stdClass();
4484 $user->id = 0;
4487 if ($ignorelockout) {
4488 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4489 // or this function is called from a SSO script.
4490 } else if ($user->id) {
4491 // Verify login lockout after other ways that may prevent user login.
4492 if (login_is_lockedout($user)) {
4493 $failurereason = AUTH_LOGIN_LOCKOUT;
4495 // Trigger login failed event.
4496 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4497 'other' => array('username' => $username, 'reason' => $failurereason)));
4498 $event->trigger();
4500 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4501 return false;
4503 } else {
4504 // We can not lockout non-existing accounts.
4507 foreach ($auths as $auth) {
4508 $authplugin = get_auth_plugin($auth);
4510 // On auth fail fall through to the next plugin.
4511 if (!$authplugin->user_login($username, $password)) {
4512 continue;
4515 // Before performing login actions, check if user still passes password policy, if admin setting is enabled.
4516 if (!empty($CFG->passwordpolicycheckonlogin)) {
4517 $errmsg = '';
4518 $passed = check_password_policy($password, $errmsg, $user);
4519 if (!$passed) {
4520 // First trigger event for failure.
4521 $failedevent = \core\event\user_password_policy_failed::create_from_user($user);
4522 $failedevent->trigger();
4524 // If able to change password, set flag and move on.
4525 if ($authplugin->can_change_password()) {
4526 // Check if we are on internal change password page, or service is external, don't show notification.
4527 $internalchangeurl = new moodle_url('/login/change_password.php');
4528 if (!($PAGE->has_set_url() && $internalchangeurl->compare($PAGE->url)) && $authplugin->is_internal()) {
4529 \core\notification::error(get_string('passwordpolicynomatch', '', $errmsg));
4531 set_user_preference('auth_forcepasswordchange', 1, $user);
4532 } else if ($authplugin->can_reset_password()) {
4533 // Else force a reset if possible.
4534 \core\notification::error(get_string('forcepasswordresetnotice', '', $errmsg));
4535 redirect(new moodle_url('/login/forgot_password.php'));
4536 } else {
4537 $notifymsg = get_string('forcepasswordresetfailurenotice', '', $errmsg);
4538 // If support page is set, add link for help.
4539 if (!empty($CFG->supportpage)) {
4540 $link = \html_writer::link($CFG->supportpage, $CFG->supportpage);
4541 $link = \html_writer::tag('p', $link);
4542 $notifymsg .= $link;
4545 // If no change or reset is possible, add a notification for user.
4546 \core\notification::error($notifymsg);
4551 // Successful authentication.
4552 if ($user->id) {
4553 // User already exists in database.
4554 if (empty($user->auth)) {
4555 // For some reason auth isn't set yet.
4556 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4557 $user->auth = $auth;
4560 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4561 // the current hash algorithm while we have access to the user's password.
4562 update_internal_user_password($user, $password);
4564 if ($authplugin->is_synchronised_with_external()) {
4565 // Update user record from external DB.
4566 $user = update_user_record_by_id($user->id);
4568 } else {
4569 // The user is authenticated but user creation may be disabled.
4570 if (!empty($CFG->authpreventaccountcreation)) {
4571 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4573 // Trigger login failed event.
4574 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4575 'reason' => $failurereason)));
4576 $event->trigger();
4578 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4579 $_SERVER['HTTP_USER_AGENT']);
4580 return false;
4581 } else {
4582 $user = create_user_record($username, $password, $auth);
4586 $authplugin->sync_roles($user);
4588 foreach ($authsenabled as $hau) {
4589 $hauth = get_auth_plugin($hau);
4590 $hauth->user_authenticated_hook($user, $username, $password);
4593 if (empty($user->id)) {
4594 $failurereason = AUTH_LOGIN_NOUSER;
4595 // Trigger login failed event.
4596 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4597 'reason' => $failurereason)));
4598 $event->trigger();
4599 return false;
4602 if (!empty($user->suspended)) {
4603 // Just in case some auth plugin suspended account.
4604 $failurereason = AUTH_LOGIN_SUSPENDED;
4605 // Trigger login failed event.
4606 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4607 'other' => array('username' => $username, 'reason' => $failurereason)));
4608 $event->trigger();
4609 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4610 return false;
4613 login_attempt_valid($user);
4614 $failurereason = AUTH_LOGIN_OK;
4615 return $user;
4618 // Failed if all the plugins have failed.
4619 if (debugging('', DEBUG_ALL)) {
4620 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4623 if ($user->id) {
4624 login_attempt_failed($user);
4625 $failurereason = AUTH_LOGIN_FAILED;
4626 // Trigger login failed event.
4627 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4628 'other' => array('username' => $username, 'reason' => $failurereason)));
4629 $event->trigger();
4630 } else {
4631 $failurereason = AUTH_LOGIN_NOUSER;
4632 // Trigger login failed event.
4633 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4634 'reason' => $failurereason)));
4635 $event->trigger();
4638 return false;
4642 * Call to complete the user login process after authenticate_user_login()
4643 * has succeeded. It will setup the $USER variable and other required bits
4644 * and pieces.
4646 * NOTE:
4647 * - It will NOT log anything -- up to the caller to decide what to log.
4648 * - this function does not set any cookies any more!
4650 * @param stdClass $user
4651 * @return stdClass A {@link $USER} object - BC only, do not use
4653 function complete_user_login($user) {
4654 global $CFG, $DB, $USER, $SESSION;
4656 \core\session\manager::login_user($user);
4658 // Reload preferences from DB.
4659 unset($USER->preference);
4660 check_user_preferences_loaded($USER);
4662 // Update login times.
4663 update_user_login_times();
4665 // Extra session prefs init.
4666 set_login_session_preferences();
4668 // Trigger login event.
4669 $event = \core\event\user_loggedin::create(
4670 array(
4671 'userid' => $USER->id,
4672 'objectid' => $USER->id,
4673 'other' => array('username' => $USER->username),
4676 $event->trigger();
4678 // Queue migrating the messaging data, if we need to.
4679 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4680 // Check if there are any legacy messages to migrate.
4681 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4682 \core_message\task\migrate_message_data::queue_task($USER->id);
4683 } else {
4684 set_user_preference('core_message_migrate_data', true, $USER->id);
4688 if (isguestuser()) {
4689 // No need to continue when user is THE guest.
4690 return $USER;
4693 if (CLI_SCRIPT) {
4694 // We can redirect to password change URL only in browser.
4695 return $USER;
4698 // Select password change url.
4699 $userauth = get_auth_plugin($USER->auth);
4701 // Check whether the user should be changing password.
4702 if (get_user_preferences('auth_forcepasswordchange', false)) {
4703 if ($userauth->can_change_password()) {
4704 if ($changeurl = $userauth->change_password_url()) {
4705 redirect($changeurl);
4706 } else {
4707 require_once($CFG->dirroot . '/login/lib.php');
4708 $SESSION->wantsurl = core_login_get_return_url();
4709 redirect($CFG->wwwroot.'/login/change_password.php');
4711 } else {
4712 print_error('nopasswordchangeforced', 'auth');
4715 return $USER;
4719 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4721 * @param string $password String to check.
4722 * @return boolean True if the $password matches the format of an md5 sum.
4724 function password_is_legacy_hash($password) {
4725 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4729 * Compare password against hash stored in user object to determine if it is valid.
4731 * If necessary it also updates the stored hash to the current format.
4733 * @param stdClass $user (Password property may be updated).
4734 * @param string $password Plain text password.
4735 * @return bool True if password is valid.
4737 function validate_internal_user_password($user, $password) {
4738 global $CFG;
4740 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4741 // Internal password is not used at all, it can not validate.
4742 return false;
4745 // If hash isn't a legacy (md5) hash, validate using the library function.
4746 if (!password_is_legacy_hash($user->password)) {
4747 return password_verify($password, $user->password);
4750 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4751 // is valid we can then update it to the new algorithm.
4753 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4754 $validated = false;
4756 if ($user->password === md5($password.$sitesalt)
4757 or $user->password === md5($password)
4758 or $user->password === md5(addslashes($password).$sitesalt)
4759 or $user->password === md5(addslashes($password))) {
4760 // Note: we are intentionally using the addslashes() here because we
4761 // need to accept old password hashes of passwords with magic quotes.
4762 $validated = true;
4764 } else {
4765 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4766 $alt = 'passwordsaltalt'.$i;
4767 if (!empty($CFG->$alt)) {
4768 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4769 $validated = true;
4770 break;
4776 if ($validated) {
4777 // If the password matches the existing md5 hash, update to the
4778 // current hash algorithm while we have access to the user's password.
4779 update_internal_user_password($user, $password);
4782 return $validated;
4786 * Calculate hash for a plain text password.
4788 * @param string $password Plain text password to be hashed.
4789 * @param bool $fasthash If true, use a low cost factor when generating the hash
4790 * This is much faster to generate but makes the hash
4791 * less secure. It is used when lots of hashes need to
4792 * be generated quickly.
4793 * @return string The hashed password.
4795 * @throws moodle_exception If a problem occurs while generating the hash.
4797 function hash_internal_user_password($password, $fasthash = false) {
4798 global $CFG;
4800 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4801 $options = ($fasthash) ? array('cost' => 4) : array();
4803 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4805 if ($generatedhash === false || $generatedhash === null) {
4806 throw new moodle_exception('Failed to generate password hash.');
4809 return $generatedhash;
4813 * Update password hash in user object (if necessary).
4815 * The password is updated if:
4816 * 1. The password has changed (the hash of $user->password is different
4817 * to the hash of $password).
4818 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4819 * md5 algorithm).
4821 * Updating the password will modify the $user object and the database
4822 * record to use the current hashing algorithm.
4823 * It will remove Web Services user tokens too.
4825 * @param stdClass $user User object (password property may be updated).
4826 * @param string $password Plain text password.
4827 * @param bool $fasthash If true, use a low cost factor when generating the hash
4828 * This is much faster to generate but makes the hash
4829 * less secure. It is used when lots of hashes need to
4830 * be generated quickly.
4831 * @return bool Always returns true.
4833 function update_internal_user_password($user, $password, $fasthash = false) {
4834 global $CFG, $DB;
4836 // Figure out what the hashed password should be.
4837 if (!isset($user->auth)) {
4838 debugging('User record in update_internal_user_password() must include field auth',
4839 DEBUG_DEVELOPER);
4840 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4842 $authplugin = get_auth_plugin($user->auth);
4843 if ($authplugin->prevent_local_passwords()) {
4844 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4845 } else {
4846 $hashedpassword = hash_internal_user_password($password, $fasthash);
4849 $algorithmchanged = false;
4851 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4852 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4853 $passwordchanged = ($user->password !== $hashedpassword);
4855 } else if (isset($user->password)) {
4856 // If verification fails then it means the password has changed.
4857 $passwordchanged = !password_verify($password, $user->password);
4858 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4859 } else {
4860 // While creating new user, password in unset in $user object, to avoid
4861 // saving it with user_create()
4862 $passwordchanged = true;
4865 if ($passwordchanged || $algorithmchanged) {
4866 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4867 $user->password = $hashedpassword;
4869 // Trigger event.
4870 $user = $DB->get_record('user', array('id' => $user->id));
4871 \core\event\user_password_updated::create_from_user($user)->trigger();
4873 // Remove WS user tokens.
4874 if (!empty($CFG->passwordchangetokendeletion)) {
4875 require_once($CFG->dirroot.'/webservice/lib.php');
4876 webservice::delete_user_ws_tokens($user->id);
4880 return true;
4884 * Get a complete user record, which includes all the info in the user record.
4886 * Intended for setting as $USER session variable
4888 * @param string $field The user field to be checked for a given value.
4889 * @param string $value The value to match for $field.
4890 * @param int $mnethostid
4891 * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4892 * found. Otherwise, it will just return false.
4893 * @return mixed False, or A {@link $USER} object.
4895 function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4896 global $CFG, $DB;
4898 if (!$field || !$value) {
4899 return false;
4902 // Change the field to lowercase.
4903 $field = core_text::strtolower($field);
4905 // List of case insensitive fields.
4906 $caseinsensitivefields = ['email'];
4908 // Username input is forced to lowercase and should be case sensitive.
4909 if ($field == 'username') {
4910 $value = core_text::strtolower($value);
4913 // Build the WHERE clause for an SQL query.
4914 $params = array('fieldval' => $value);
4916 // Do a case-insensitive query, if necessary.
4917 if (in_array($field, $caseinsensitivefields)) {
4918 $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4919 } else {
4920 $fieldselect = "$field = :fieldval";
4922 $constraints = "$fieldselect AND deleted <> 1";
4924 // If we are loading user data based on anything other than id,
4925 // we must also restrict our search based on mnet host.
4926 if ($field != 'id') {
4927 if (empty($mnethostid)) {
4928 // If empty, we restrict to local users.
4929 $mnethostid = $CFG->mnet_localhost_id;
4932 if (!empty($mnethostid)) {
4933 $params['mnethostid'] = $mnethostid;
4934 $constraints .= " AND mnethostid = :mnethostid";
4937 // Get all the basic user data.
4938 try {
4939 // Make sure that there's only a single record that matches our query.
4940 // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4941 // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4942 $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST);
4943 } catch (dml_exception $exception) {
4944 if ($throwexception) {
4945 throw $exception;
4946 } else {
4947 // Return false when no records or multiple records were found.
4948 return false;
4952 // Get various settings and preferences.
4954 // Preload preference cache.
4955 check_user_preferences_loaded($user);
4957 // Load course enrolment related stuff.
4958 $user->lastcourseaccess = array(); // During last session.
4959 $user->currentcourseaccess = array(); // During current session.
4960 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4961 foreach ($lastaccesses as $lastaccess) {
4962 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4966 $sql = "SELECT g.id, g.courseid
4967 FROM {groups} g, {groups_members} gm
4968 WHERE gm.groupid=g.id AND gm.userid=?";
4970 // This is a special hack to speedup calendar display.
4971 $user->groupmember = array();
4972 if (!isguestuser($user)) {
4973 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4974 foreach ($groups as $group) {
4975 if (!array_key_exists($group->courseid, $user->groupmember)) {
4976 $user->groupmember[$group->courseid] = array();
4978 $user->groupmember[$group->courseid][$group->id] = $group->id;
4983 // Add cohort theme.
4984 if (!empty($CFG->allowcohortthemes)) {
4985 require_once($CFG->dirroot . '/cohort/lib.php');
4986 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4987 $user->cohorttheme = $cohorttheme;
4991 // Add the custom profile fields to the user record.
4992 $user->profile = array();
4993 if (!isguestuser($user)) {
4994 require_once($CFG->dirroot.'/user/profile/lib.php');
4995 profile_load_custom_fields($user);
4998 // Rewrite some variables if necessary.
4999 if (!empty($user->description)) {
5000 // No need to cart all of it around.
5001 $user->description = true;
5003 if (isguestuser($user)) {
5004 // Guest language always same as site.
5005 $user->lang = $CFG->lang;
5006 // Name always in current language.
5007 $user->firstname = get_string('guestuser');
5008 $user->lastname = ' ';
5011 return $user;
5015 * Validate a password against the configured password policy
5017 * @param string $password the password to be checked against the password policy
5018 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
5019 * @param stdClass $user the user object to perform password validation against. Defaults to null if not provided.
5021 * @return bool true if the password is valid according to the policy. false otherwise.
5023 function check_password_policy($password, &$errmsg, $user = null) {
5024 global $CFG;
5026 if (!empty($CFG->passwordpolicy)) {
5027 $errmsg = '';
5028 if (core_text::strlen($password) < $CFG->minpasswordlength) {
5029 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
5031 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
5032 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
5034 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
5035 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
5037 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
5038 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
5040 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
5041 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
5043 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
5044 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
5048 // Fire any additional password policy functions from plugins.
5049 // Plugin functions should output an error message string or empty string for success.
5050 $pluginsfunction = get_plugins_with_function('check_password_policy');
5051 foreach ($pluginsfunction as $plugintype => $plugins) {
5052 foreach ($plugins as $pluginfunction) {
5053 $pluginerr = $pluginfunction($password, $user);
5054 if ($pluginerr) {
5055 $errmsg .= '<div>'. $pluginerr .'</div>';
5060 if ($errmsg == '') {
5061 return true;
5062 } else {
5063 return false;
5069 * When logging in, this function is run to set certain preferences for the current SESSION.
5071 function set_login_session_preferences() {
5072 global $SESSION;
5074 $SESSION->justloggedin = true;
5076 unset($SESSION->lang);
5077 unset($SESSION->forcelang);
5078 unset($SESSION->load_navigation_admin);
5083 * Delete a course, including all related data from the database, and any associated files.
5085 * @param mixed $courseorid The id of the course or course object to delete.
5086 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5087 * @return bool true if all the removals succeeded. false if there were any failures. If this
5088 * method returns false, some of the removals will probably have succeeded, and others
5089 * failed, but you have no way of knowing which.
5091 function delete_course($courseorid, $showfeedback = true) {
5092 global $DB;
5094 if (is_object($courseorid)) {
5095 $courseid = $courseorid->id;
5096 $course = $courseorid;
5097 } else {
5098 $courseid = $courseorid;
5099 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
5100 return false;
5103 $context = context_course::instance($courseid);
5105 // Frontpage course can not be deleted!!
5106 if ($courseid == SITEID) {
5107 return false;
5110 // Allow plugins to use this course before we completely delete it.
5111 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
5112 foreach ($pluginsfunction as $plugintype => $plugins) {
5113 foreach ($plugins as $pluginfunction) {
5114 $pluginfunction($course);
5119 // Tell the search manager we are about to delete a course. This prevents us sending updates
5120 // for each individual context being deleted.
5121 \core_search\manager::course_deleting_start($courseid);
5123 $handler = core_course\customfield\course_handler::create();
5124 $handler->delete_instance($courseid);
5126 // Make the course completely empty.
5127 remove_course_contents($courseid, $showfeedback);
5129 // Delete the course and related context instance.
5130 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
5132 $DB->delete_records("course", array("id" => $courseid));
5133 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5135 // Reset all course related caches here.
5136 if (class_exists('format_base', false)) {
5137 format_base::reset_course_cache($courseid);
5140 // Tell search that we have deleted the course so it can delete course data from the index.
5141 \core_search\manager::course_deleting_finish($courseid);
5143 // Trigger a course deleted event.
5144 $event = \core\event\course_deleted::create(array(
5145 'objectid' => $course->id,
5146 'context' => $context,
5147 'other' => array(
5148 'shortname' => $course->shortname,
5149 'fullname' => $course->fullname,
5150 'idnumber' => $course->idnumber
5153 $event->add_record_snapshot('course', $course);
5154 $event->trigger();
5156 return true;
5160 * Clear a course out completely, deleting all content but don't delete the course itself.
5162 * This function does not verify any permissions.
5164 * Please note this function also deletes all user enrolments,
5165 * enrolment instances and role assignments by default.
5167 * $options:
5168 * - 'keep_roles_and_enrolments' - false by default
5169 * - 'keep_groups_and_groupings' - false by default
5171 * @param int $courseid The id of the course that is being deleted
5172 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5173 * @param array $options extra options
5174 * @return bool true if all the removals succeeded. false if there were any failures. If this
5175 * method returns false, some of the removals will probably have succeeded, and others
5176 * failed, but you have no way of knowing which.
5178 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5179 global $CFG, $DB, $OUTPUT;
5181 require_once($CFG->libdir.'/badgeslib.php');
5182 require_once($CFG->libdir.'/completionlib.php');
5183 require_once($CFG->libdir.'/questionlib.php');
5184 require_once($CFG->libdir.'/gradelib.php');
5185 require_once($CFG->dirroot.'/group/lib.php');
5186 require_once($CFG->dirroot.'/comment/lib.php');
5187 require_once($CFG->dirroot.'/rating/lib.php');
5188 require_once($CFG->dirroot.'/notes/lib.php');
5190 // Handle course badges.
5191 badges_handle_course_deletion($courseid);
5193 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5194 $strdeleted = get_string('deleted').' - ';
5196 // Some crazy wishlist of stuff we should skip during purging of course content.
5197 $options = (array)$options;
5199 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5200 $coursecontext = context_course::instance($courseid);
5201 $fs = get_file_storage();
5203 // Delete course completion information, this has to be done before grades and enrols.
5204 $cc = new completion_info($course);
5205 $cc->clear_criteria();
5206 if ($showfeedback) {
5207 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5210 // Remove all data from gradebook - this needs to be done before course modules
5211 // because while deleting this information, the system may need to reference
5212 // the course modules that own the grades.
5213 remove_course_grades($courseid, $showfeedback);
5214 remove_grade_letters($coursecontext, $showfeedback);
5216 // Delete course blocks in any all child contexts,
5217 // they may depend on modules so delete them first.
5218 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5219 foreach ($childcontexts as $childcontext) {
5220 blocks_delete_all_for_context($childcontext->id);
5222 unset($childcontexts);
5223 blocks_delete_all_for_context($coursecontext->id);
5224 if ($showfeedback) {
5225 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5228 // Get the list of all modules that are properly installed.
5229 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5231 // Delete every instance of every module,
5232 // this has to be done before deleting of course level stuff.
5233 $locations = core_component::get_plugin_list('mod');
5234 foreach ($locations as $modname => $moddir) {
5235 if ($modname === 'NEWMODULE') {
5236 continue;
5238 if (array_key_exists($modname, $allmodules)) {
5239 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5240 FROM {".$modname."} m
5241 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5242 WHERE m.course = :courseid";
5243 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5244 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5246 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5247 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5249 if ($instances) {
5250 foreach ($instances as $cm) {
5251 if ($cm->id) {
5252 // Delete activity context questions and question categories.
5253 question_delete_activity($cm, $showfeedback);
5254 // Notify the competency subsystem.
5255 \core_competency\api::hook_course_module_deleted($cm);
5257 if (function_exists($moddelete)) {
5258 // This purges all module data in related tables, extra user prefs, settings, etc.
5259 $moddelete($cm->modinstance);
5260 } else {
5261 // NOTE: we should not allow installation of modules with missing delete support!
5262 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5263 $DB->delete_records($modname, array('id' => $cm->modinstance));
5266 if ($cm->id) {
5267 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5268 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5269 $DB->delete_records('course_modules', array('id' => $cm->id));
5273 if ($instances and $showfeedback) {
5274 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5276 } else {
5277 // Ooops, this module is not properly installed, force-delete it in the next block.
5281 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5283 // Delete completion defaults.
5284 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5286 // Remove all data from availability and completion tables that is associated
5287 // with course-modules belonging to this course. Note this is done even if the
5288 // features are not enabled now, in case they were enabled previously.
5289 $DB->delete_records_select('course_modules_completion',
5290 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5291 array($courseid));
5293 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5294 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5295 $allmodulesbyid = array_flip($allmodules);
5296 foreach ($cms as $cm) {
5297 if (array_key_exists($cm->module, $allmodulesbyid)) {
5298 try {
5299 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5300 } catch (Exception $e) {
5301 // Ignore weird or missing table problems.
5304 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5305 $DB->delete_records('course_modules', array('id' => $cm->id));
5308 if ($showfeedback) {
5309 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5312 // Delete questions and question categories.
5313 question_delete_course($course, $showfeedback);
5314 if ($showfeedback) {
5315 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5318 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5319 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5320 foreach ($childcontexts as $childcontext) {
5321 $childcontext->delete();
5323 unset($childcontexts);
5325 // Remove all roles and enrolments by default.
5326 if (empty($options['keep_roles_and_enrolments'])) {
5327 // This hack is used in restore when deleting contents of existing course.
5328 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5329 enrol_course_delete($course);
5330 if ($showfeedback) {
5331 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5335 // Delete any groups, removing members and grouping/course links first.
5336 if (empty($options['keep_groups_and_groupings'])) {
5337 groups_delete_groupings($course->id, $showfeedback);
5338 groups_delete_groups($course->id, $showfeedback);
5341 // Filters be gone!
5342 filter_delete_all_for_context($coursecontext->id);
5344 // Notes, you shall not pass!
5345 note_delete_all($course->id);
5347 // Die comments!
5348 comment::delete_comments($coursecontext->id);
5350 // Ratings are history too.
5351 $delopt = new stdclass();
5352 $delopt->contextid = $coursecontext->id;
5353 $rm = new rating_manager();
5354 $rm->delete_ratings($delopt);
5356 // Delete course tags.
5357 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5359 // Notify the competency subsystem.
5360 \core_competency\api::hook_course_deleted($course);
5362 // Delete calendar events.
5363 $DB->delete_records('event', array('courseid' => $course->id));
5364 $fs->delete_area_files($coursecontext->id, 'calendar');
5366 // Delete all related records in other core tables that may have a courseid
5367 // This array stores the tables that need to be cleared, as
5368 // table_name => column_name that contains the course id.
5369 $tablestoclear = array(
5370 'backup_courses' => 'courseid', // Scheduled backup stuff.
5371 'user_lastaccess' => 'courseid', // User access info.
5373 foreach ($tablestoclear as $table => $col) {
5374 $DB->delete_records($table, array($col => $course->id));
5377 // Delete all course backup files.
5378 $fs->delete_area_files($coursecontext->id, 'backup');
5380 // Cleanup course record - remove links to deleted stuff.
5381 $oldcourse = new stdClass();
5382 $oldcourse->id = $course->id;
5383 $oldcourse->summary = '';
5384 $oldcourse->cacherev = 0;
5385 $oldcourse->legacyfiles = 0;
5386 if (!empty($options['keep_groups_and_groupings'])) {
5387 $oldcourse->defaultgroupingid = 0;
5389 $DB->update_record('course', $oldcourse);
5391 // Delete course sections.
5392 $DB->delete_records('course_sections', array('course' => $course->id));
5394 // Delete legacy, section and any other course files.
5395 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5397 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5398 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5399 // Easy, do not delete the context itself...
5400 $coursecontext->delete_content();
5401 } else {
5402 // Hack alert!!!!
5403 // We can not drop all context stuff because it would bork enrolments and roles,
5404 // there might be also files used by enrol plugins...
5407 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5408 // also some non-standard unsupported plugins may try to store something there.
5409 fulldelete($CFG->dataroot.'/'.$course->id);
5411 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5412 $cachemodinfo = cache::make('core', 'coursemodinfo');
5413 $cachemodinfo->delete($courseid);
5415 // Trigger a course content deleted event.
5416 $event = \core\event\course_content_deleted::create(array(
5417 'objectid' => $course->id,
5418 'context' => $coursecontext,
5419 'other' => array('shortname' => $course->shortname,
5420 'fullname' => $course->fullname,
5421 'options' => $options) // Passing this for legacy reasons.
5423 $event->add_record_snapshot('course', $course);
5424 $event->trigger();
5426 return true;
5430 * Change dates in module - used from course reset.
5432 * @param string $modname forum, assignment, etc
5433 * @param array $fields array of date fields from mod table
5434 * @param int $timeshift time difference
5435 * @param int $courseid
5436 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5437 * @return bool success
5439 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5440 global $CFG, $DB;
5441 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5443 $return = true;
5444 $params = array($timeshift, $courseid);
5445 foreach ($fields as $field) {
5446 $updatesql = "UPDATE {".$modname."}
5447 SET $field = $field + ?
5448 WHERE course=? AND $field<>0";
5449 if ($modid) {
5450 $updatesql .= ' AND id=?';
5451 $params[] = $modid;
5453 $return = $DB->execute($updatesql, $params) && $return;
5456 return $return;
5460 * This function will empty a course of user data.
5461 * It will retain the activities and the structure of the course.
5463 * @param object $data an object containing all the settings including courseid (without magic quotes)
5464 * @return array status array of array component, item, error
5466 function reset_course_userdata($data) {
5467 global $CFG, $DB;
5468 require_once($CFG->libdir.'/gradelib.php');
5469 require_once($CFG->libdir.'/completionlib.php');
5470 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5471 require_once($CFG->dirroot.'/group/lib.php');
5473 $data->courseid = $data->id;
5474 $context = context_course::instance($data->courseid);
5476 $eventparams = array(
5477 'context' => $context,
5478 'courseid' => $data->id,
5479 'other' => array(
5480 'reset_options' => (array) $data
5483 $event = \core\event\course_reset_started::create($eventparams);
5484 $event->trigger();
5486 // Calculate the time shift of dates.
5487 if (!empty($data->reset_start_date)) {
5488 // Time part of course startdate should be zero.
5489 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5490 } else {
5491 $data->timeshift = 0;
5494 // Result array: component, item, error.
5495 $status = array();
5497 // Start the resetting.
5498 $componentstr = get_string('general');
5500 // Move the course start time.
5501 if (!empty($data->reset_start_date) and $data->timeshift) {
5502 // Change course start data.
5503 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5504 // Update all course and group events - do not move activity events.
5505 $updatesql = "UPDATE {event}
5506 SET timestart = timestart + ?
5507 WHERE courseid=? AND instance=0";
5508 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5510 // Update any date activity restrictions.
5511 if ($CFG->enableavailability) {
5512 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5515 // Update completion expected dates.
5516 if ($CFG->enablecompletion) {
5517 $modinfo = get_fast_modinfo($data->courseid);
5518 $changed = false;
5519 foreach ($modinfo->get_cms() as $cm) {
5520 if ($cm->completion && !empty($cm->completionexpected)) {
5521 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5522 array('id' => $cm->id));
5523 $changed = true;
5527 // Clear course cache if changes made.
5528 if ($changed) {
5529 rebuild_course_cache($data->courseid, true);
5532 // Update course date completion criteria.
5533 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5536 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5539 if (!empty($data->reset_end_date)) {
5540 // If the user set a end date value respect it.
5541 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5542 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5543 // If there is a time shift apply it to the end date as well.
5544 $enddate = $data->reset_end_date_old + $data->timeshift;
5545 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5548 if (!empty($data->reset_events)) {
5549 $DB->delete_records('event', array('courseid' => $data->courseid));
5550 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5553 if (!empty($data->reset_notes)) {
5554 require_once($CFG->dirroot.'/notes/lib.php');
5555 note_delete_all($data->courseid);
5556 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5559 if (!empty($data->delete_blog_associations)) {
5560 require_once($CFG->dirroot.'/blog/lib.php');
5561 blog_remove_associations_for_course($data->courseid);
5562 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5565 if (!empty($data->reset_completion)) {
5566 // Delete course and activity completion information.
5567 $course = $DB->get_record('course', array('id' => $data->courseid));
5568 $cc = new completion_info($course);
5569 $cc->delete_all_completion_data();
5570 $status[] = array('component' => $componentstr,
5571 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5574 if (!empty($data->reset_competency_ratings)) {
5575 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5576 $status[] = array('component' => $componentstr,
5577 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5580 $componentstr = get_string('roles');
5582 if (!empty($data->reset_roles_overrides)) {
5583 $children = $context->get_child_contexts();
5584 foreach ($children as $child) {
5585 $child->delete_capabilities();
5587 $context->delete_capabilities();
5588 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5591 if (!empty($data->reset_roles_local)) {
5592 $children = $context->get_child_contexts();
5593 foreach ($children as $child) {
5594 role_unassign_all(array('contextid' => $child->id));
5596 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5599 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5600 $data->unenrolled = array();
5601 if (!empty($data->unenrol_users)) {
5602 $plugins = enrol_get_plugins(true);
5603 $instances = enrol_get_instances($data->courseid, true);
5604 foreach ($instances as $key => $instance) {
5605 if (!isset($plugins[$instance->enrol])) {
5606 unset($instances[$key]);
5607 continue;
5611 $usersroles = enrol_get_course_users_roles($data->courseid);
5612 foreach ($data->unenrol_users as $withroleid) {
5613 if ($withroleid) {
5614 $sql = "SELECT ue.*
5615 FROM {user_enrolments} ue
5616 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5617 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5618 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5619 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5621 } else {
5622 // Without any role assigned at course context.
5623 $sql = "SELECT ue.*
5624 FROM {user_enrolments} ue
5625 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5626 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5627 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5628 WHERE ra.id IS null";
5629 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5632 $rs = $DB->get_recordset_sql($sql, $params);
5633 foreach ($rs as $ue) {
5634 if (!isset($instances[$ue->enrolid])) {
5635 continue;
5637 $instance = $instances[$ue->enrolid];
5638 $plugin = $plugins[$instance->enrol];
5639 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5640 continue;
5643 if ($withroleid && count($usersroles[$ue->userid]) > 1) {
5644 // If we don't remove all roles and user has more than one role, just remove this role.
5645 role_unassign($withroleid, $ue->userid, $context->id);
5647 unset($usersroles[$ue->userid][$withroleid]);
5648 } else {
5649 // If we remove all roles or user has only one role, unenrol user from course.
5650 $plugin->unenrol_user($instance, $ue->userid);
5652 $data->unenrolled[$ue->userid] = $ue->userid;
5654 $rs->close();
5657 if (!empty($data->unenrolled)) {
5658 $status[] = array(
5659 'component' => $componentstr,
5660 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5661 'error' => false
5665 $componentstr = get_string('groups');
5667 // Remove all group members.
5668 if (!empty($data->reset_groups_members)) {
5669 groups_delete_group_members($data->courseid);
5670 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5673 // Remove all groups.
5674 if (!empty($data->reset_groups_remove)) {
5675 groups_delete_groups($data->courseid, false);
5676 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5679 // Remove all grouping members.
5680 if (!empty($data->reset_groupings_members)) {
5681 groups_delete_groupings_groups($data->courseid, false);
5682 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5685 // Remove all groupings.
5686 if (!empty($data->reset_groupings_remove)) {
5687 groups_delete_groupings($data->courseid, false);
5688 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5691 // Look in every instance of every module for data to delete.
5692 $unsupportedmods = array();
5693 if ($allmods = $DB->get_records('modules') ) {
5694 foreach ($allmods as $mod) {
5695 $modname = $mod->name;
5696 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5697 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5698 if (file_exists($modfile)) {
5699 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5700 continue; // Skip mods with no instances.
5702 include_once($modfile);
5703 if (function_exists($moddeleteuserdata)) {
5704 $modstatus = $moddeleteuserdata($data);
5705 if (is_array($modstatus)) {
5706 $status = array_merge($status, $modstatus);
5707 } else {
5708 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5710 } else {
5711 $unsupportedmods[] = $mod;
5713 } else {
5714 debugging('Missing lib.php in '.$modname.' module!');
5716 // Update calendar events for all modules.
5717 course_module_bulk_update_calendar_events($modname, $data->courseid);
5721 // Mention unsupported mods.
5722 if (!empty($unsupportedmods)) {
5723 foreach ($unsupportedmods as $mod) {
5724 $status[] = array(
5725 'component' => get_string('modulenameplural', $mod->name),
5726 'item' => '',
5727 'error' => get_string('resetnotimplemented')
5732 $componentstr = get_string('gradebook', 'grades');
5733 // Reset gradebook,.
5734 if (!empty($data->reset_gradebook_items)) {
5735 remove_course_grades($data->courseid, false);
5736 grade_grab_course_grades($data->courseid);
5737 grade_regrade_final_grades($data->courseid);
5738 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5740 } else if (!empty($data->reset_gradebook_grades)) {
5741 grade_course_reset($data->courseid);
5742 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5744 // Reset comments.
5745 if (!empty($data->reset_comments)) {
5746 require_once($CFG->dirroot.'/comment/lib.php');
5747 comment::reset_course_page_comments($context);
5750 $event = \core\event\course_reset_ended::create($eventparams);
5751 $event->trigger();
5753 return $status;
5757 * Generate an email processing address.
5759 * @param int $modid
5760 * @param string $modargs
5761 * @return string Returns email processing address
5763 function generate_email_processing_address($modid, $modargs) {
5764 global $CFG;
5766 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5767 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5773 * @todo Finish documenting this function
5775 * @param string $modargs
5776 * @param string $body Currently unused
5778 function moodle_process_email($modargs, $body) {
5779 global $DB;
5781 // The first char should be an unencoded letter. We'll take this as an action.
5782 switch ($modargs[0]) {
5783 case 'B': { // Bounce.
5784 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5785 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5786 // Check the half md5 of their email.
5787 $md5check = substr(md5($user->email), 0, 16);
5788 if ($md5check == substr($modargs, -16)) {
5789 set_bounce_count($user);
5791 // Else maybe they've already changed it?
5794 break;
5795 // Maybe more later?
5799 // CORRESPONDENCE.
5802 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5804 * @param string $action 'get', 'buffer', 'close' or 'flush'
5805 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5807 function get_mailer($action='get') {
5808 global $CFG;
5810 /** @var moodle_phpmailer $mailer */
5811 static $mailer = null;
5812 static $counter = 0;
5814 if (!isset($CFG->smtpmaxbulk)) {
5815 $CFG->smtpmaxbulk = 1;
5818 if ($action == 'get') {
5819 $prevkeepalive = false;
5821 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5822 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5823 $counter++;
5824 // Reset the mailer.
5825 $mailer->Priority = 3;
5826 $mailer->CharSet = 'UTF-8'; // Our default.
5827 $mailer->ContentType = "text/plain";
5828 $mailer->Encoding = "8bit";
5829 $mailer->From = "root@localhost";
5830 $mailer->FromName = "Root User";
5831 $mailer->Sender = "";
5832 $mailer->Subject = "";
5833 $mailer->Body = "";
5834 $mailer->AltBody = "";
5835 $mailer->ConfirmReadingTo = "";
5837 $mailer->clearAllRecipients();
5838 $mailer->clearReplyTos();
5839 $mailer->clearAttachments();
5840 $mailer->clearCustomHeaders();
5841 return $mailer;
5844 $prevkeepalive = $mailer->SMTPKeepAlive;
5845 get_mailer('flush');
5848 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5849 $mailer = new moodle_phpmailer();
5851 $counter = 1;
5853 if ($CFG->smtphosts == 'qmail') {
5854 // Use Qmail system.
5855 $mailer->isQmail();
5857 } else if (empty($CFG->smtphosts)) {
5858 // Use PHP mail() = sendmail.
5859 $mailer->isMail();
5861 } else {
5862 // Use SMTP directly.
5863 $mailer->isSMTP();
5864 if (!empty($CFG->debugsmtp) && (!empty($CFG->debugdeveloper))) {
5865 $mailer->SMTPDebug = 3;
5867 // Specify main and backup servers.
5868 $mailer->Host = $CFG->smtphosts;
5869 // Specify secure connection protocol.
5870 $mailer->SMTPSecure = $CFG->smtpsecure;
5871 // Use previous keepalive.
5872 $mailer->SMTPKeepAlive = $prevkeepalive;
5874 if ($CFG->smtpuser) {
5875 // Use SMTP authentication.
5876 $mailer->SMTPAuth = true;
5877 $mailer->Username = $CFG->smtpuser;
5878 $mailer->Password = $CFG->smtppass;
5882 return $mailer;
5885 $nothing = null;
5887 // Keep smtp session open after sending.
5888 if ($action == 'buffer') {
5889 if (!empty($CFG->smtpmaxbulk)) {
5890 get_mailer('flush');
5891 $m = get_mailer();
5892 if ($m->Mailer == 'smtp') {
5893 $m->SMTPKeepAlive = true;
5896 return $nothing;
5899 // Close smtp session, but continue buffering.
5900 if ($action == 'flush') {
5901 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5902 if (!empty($mailer->SMTPDebug)) {
5903 echo '<pre>'."\n";
5905 $mailer->SmtpClose();
5906 if (!empty($mailer->SMTPDebug)) {
5907 echo '</pre>';
5910 return $nothing;
5913 // Close smtp session, do not buffer anymore.
5914 if ($action == 'close') {
5915 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5916 get_mailer('flush');
5917 $mailer->SMTPKeepAlive = false;
5919 $mailer = null; // Better force new instance.
5920 return $nothing;
5925 * A helper function to test for email diversion
5927 * @param string $email
5928 * @return bool Returns true if the email should be diverted
5930 function email_should_be_diverted($email) {
5931 global $CFG;
5933 if (empty($CFG->divertallemailsto)) {
5934 return false;
5937 if (empty($CFG->divertallemailsexcept)) {
5938 return true;
5941 $patterns = array_map('trim', explode(',', $CFG->divertallemailsexcept));
5942 foreach ($patterns as $pattern) {
5943 if (preg_match("/$pattern/", $email)) {
5944 return false;
5948 return true;
5952 * Generate a unique email Message-ID using the moodle domain and install path
5954 * @param string $localpart An optional unique message id prefix.
5955 * @return string The formatted ID ready for appending to the email headers.
5957 function generate_email_messageid($localpart = null) {
5958 global $CFG;
5960 $urlinfo = parse_url($CFG->wwwroot);
5961 $base = '@' . $urlinfo['host'];
5963 // If multiple moodles are on the same domain we want to tell them
5964 // apart so we add the install path to the local part. This means
5965 // that the id local part should never contain a / character so
5966 // we can correctly parse the id to reassemble the wwwroot.
5967 if (isset($urlinfo['path'])) {
5968 $base = $urlinfo['path'] . $base;
5971 if (empty($localpart)) {
5972 $localpart = uniqid('', true);
5975 // Because we may have an option /installpath suffix to the local part
5976 // of the id we need to escape any / chars which are in the $localpart.
5977 $localpart = str_replace('/', '%2F', $localpart);
5979 return '<' . $localpart . $base . '>';
5983 * Send an email to a specified user
5985 * @param stdClass $user A {@link $USER} object
5986 * @param stdClass $from A {@link $USER} object
5987 * @param string $subject plain text subject line of the email
5988 * @param string $messagetext plain text version of the message
5989 * @param string $messagehtml complete html version of the message (optional)
5990 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5991 * @param string $attachname the name of the file (extension indicates MIME)
5992 * @param bool $usetrueaddress determines whether $from email address should
5993 * be sent out. Will be overruled by user profile setting for maildisplay
5994 * @param string $replyto Email address to reply to
5995 * @param string $replytoname Name of reply to recipient
5996 * @param int $wordwrapwidth custom word wrap width, default 79
5997 * @return bool Returns true if mail was sent OK and false if there was an error.
5999 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
6000 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
6002 global $CFG, $PAGE, $SITE;
6004 if (empty($user) or empty($user->id)) {
6005 debugging('Can not send email to null user', DEBUG_DEVELOPER);
6006 return false;
6009 if (empty($user->email)) {
6010 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
6011 return false;
6014 if (!empty($user->deleted)) {
6015 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
6016 return false;
6019 if (defined('BEHAT_SITE_RUNNING')) {
6020 // Fake email sending in behat.
6021 return true;
6024 if (!empty($CFG->noemailever)) {
6025 // Hidden setting for development sites, set in config.php if needed.
6026 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
6027 return true;
6030 if (email_should_be_diverted($user->email)) {
6031 $subject = "[DIVERTED {$user->email}] $subject";
6032 $user = clone($user);
6033 $user->email = $CFG->divertallemailsto;
6036 // Skip mail to suspended users.
6037 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
6038 return true;
6041 if (!validate_email($user->email)) {
6042 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
6043 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
6044 return false;
6047 if (over_bounce_threshold($user)) {
6048 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
6049 return false;
6052 // TLD .invalid is specifically reserved for invalid domain names.
6053 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
6054 if (substr($user->email, -8) == '.invalid') {
6055 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
6056 return true; // This is not an error.
6059 // If the user is a remote mnet user, parse the email text for URL to the
6060 // wwwroot and modify the url to direct the user's browser to login at their
6061 // home site (identity provider - idp) before hitting the link itself.
6062 if (is_mnet_remote_user($user)) {
6063 require_once($CFG->dirroot.'/mnet/lib.php');
6065 $jumpurl = mnet_get_idp_jump_url($user);
6066 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
6068 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
6069 $callback,
6070 $messagetext);
6071 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
6072 $callback,
6073 $messagehtml);
6075 $mail = get_mailer();
6077 if (!empty($mail->SMTPDebug)) {
6078 echo '<pre>' . "\n";
6081 $temprecipients = array();
6082 $tempreplyto = array();
6084 // Make sure that we fall back onto some reasonable no-reply address.
6085 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
6086 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
6088 if (!validate_email($noreplyaddress)) {
6089 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
6090 $noreplyaddress = $noreplyaddressdefault;
6093 // Make up an email address for handling bounces.
6094 if (!empty($CFG->handlebounces)) {
6095 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
6096 $mail->Sender = generate_email_processing_address(0, $modargs);
6097 } else {
6098 $mail->Sender = $noreplyaddress;
6101 // Make sure that the explicit replyto is valid, fall back to the implicit one.
6102 if (!empty($replyto) && !validate_email($replyto)) {
6103 debugging('email_to_user: Invalid replyto-email '.s($replyto));
6104 $replyto = $noreplyaddress;
6107 if (is_string($from)) { // So we can pass whatever we want if there is need.
6108 $mail->From = $noreplyaddress;
6109 $mail->FromName = $from;
6110 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
6111 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6112 // in a course with the sender.
6113 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
6114 if (!validate_email($from->email)) {
6115 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
6116 // Better not to use $noreplyaddress in this case.
6117 return false;
6119 $mail->From = $from->email;
6120 $fromdetails = new stdClass();
6121 $fromdetails->name = fullname($from);
6122 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6123 $fromdetails->siteshortname = format_string($SITE->shortname);
6124 $fromstring = $fromdetails->name;
6125 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
6126 $fromstring = get_string('emailvia', 'core', $fromdetails);
6128 $mail->FromName = $fromstring;
6129 if (empty($replyto)) {
6130 $tempreplyto[] = array($from->email, fullname($from));
6132 } else {
6133 $mail->From = $noreplyaddress;
6134 $fromdetails = new stdClass();
6135 $fromdetails->name = fullname($from);
6136 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6137 $fromdetails->siteshortname = format_string($SITE->shortname);
6138 $fromstring = $fromdetails->name;
6139 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
6140 $fromstring = get_string('emailvia', 'core', $fromdetails);
6142 $mail->FromName = $fromstring;
6143 if (empty($replyto)) {
6144 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
6148 if (!empty($replyto)) {
6149 $tempreplyto[] = array($replyto, $replytoname);
6152 $temprecipients[] = array($user->email, fullname($user));
6154 // Set word wrap.
6155 $mail->WordWrap = $wordwrapwidth;
6157 if (!empty($from->customheaders)) {
6158 // Add custom headers.
6159 if (is_array($from->customheaders)) {
6160 foreach ($from->customheaders as $customheader) {
6161 $mail->addCustomHeader($customheader);
6163 } else {
6164 $mail->addCustomHeader($from->customheaders);
6168 // If the X-PHP-Originating-Script email header is on then also add an additional
6169 // header with details of where exactly in moodle the email was triggered from,
6170 // either a call to message_send() or to email_to_user().
6171 if (ini_get('mail.add_x_header')) {
6173 $stack = debug_backtrace(false);
6174 $origin = $stack[0];
6176 foreach ($stack as $depth => $call) {
6177 if ($call['function'] == 'message_send') {
6178 $origin = $call;
6182 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
6183 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
6184 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
6187 if (!empty($from->priority)) {
6188 $mail->Priority = $from->priority;
6191 $renderer = $PAGE->get_renderer('core');
6192 $context = array(
6193 'sitefullname' => $SITE->fullname,
6194 'siteshortname' => $SITE->shortname,
6195 'sitewwwroot' => $CFG->wwwroot,
6196 'subject' => $subject,
6197 'prefix' => $CFG->emailsubjectprefix,
6198 'to' => $user->email,
6199 'toname' => fullname($user),
6200 'from' => $mail->From,
6201 'fromname' => $mail->FromName,
6203 if (!empty($tempreplyto[0])) {
6204 $context['replyto'] = $tempreplyto[0][0];
6205 $context['replytoname'] = $tempreplyto[0][1];
6207 if ($user->id > 0) {
6208 $context['touserid'] = $user->id;
6209 $context['tousername'] = $user->username;
6212 if (!empty($user->mailformat) && $user->mailformat == 1) {
6213 // Only process html templates if the user preferences allow html email.
6215 if (!$messagehtml) {
6216 // If no html has been given, BUT there is an html wrapping template then
6217 // auto convert the text to html and then wrap it.
6218 $messagehtml = trim(text_to_html($messagetext));
6220 $context['body'] = $messagehtml;
6221 $messagehtml = $renderer->render_from_template('core/email_html', $context);
6224 $context['body'] = html_to_text(nl2br($messagetext));
6225 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
6226 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
6227 $messagetext = $renderer->render_from_template('core/email_text', $context);
6229 // Autogenerate a MessageID if it's missing.
6230 if (empty($mail->MessageID)) {
6231 $mail->MessageID = generate_email_messageid();
6234 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6235 // Don't ever send HTML to users who don't want it.
6236 $mail->isHTML(true);
6237 $mail->Encoding = 'quoted-printable';
6238 $mail->Body = $messagehtml;
6239 $mail->AltBody = "\n$messagetext\n";
6240 } else {
6241 $mail->IsHTML(false);
6242 $mail->Body = "\n$messagetext\n";
6245 if ($attachment && $attachname) {
6246 if (preg_match( "~\\.\\.~" , $attachment )) {
6247 // Security check for ".." in dir path.
6248 $supportuser = core_user::get_support_user();
6249 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6250 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6251 } else {
6252 require_once($CFG->libdir.'/filelib.php');
6253 $mimetype = mimeinfo('type', $attachname);
6255 $attachmentpath = $attachment;
6257 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6258 $attachpath = str_replace('\\', '/', $attachmentpath);
6259 // Make sure both variables are normalised before comparing.
6260 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
6262 // If the attachment is a full path to a file in the tempdir, use it as is,
6263 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6264 if (strpos($attachpath, $temppath) !== 0) {
6265 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
6268 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
6272 // Check if the email should be sent in an other charset then the default UTF-8.
6273 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6275 // Use the defined site mail charset or eventually the one preferred by the recipient.
6276 $charset = $CFG->sitemailcharset;
6277 if (!empty($CFG->allowusermailcharset)) {
6278 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6279 $charset = $useremailcharset;
6283 // Convert all the necessary strings if the charset is supported.
6284 $charsets = get_list_of_charsets();
6285 unset($charsets['UTF-8']);
6286 if (in_array($charset, $charsets)) {
6287 $mail->CharSet = $charset;
6288 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6289 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6290 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6291 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6293 foreach ($temprecipients as $key => $values) {
6294 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6296 foreach ($tempreplyto as $key => $values) {
6297 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6302 foreach ($temprecipients as $values) {
6303 $mail->addAddress($values[0], $values[1]);
6305 foreach ($tempreplyto as $values) {
6306 $mail->addReplyTo($values[0], $values[1]);
6309 if ($mail->send()) {
6310 set_send_count($user);
6311 if (!empty($mail->SMTPDebug)) {
6312 echo '</pre>';
6314 return true;
6315 } else {
6316 // Trigger event for failing to send email.
6317 $event = \core\event\email_failed::create(array(
6318 'context' => context_system::instance(),
6319 'userid' => $from->id,
6320 'relateduserid' => $user->id,
6321 'other' => array(
6322 'subject' => $subject,
6323 'message' => $messagetext,
6324 'errorinfo' => $mail->ErrorInfo
6327 $event->trigger();
6328 if (CLI_SCRIPT) {
6329 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6331 if (!empty($mail->SMTPDebug)) {
6332 echo '</pre>';
6334 return false;
6339 * Check to see if a user's real email address should be used for the "From" field.
6341 * @param object $from The user object for the user we are sending the email from.
6342 * @param object $user The user object that we are sending the email to.
6343 * @param array $unused No longer used.
6344 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6346 function can_send_from_real_email_address($from, $user, $unused = null) {
6347 global $CFG;
6348 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6349 return false;
6351 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6352 // Email is in the list of allowed domains for sending email,
6353 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6354 // in a course with the sender.
6355 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6356 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6357 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6358 && enrol_get_shared_courses($user, $from, false, true)))) {
6359 return true;
6361 return false;
6365 * Generate a signoff for emails based on support settings
6367 * @return string
6369 function generate_email_signoff() {
6370 global $CFG;
6372 $signoff = "\n";
6373 if (!empty($CFG->supportname)) {
6374 $signoff .= $CFG->supportname."\n";
6376 if (!empty($CFG->supportemail)) {
6377 $signoff .= $CFG->supportemail."\n";
6379 if (!empty($CFG->supportpage)) {
6380 $signoff .= $CFG->supportpage."\n";
6382 return $signoff;
6386 * Sets specified user's password and send the new password to the user via email.
6388 * @param stdClass $user A {@link $USER} object
6389 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6390 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6392 function setnew_password_and_mail($user, $fasthash = false) {
6393 global $CFG, $DB;
6395 // We try to send the mail in language the user understands,
6396 // unfortunately the filter_string() does not support alternative langs yet
6397 // so multilang will not work properly for site->fullname.
6398 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6400 $site = get_site();
6402 $supportuser = core_user::get_support_user();
6404 $newpassword = generate_password();
6406 update_internal_user_password($user, $newpassword, $fasthash);
6408 $a = new stdClass();
6409 $a->firstname = fullname($user, true);
6410 $a->sitename = format_string($site->fullname);
6411 $a->username = $user->username;
6412 $a->newpassword = $newpassword;
6413 $a->link = $CFG->wwwroot .'/login/?lang='.$lang;
6414 $a->signoff = generate_email_signoff();
6416 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6418 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6420 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6421 return email_to_user($user, $supportuser, $subject, $message);
6426 * Resets specified user's password and send the new password to the user via email.
6428 * @param stdClass $user A {@link $USER} object
6429 * @return bool Returns true if mail was sent OK and false if there was an error.
6431 function reset_password_and_mail($user) {
6432 global $CFG;
6434 $site = get_site();
6435 $supportuser = core_user::get_support_user();
6437 $userauth = get_auth_plugin($user->auth);
6438 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6439 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6440 return false;
6443 $newpassword = generate_password();
6445 if (!$userauth->user_update_password($user, $newpassword)) {
6446 print_error("cannotsetpassword");
6449 $a = new stdClass();
6450 $a->firstname = $user->firstname;
6451 $a->lastname = $user->lastname;
6452 $a->sitename = format_string($site->fullname);
6453 $a->username = $user->username;
6454 $a->newpassword = $newpassword;
6455 $a->link = $CFG->wwwroot .'/login/change_password.php';
6456 $a->signoff = generate_email_signoff();
6458 $message = get_string('newpasswordtext', '', $a);
6460 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6462 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6464 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6465 return email_to_user($user, $supportuser, $subject, $message);
6469 * Send email to specified user with confirmation text and activation link.
6471 * @param stdClass $user A {@link $USER} object
6472 * @param string $confirmationurl user confirmation URL
6473 * @return bool Returns true if mail was sent OK and false if there was an error.
6475 function send_confirmation_email($user, $confirmationurl = null) {
6476 global $CFG;
6478 $site = get_site();
6479 $supportuser = core_user::get_support_user();
6481 $data = new stdClass();
6482 $data->firstname = fullname($user);
6483 $data->sitename = format_string($site->fullname);
6484 $data->admin = generate_email_signoff();
6486 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6488 if (empty($confirmationurl)) {
6489 $confirmationurl = '/login/confirm.php';
6492 $confirmationurl = new moodle_url($confirmationurl);
6493 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6494 $confirmationurl->remove_params('data');
6495 $confirmationpath = $confirmationurl->out(false);
6497 // We need to custom encode the username to include trailing dots in the link.
6498 // Because of this custom encoding we can't use moodle_url directly.
6499 // Determine if a query string is present in the confirmation url.
6500 $hasquerystring = strpos($confirmationpath, '?') !== false;
6501 // Perform normal url encoding of the username first.
6502 $username = urlencode($user->username);
6503 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6504 $username = str_replace('.', '%2E', $username);
6506 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6508 $message = get_string('emailconfirmation', '', $data);
6509 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6511 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6512 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6516 * Sends a password change confirmation email.
6518 * @param stdClass $user A {@link $USER} object
6519 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6520 * @return bool Returns true if mail was sent OK and false if there was an error.
6522 function send_password_change_confirmation_email($user, $resetrecord) {
6523 global $CFG;
6525 $site = get_site();
6526 $supportuser = core_user::get_support_user();
6527 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6529 $data = new stdClass();
6530 $data->firstname = $user->firstname;
6531 $data->lastname = $user->lastname;
6532 $data->username = $user->username;
6533 $data->sitename = format_string($site->fullname);
6534 $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6535 $data->admin = generate_email_signoff();
6536 $data->resetminutes = $pwresetmins;
6538 $message = get_string('emailresetconfirmation', '', $data);
6539 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6541 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6542 return email_to_user($user, $supportuser, $subject, $message);
6547 * Sends an email containing information on how to change your password.
6549 * @param stdClass $user A {@link $USER} object
6550 * @return bool Returns true if mail was sent OK and false if there was an error.
6552 function send_password_change_info($user) {
6553 $site = get_site();
6554 $supportuser = core_user::get_support_user();
6556 $data = new stdClass();
6557 $data->firstname = $user->firstname;
6558 $data->lastname = $user->lastname;
6559 $data->username = $user->username;
6560 $data->sitename = format_string($site->fullname);
6561 $data->admin = generate_email_signoff();
6563 if (!is_enabled_auth($user->auth)) {
6564 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6565 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6566 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6567 return email_to_user($user, $supportuser, $subject, $message);
6570 $userauth = get_auth_plugin($user->auth);
6571 ['subject' => $subject, 'message' => $message] = $userauth->get_password_change_info($user);
6573 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6574 return email_to_user($user, $supportuser, $subject, $message);
6578 * Check that an email is allowed. It returns an error message if there was a problem.
6580 * @param string $email Content of email
6581 * @return string|false
6583 function email_is_not_allowed($email) {
6584 global $CFG;
6586 // Comparing lowercase domains.
6587 $email = strtolower($email);
6588 if (!empty($CFG->allowemailaddresses)) {
6589 $allowed = explode(' ', strtolower($CFG->allowemailaddresses));
6590 foreach ($allowed as $allowedpattern) {
6591 $allowedpattern = trim($allowedpattern);
6592 if (!$allowedpattern) {
6593 continue;
6595 if (strpos($allowedpattern, '.') === 0) {
6596 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6597 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6598 return false;
6601 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6602 return false;
6605 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6607 } else if (!empty($CFG->denyemailaddresses)) {
6608 $denied = explode(' ', strtolower($CFG->denyemailaddresses));
6609 foreach ($denied as $deniedpattern) {
6610 $deniedpattern = trim($deniedpattern);
6611 if (!$deniedpattern) {
6612 continue;
6614 if (strpos($deniedpattern, '.') === 0) {
6615 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6616 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6617 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6620 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6621 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6626 return false;
6629 // FILE HANDLING.
6632 * Returns local file storage instance
6634 * @return file_storage
6636 function get_file_storage($reset = false) {
6637 global $CFG;
6639 static $fs = null;
6641 if ($reset) {
6642 $fs = null;
6643 return;
6646 if ($fs) {
6647 return $fs;
6650 require_once("$CFG->libdir/filelib.php");
6652 $fs = new file_storage();
6654 return $fs;
6658 * Returns local file storage instance
6660 * @return file_browser
6662 function get_file_browser() {
6663 global $CFG;
6665 static $fb = null;
6667 if ($fb) {
6668 return $fb;
6671 require_once("$CFG->libdir/filelib.php");
6673 $fb = new file_browser();
6675 return $fb;
6679 * Returns file packer
6681 * @param string $mimetype default application/zip
6682 * @return file_packer
6684 function get_file_packer($mimetype='application/zip') {
6685 global $CFG;
6687 static $fp = array();
6689 if (isset($fp[$mimetype])) {
6690 return $fp[$mimetype];
6693 switch ($mimetype) {
6694 case 'application/zip':
6695 case 'application/vnd.moodle.profiling':
6696 $classname = 'zip_packer';
6697 break;
6699 case 'application/x-gzip' :
6700 $classname = 'tgz_packer';
6701 break;
6703 case 'application/vnd.moodle.backup':
6704 $classname = 'mbz_packer';
6705 break;
6707 default:
6708 return false;
6711 require_once("$CFG->libdir/filestorage/$classname.php");
6712 $fp[$mimetype] = new $classname();
6714 return $fp[$mimetype];
6718 * Returns current name of file on disk if it exists.
6720 * @param string $newfile File to be verified
6721 * @return string Current name of file on disk if true
6723 function valid_uploaded_file($newfile) {
6724 if (empty($newfile)) {
6725 return '';
6727 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6728 return $newfile['tmp_name'];
6729 } else {
6730 return '';
6735 * Returns the maximum size for uploading files.
6737 * There are seven possible upload limits:
6738 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6739 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6740 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6741 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6742 * 5. by the Moodle admin in $CFG->maxbytes
6743 * 6. by the teacher in the current course $course->maxbytes
6744 * 7. by the teacher for the current module, eg $assignment->maxbytes
6746 * These last two are passed to this function as arguments (in bytes).
6747 * Anything defined as 0 is ignored.
6748 * The smallest of all the non-zero numbers is returned.
6750 * @todo Finish documenting this function
6752 * @param int $sitebytes Set maximum size
6753 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6754 * @param int $modulebytes Current module ->maxbytes (in bytes)
6755 * @param bool $unused This parameter has been deprecated and is not used any more.
6756 * @return int The maximum size for uploading files.
6758 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6760 if (! $filesize = ini_get('upload_max_filesize')) {
6761 $filesize = '5M';
6763 $minimumsize = get_real_size($filesize);
6765 if ($postsize = ini_get('post_max_size')) {
6766 $postsize = get_real_size($postsize);
6767 if ($postsize < $minimumsize) {
6768 $minimumsize = $postsize;
6772 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6773 $minimumsize = $sitebytes;
6776 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6777 $minimumsize = $coursebytes;
6780 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6781 $minimumsize = $modulebytes;
6784 return $minimumsize;
6788 * Returns the maximum size for uploading files for the current user
6790 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6792 * @param context $context The context in which to check user capabilities
6793 * @param int $sitebytes Set maximum size
6794 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6795 * @param int $modulebytes Current module ->maxbytes (in bytes)
6796 * @param stdClass $user The user
6797 * @param bool $unused This parameter has been deprecated and is not used any more.
6798 * @return int The maximum size for uploading files.
6800 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6801 $unused = false) {
6802 global $USER;
6804 if (empty($user)) {
6805 $user = $USER;
6808 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6809 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6812 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6816 * Returns an array of possible sizes in local language
6818 * Related to {@link get_max_upload_file_size()} - this function returns an
6819 * array of possible sizes in an array, translated to the
6820 * local language.
6822 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6824 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6825 * with the value set to 0. This option will be the first in the list.
6827 * @uses SORT_NUMERIC
6828 * @param int $sitebytes Set maximum size
6829 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6830 * @param int $modulebytes Current module ->maxbytes (in bytes)
6831 * @param int|array $custombytes custom upload size/s which will be added to list,
6832 * Only value/s smaller then maxsize will be added to list.
6833 * @return array
6835 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6836 global $CFG;
6838 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6839 return array();
6842 if ($sitebytes == 0) {
6843 // Will get the minimum of upload_max_filesize or post_max_size.
6844 $sitebytes = get_max_upload_file_size();
6847 $filesize = array();
6848 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6849 5242880, 10485760, 20971520, 52428800, 104857600,
6850 262144000, 524288000, 786432000, 1073741824,
6851 2147483648, 4294967296, 8589934592);
6853 // If custombytes is given and is valid then add it to the list.
6854 if (is_number($custombytes) and $custombytes > 0) {
6855 $custombytes = (int)$custombytes;
6856 if (!in_array($custombytes, $sizelist)) {
6857 $sizelist[] = $custombytes;
6859 } else if (is_array($custombytes)) {
6860 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6863 // Allow maxbytes to be selected if it falls outside the above boundaries.
6864 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6865 // Note: get_real_size() is used in order to prevent problems with invalid values.
6866 $sizelist[] = get_real_size($CFG->maxbytes);
6869 foreach ($sizelist as $sizebytes) {
6870 if ($sizebytes < $maxsize && $sizebytes > 0) {
6871 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6875 $limitlevel = '';
6876 $displaysize = '';
6877 if ($modulebytes &&
6878 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6879 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6880 $limitlevel = get_string('activity', 'core');
6881 $displaysize = display_size($modulebytes);
6882 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6884 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6885 $limitlevel = get_string('course', 'core');
6886 $displaysize = display_size($coursebytes);
6887 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6889 } else if ($sitebytes) {
6890 $limitlevel = get_string('site', 'core');
6891 $displaysize = display_size($sitebytes);
6892 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6895 krsort($filesize, SORT_NUMERIC);
6896 if ($limitlevel) {
6897 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6898 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6901 return $filesize;
6905 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6907 * If excludefiles is defined, then that file/directory is ignored
6908 * If getdirs is true, then (sub)directories are included in the output
6909 * If getfiles is true, then files are included in the output
6910 * (at least one of these must be true!)
6912 * @todo Finish documenting this function. Add examples of $excludefile usage.
6914 * @param string $rootdir A given root directory to start from
6915 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6916 * @param bool $descend If true then subdirectories are recursed as well
6917 * @param bool $getdirs If true then (sub)directories are included in the output
6918 * @param bool $getfiles If true then files are included in the output
6919 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6921 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6923 $dirs = array();
6925 if (!$getdirs and !$getfiles) { // Nothing to show.
6926 return $dirs;
6929 if (!is_dir($rootdir)) { // Must be a directory.
6930 return $dirs;
6933 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6934 return $dirs;
6937 if (!is_array($excludefiles)) {
6938 $excludefiles = array($excludefiles);
6941 while (false !== ($file = readdir($dir))) {
6942 $firstchar = substr($file, 0, 1);
6943 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6944 continue;
6946 $fullfile = $rootdir .'/'. $file;
6947 if (filetype($fullfile) == 'dir') {
6948 if ($getdirs) {
6949 $dirs[] = $file;
6951 if ($descend) {
6952 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6953 foreach ($subdirs as $subdir) {
6954 $dirs[] = $file .'/'. $subdir;
6957 } else if ($getfiles) {
6958 $dirs[] = $file;
6961 closedir($dir);
6963 asort($dirs);
6965 return $dirs;
6970 * Adds up all the files in a directory and works out the size.
6972 * @param string $rootdir The directory to start from
6973 * @param string $excludefile A file to exclude when summing directory size
6974 * @return int The summed size of all files and subfiles within the root directory
6976 function get_directory_size($rootdir, $excludefile='') {
6977 global $CFG;
6979 // Do it this way if we can, it's much faster.
6980 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6981 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6982 $output = null;
6983 $return = null;
6984 exec($command, $output, $return);
6985 if (is_array($output)) {
6986 // We told it to return k.
6987 return get_real_size(intval($output[0]).'k');
6991 if (!is_dir($rootdir)) {
6992 // Must be a directory.
6993 return 0;
6996 if (!$dir = @opendir($rootdir)) {
6997 // Can't open it for some reason.
6998 return 0;
7001 $size = 0;
7003 while (false !== ($file = readdir($dir))) {
7004 $firstchar = substr($file, 0, 1);
7005 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
7006 continue;
7008 $fullfile = $rootdir .'/'. $file;
7009 if (filetype($fullfile) == 'dir') {
7010 $size += get_directory_size($fullfile, $excludefile);
7011 } else {
7012 $size += filesize($fullfile);
7015 closedir($dir);
7017 return $size;
7021 * Converts bytes into display form
7023 * @static string $gb Localized string for size in gigabytes
7024 * @static string $mb Localized string for size in megabytes
7025 * @static string $kb Localized string for size in kilobytes
7026 * @static string $b Localized string for size in bytes
7027 * @param int $size The size to convert to human readable form
7028 * @return string
7030 function display_size($size) {
7032 static $gb, $mb, $kb, $b;
7034 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
7035 return get_string('unlimited');
7038 if (empty($gb)) {
7039 $gb = get_string('sizegb');
7040 $mb = get_string('sizemb');
7041 $kb = get_string('sizekb');
7042 $b = get_string('sizeb');
7045 if ($size >= 1073741824) {
7046 $size = round($size / 1073741824 * 10) / 10 . $gb;
7047 } else if ($size >= 1048576) {
7048 $size = round($size / 1048576 * 10) / 10 . $mb;
7049 } else if ($size >= 1024) {
7050 $size = round($size / 1024 * 10) / 10 . $kb;
7051 } else {
7052 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
7054 return $size;
7058 * Cleans a given filename by removing suspicious or troublesome characters
7060 * @see clean_param()
7061 * @param string $string file name
7062 * @return string cleaned file name
7064 function clean_filename($string) {
7065 return clean_param($string, PARAM_FILE);
7068 // STRING TRANSLATION.
7071 * Returns the code for the current language
7073 * @category string
7074 * @return string
7076 function current_language() {
7077 global $CFG, $USER, $SESSION, $COURSE;
7079 if (!empty($SESSION->forcelang)) {
7080 // Allows overriding course-forced language (useful for admins to check
7081 // issues in courses whose language they don't understand).
7082 // Also used by some code to temporarily get language-related information in a
7083 // specific language (see force_current_language()).
7084 $return = $SESSION->forcelang;
7086 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
7087 // Course language can override all other settings for this page.
7088 $return = $COURSE->lang;
7090 } else if (!empty($SESSION->lang)) {
7091 // Session language can override other settings.
7092 $return = $SESSION->lang;
7094 } else if (!empty($USER->lang)) {
7095 $return = $USER->lang;
7097 } else if (isset($CFG->lang)) {
7098 $return = $CFG->lang;
7100 } else {
7101 $return = 'en';
7104 // Just in case this slipped in from somewhere by accident.
7105 $return = str_replace('_utf8', '', $return);
7107 return $return;
7111 * Returns parent language of current active language if defined
7113 * @category string
7114 * @param string $lang null means current language
7115 * @return string
7117 function get_parent_language($lang=null) {
7119 $parentlang = get_string_manager()->get_string('parentlanguage', 'langconfig', null, $lang);
7121 if ($parentlang === 'en') {
7122 $parentlang = '';
7125 return $parentlang;
7129 * Force the current language to get strings and dates localised in the given language.
7131 * After calling this function, all strings will be provided in the given language
7132 * until this function is called again, or equivalent code is run.
7134 * @param string $language
7135 * @return string previous $SESSION->forcelang value
7137 function force_current_language($language) {
7138 global $SESSION;
7139 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
7140 if ($language !== $sessionforcelang) {
7141 // Seting forcelang to null or an empty string disables it's effect.
7142 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
7143 $SESSION->forcelang = $language;
7144 moodle_setlocale();
7147 return $sessionforcelang;
7151 * Returns current string_manager instance.
7153 * The param $forcereload is needed for CLI installer only where the string_manager instance
7154 * must be replaced during the install.php script life time.
7156 * @category string
7157 * @param bool $forcereload shall the singleton be released and new instance created instead?
7158 * @return core_string_manager
7160 function get_string_manager($forcereload=false) {
7161 global $CFG;
7163 static $singleton = null;
7165 if ($forcereload) {
7166 $singleton = null;
7168 if ($singleton === null) {
7169 if (empty($CFG->early_install_lang)) {
7171 $transaliases = array();
7172 if (empty($CFG->langlist)) {
7173 $translist = array();
7174 } else {
7175 $translist = explode(',', $CFG->langlist);
7176 $translist = array_map('trim', $translist);
7177 // Each language in the $CFG->langlist can has an "alias" that would substitute the default language name.
7178 foreach ($translist as $i => $value) {
7179 $parts = preg_split('/\s*\|\s*/', $value, 2);
7180 if (count($parts) == 2) {
7181 $transaliases[$parts[0]] = $parts[1];
7182 $translist[$i] = $parts[0];
7187 if (!empty($CFG->config_php_settings['customstringmanager'])) {
7188 $classname = $CFG->config_php_settings['customstringmanager'];
7190 if (class_exists($classname)) {
7191 $implements = class_implements($classname);
7193 if (isset($implements['core_string_manager'])) {
7194 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7195 return $singleton;
7197 } else {
7198 debugging('Unable to instantiate custom string manager: class '.$classname.
7199 ' does not implement the core_string_manager interface.');
7202 } else {
7203 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7207 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7209 } else {
7210 $singleton = new core_string_manager_install();
7214 return $singleton;
7218 * Returns a localized string.
7220 * Returns the translated string specified by $identifier as
7221 * for $module. Uses the same format files as STphp.
7222 * $a is an object, string or number that can be used
7223 * within translation strings
7225 * eg 'hello {$a->firstname} {$a->lastname}'
7226 * or 'hello {$a}'
7228 * If you would like to directly echo the localized string use
7229 * the function {@link print_string()}
7231 * Example usage of this function involves finding the string you would
7232 * like a local equivalent of and using its identifier and module information
7233 * to retrieve it.<br/>
7234 * If you open moodle/lang/en/moodle.php and look near line 278
7235 * you will find a string to prompt a user for their word for 'course'
7236 * <code>
7237 * $string['course'] = 'Course';
7238 * </code>
7239 * So if you want to display the string 'Course'
7240 * in any language that supports it on your site
7241 * you just need to use the identifier 'course'
7242 * <code>
7243 * $mystring = '<strong>'. get_string('course') .'</strong>';
7244 * or
7245 * </code>
7246 * If the string you want is in another file you'd take a slightly
7247 * different approach. Looking in moodle/lang/en/calendar.php you find
7248 * around line 75:
7249 * <code>
7250 * $string['typecourse'] = 'Course event';
7251 * </code>
7252 * If you want to display the string "Course event" in any language
7253 * supported you would use the identifier 'typecourse' and the module 'calendar'
7254 * (because it is in the file calendar.php):
7255 * <code>
7256 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7257 * </code>
7259 * As a last resort, should the identifier fail to map to a string
7260 * the returned string will be [[ $identifier ]]
7262 * In Moodle 2.3 there is a new argument to this function $lazyload.
7263 * Setting $lazyload to true causes get_string to return a lang_string object
7264 * rather than the string itself. The fetching of the string is then put off until
7265 * the string object is first used. The object can be used by calling it's out
7266 * method or by casting the object to a string, either directly e.g.
7267 * (string)$stringobject
7268 * or indirectly by using the string within another string or echoing it out e.g.
7269 * echo $stringobject
7270 * return "<p>{$stringobject}</p>";
7271 * It is worth noting that using $lazyload and attempting to use the string as an
7272 * array key will cause a fatal error as objects cannot be used as array keys.
7273 * But you should never do that anyway!
7274 * For more information {@link lang_string}
7276 * @category string
7277 * @param string $identifier The key identifier for the localized string
7278 * @param string $component The module where the key identifier is stored,
7279 * usually expressed as the filename in the language pack without the
7280 * .php on the end but can also be written as mod/forum or grade/export/xls.
7281 * If none is specified then moodle.php is used.
7282 * @param string|object|array $a An object, string or number that can be used
7283 * within translation strings
7284 * @param bool $lazyload If set to true a string object is returned instead of
7285 * the string itself. The string then isn't calculated until it is first used.
7286 * @return string The localized string.
7287 * @throws coding_exception
7289 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7290 global $CFG;
7292 // If the lazy load argument has been supplied return a lang_string object
7293 // instead.
7294 // We need to make sure it is true (and a bool) as you will see below there
7295 // used to be a forth argument at one point.
7296 if ($lazyload === true) {
7297 return new lang_string($identifier, $component, $a);
7300 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7301 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7304 // There is now a forth argument again, this time it is a boolean however so
7305 // we can still check for the old extralocations parameter.
7306 if (!is_bool($lazyload) && !empty($lazyload)) {
7307 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7310 if (strpos($component, '/') !== false) {
7311 debugging('The module name you passed to get_string is the deprecated format ' .
7312 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7313 $componentpath = explode('/', $component);
7315 switch ($componentpath[0]) {
7316 case 'mod':
7317 $component = $componentpath[1];
7318 break;
7319 case 'blocks':
7320 case 'block':
7321 $component = 'block_'.$componentpath[1];
7322 break;
7323 case 'enrol':
7324 $component = 'enrol_'.$componentpath[1];
7325 break;
7326 case 'format':
7327 $component = 'format_'.$componentpath[1];
7328 break;
7329 case 'grade':
7330 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7331 break;
7335 $result = get_string_manager()->get_string($identifier, $component, $a);
7337 // Debugging feature lets you display string identifier and component.
7338 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7339 $result .= ' {' . $identifier . '/' . $component . '}';
7341 return $result;
7345 * Converts an array of strings to their localized value.
7347 * @param array $array An array of strings
7348 * @param string $component The language module that these strings can be found in.
7349 * @return stdClass translated strings.
7351 function get_strings($array, $component = '') {
7352 $string = new stdClass;
7353 foreach ($array as $item) {
7354 $string->$item = get_string($item, $component);
7356 return $string;
7360 * Prints out a translated string.
7362 * Prints out a translated string using the return value from the {@link get_string()} function.
7364 * Example usage of this function when the string is in the moodle.php file:<br/>
7365 * <code>
7366 * echo '<strong>';
7367 * print_string('course');
7368 * echo '</strong>';
7369 * </code>
7371 * Example usage of this function when the string is not in the moodle.php file:<br/>
7372 * <code>
7373 * echo '<h1>';
7374 * print_string('typecourse', 'calendar');
7375 * echo '</h1>';
7376 * </code>
7378 * @category string
7379 * @param string $identifier The key identifier for the localized string
7380 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7381 * @param string|object|array $a An object, string or number that can be used within translation strings
7383 function print_string($identifier, $component = '', $a = null) {
7384 echo get_string($identifier, $component, $a);
7388 * Returns a list of charset codes
7390 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7391 * (checking that such charset is supported by the texlib library!)
7393 * @return array And associative array with contents in the form of charset => charset
7395 function get_list_of_charsets() {
7397 $charsets = array(
7398 'EUC-JP' => 'EUC-JP',
7399 'ISO-2022-JP'=> 'ISO-2022-JP',
7400 'ISO-8859-1' => 'ISO-8859-1',
7401 'SHIFT-JIS' => 'SHIFT-JIS',
7402 'GB2312' => 'GB2312',
7403 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7404 'UTF-8' => 'UTF-8');
7406 asort($charsets);
7408 return $charsets;
7412 * Returns a list of valid and compatible themes
7414 * @return array
7416 function get_list_of_themes() {
7417 global $CFG;
7419 $themes = array();
7421 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7422 $themelist = explode(',', $CFG->themelist);
7423 } else {
7424 $themelist = array_keys(core_component::get_plugin_list("theme"));
7427 foreach ($themelist as $key => $themename) {
7428 $theme = theme_config::load($themename);
7429 $themes[$themename] = $theme;
7432 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7434 return $themes;
7438 * Factory function for emoticon_manager
7440 * @return emoticon_manager singleton
7442 function get_emoticon_manager() {
7443 static $singleton = null;
7445 if (is_null($singleton)) {
7446 $singleton = new emoticon_manager();
7449 return $singleton;
7453 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7455 * Whenever this manager mentiones 'emoticon object', the following data
7456 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7457 * altidentifier and altcomponent
7459 * @see admin_setting_emoticons
7461 * @copyright 2010 David Mudrak
7462 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7464 class emoticon_manager {
7467 * Returns the currently enabled emoticons
7469 * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
7470 * @return array of emoticon objects
7472 public function get_emoticons($selectable = false) {
7473 global $CFG;
7474 $notselectable = ['martin', 'egg'];
7476 if (empty($CFG->emoticons)) {
7477 return array();
7480 $emoticons = $this->decode_stored_config($CFG->emoticons);
7482 if (!is_array($emoticons)) {
7483 // Something is wrong with the format of stored setting.
7484 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7485 return array();
7487 if ($selectable) {
7488 foreach ($emoticons as $index => $emote) {
7489 if (in_array($emote->altidentifier, $notselectable)) {
7490 // Skip this one.
7491 unset($emoticons[$index]);
7496 return $emoticons;
7500 * Converts emoticon object into renderable pix_emoticon object
7502 * @param stdClass $emoticon emoticon object
7503 * @param array $attributes explicit HTML attributes to set
7504 * @return pix_emoticon
7506 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7507 $stringmanager = get_string_manager();
7508 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7509 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7510 } else {
7511 $alt = s($emoticon->text);
7513 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7517 * Encodes the array of emoticon objects into a string storable in config table
7519 * @see self::decode_stored_config()
7520 * @param array $emoticons array of emtocion objects
7521 * @return string
7523 public function encode_stored_config(array $emoticons) {
7524 return json_encode($emoticons);
7528 * Decodes the string into an array of emoticon objects
7530 * @see self::encode_stored_config()
7531 * @param string $encoded
7532 * @return string|null
7534 public function decode_stored_config($encoded) {
7535 $decoded = json_decode($encoded);
7536 if (!is_array($decoded)) {
7537 return null;
7539 return $decoded;
7543 * Returns default set of emoticons supported by Moodle
7545 * @return array of sdtClasses
7547 public function default_emoticons() {
7548 return array(
7549 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7550 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7551 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7552 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7553 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7554 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7555 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7556 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7557 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7558 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7559 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7560 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7561 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7562 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7563 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7564 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7565 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7566 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7567 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7568 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7569 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7570 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7571 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7572 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7573 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7574 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7575 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7576 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7577 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7578 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7583 * Helper method preparing the stdClass with the emoticon properties
7585 * @param string|array $text or array of strings
7586 * @param string $imagename to be used by {@link pix_emoticon}
7587 * @param string $altidentifier alternative string identifier, null for no alt
7588 * @param string $altcomponent where the alternative string is defined
7589 * @param string $imagecomponent to be used by {@link pix_emoticon}
7590 * @return stdClass
7592 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7593 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7594 return (object)array(
7595 'text' => $text,
7596 'imagename' => $imagename,
7597 'imagecomponent' => $imagecomponent,
7598 'altidentifier' => $altidentifier,
7599 'altcomponent' => $altcomponent,
7604 // ENCRYPTION.
7607 * rc4encrypt
7609 * @param string $data Data to encrypt.
7610 * @return string The now encrypted data.
7612 function rc4encrypt($data) {
7613 return endecrypt(get_site_identifier(), $data, '');
7617 * rc4decrypt
7619 * @param string $data Data to decrypt.
7620 * @return string The now decrypted data.
7622 function rc4decrypt($data) {
7623 return endecrypt(get_site_identifier(), $data, 'de');
7627 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7629 * @todo Finish documenting this function
7631 * @param string $pwd The password to use when encrypting or decrypting
7632 * @param string $data The data to be decrypted/encrypted
7633 * @param string $case Either 'de' for decrypt or '' for encrypt
7634 * @return string
7636 function endecrypt ($pwd, $data, $case) {
7638 if ($case == 'de') {
7639 $data = urldecode($data);
7642 $key[] = '';
7643 $box[] = '';
7644 $pwdlength = strlen($pwd);
7646 for ($i = 0; $i <= 255; $i++) {
7647 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7648 $box[$i] = $i;
7651 $x = 0;
7653 for ($i = 0; $i <= 255; $i++) {
7654 $x = ($x + $box[$i] + $key[$i]) % 256;
7655 $tempswap = $box[$i];
7656 $box[$i] = $box[$x];
7657 $box[$x] = $tempswap;
7660 $cipher = '';
7662 $a = 0;
7663 $j = 0;
7665 for ($i = 0; $i < strlen($data); $i++) {
7666 $a = ($a + 1) % 256;
7667 $j = ($j + $box[$a]) % 256;
7668 $temp = $box[$a];
7669 $box[$a] = $box[$j];
7670 $box[$j] = $temp;
7671 $k = $box[(($box[$a] + $box[$j]) % 256)];
7672 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7673 $cipher .= chr($cipherby);
7676 if ($case == 'de') {
7677 $cipher = urldecode(urlencode($cipher));
7678 } else {
7679 $cipher = urlencode($cipher);
7682 return $cipher;
7685 // ENVIRONMENT CHECKING.
7688 * This method validates a plug name. It is much faster than calling clean_param.
7690 * @param string $name a string that might be a plugin name.
7691 * @return bool if this string is a valid plugin name.
7693 function is_valid_plugin_name($name) {
7694 // This does not work for 'mod', bad luck, use any other type.
7695 return core_component::is_valid_plugin_name('tool', $name);
7699 * Get a list of all the plugins of a given type that define a certain API function
7700 * in a certain file. The plugin component names and function names are returned.
7702 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7703 * @param string $function the part of the name of the function after the
7704 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7705 * names like report_courselist_hook.
7706 * @param string $file the name of file within the plugin that defines the
7707 * function. Defaults to lib.php.
7708 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7709 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7711 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7712 global $CFG;
7714 // We don't include here as all plugin types files would be included.
7715 $plugins = get_plugins_with_function($function, $file, false);
7717 if (empty($plugins[$plugintype])) {
7718 return array();
7721 $allplugins = core_component::get_plugin_list($plugintype);
7723 // Reformat the array and include the files.
7724 $pluginfunctions = array();
7725 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7727 // Check that it has not been removed and the file is still available.
7728 if (!empty($allplugins[$pluginname])) {
7730 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7731 if (file_exists($filepath)) {
7732 include_once($filepath);
7733 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7738 return $pluginfunctions;
7742 * Get a list of all the plugins that define a certain API function in a certain file.
7744 * @param string $function the part of the name of the function after the
7745 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7746 * names like report_courselist_hook.
7747 * @param string $file the name of file within the plugin that defines the
7748 * function. Defaults to lib.php.
7749 * @param bool $include Whether to include the files that contain the functions or not.
7750 * @return array with [plugintype][plugin] = functionname
7752 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7753 global $CFG;
7755 if (during_initial_install() || isset($CFG->upgraderunning)) {
7756 // API functions _must not_ be called during an installation or upgrade.
7757 return [];
7760 $cache = \cache::make('core', 'plugin_functions');
7762 // Including both although I doubt that we will find two functions definitions with the same name.
7763 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7764 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7765 $pluginfunctions = $cache->get($key);
7767 // Use the plugin manager to check that plugins are currently installed.
7768 $pluginmanager = \core_plugin_manager::instance();
7770 if ($pluginfunctions !== false) {
7772 // Checking that the files are still available.
7773 foreach ($pluginfunctions as $plugintype => $plugins) {
7775 $allplugins = \core_component::get_plugin_list($plugintype);
7776 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7777 foreach ($plugins as $plugin => $function) {
7778 if (!isset($installedplugins[$plugin])) {
7779 // Plugin code is still present on disk but it is not installed.
7780 unset($pluginfunctions[$plugintype][$plugin]);
7781 continue;
7784 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7785 if (empty($allplugins[$plugin])) {
7786 unset($pluginfunctions[$plugintype][$plugin]);
7787 continue;
7790 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7791 if ($include && $fileexists) {
7792 // Include the files if it was requested.
7793 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7794 } else if (!$fileexists) {
7795 // If the file is not available any more it should not be returned.
7796 unset($pluginfunctions[$plugintype][$plugin]);
7800 return $pluginfunctions;
7803 $pluginfunctions = array();
7805 // To fill the cached. Also, everything should continue working with cache disabled.
7806 $plugintypes = \core_component::get_plugin_types();
7807 foreach ($plugintypes as $plugintype => $unused) {
7809 // We need to include files here.
7810 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7811 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7812 foreach ($pluginswithfile as $plugin => $notused) {
7814 if (!isset($installedplugins[$plugin])) {
7815 continue;
7818 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7820 $pluginfunction = false;
7821 if (function_exists($fullfunction)) {
7822 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7823 $pluginfunction = $fullfunction;
7825 } else if ($plugintype === 'mod') {
7826 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7827 $shortfunction = $plugin . '_' . $function;
7828 if (function_exists($shortfunction)) {
7829 $pluginfunction = $shortfunction;
7833 if ($pluginfunction) {
7834 if (empty($pluginfunctions[$plugintype])) {
7835 $pluginfunctions[$plugintype] = array();
7837 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7842 $cache->set($key, $pluginfunctions);
7844 return $pluginfunctions;
7849 * Lists plugin-like directories within specified directory
7851 * This function was originally used for standard Moodle plugins, please use
7852 * new core_component::get_plugin_list() now.
7854 * This function is used for general directory listing and backwards compatility.
7856 * @param string $directory relative directory from root
7857 * @param string $exclude dir name to exclude from the list (defaults to none)
7858 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7859 * @return array Sorted array of directory names found under the requested parameters
7861 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7862 global $CFG;
7864 $plugins = array();
7866 if (empty($basedir)) {
7867 $basedir = $CFG->dirroot .'/'. $directory;
7869 } else {
7870 $basedir = $basedir .'/'. $directory;
7873 if ($CFG->debugdeveloper and empty($exclude)) {
7874 // Make sure devs do not use this to list normal plugins,
7875 // this is intended for general directories that are not plugins!
7877 $subtypes = core_component::get_plugin_types();
7878 if (in_array($basedir, $subtypes)) {
7879 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7881 unset($subtypes);
7884 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7885 if (!$dirhandle = opendir($basedir)) {
7886 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7887 return array();
7889 while (false !== ($dir = readdir($dirhandle))) {
7890 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7891 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7892 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7893 continue;
7895 if (filetype($basedir .'/'. $dir) != 'dir') {
7896 continue;
7898 $plugins[] = $dir;
7900 closedir($dirhandle);
7902 if ($plugins) {
7903 asort($plugins);
7905 return $plugins;
7909 * Invoke plugin's callback functions
7911 * @param string $type plugin type e.g. 'mod'
7912 * @param string $name plugin name
7913 * @param string $feature feature name
7914 * @param string $action feature's action
7915 * @param array $params parameters of callback function, should be an array
7916 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7917 * @return mixed
7919 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7921 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7922 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7926 * Invoke component's callback functions
7928 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7929 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7930 * @param array $params parameters of callback function
7931 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7932 * @return mixed
7934 function component_callback($component, $function, array $params = array(), $default = null) {
7936 $functionname = component_callback_exists($component, $function);
7938 if ($functionname) {
7939 // Function exists, so just return function result.
7940 $ret = call_user_func_array($functionname, $params);
7941 if (is_null($ret)) {
7942 return $default;
7943 } else {
7944 return $ret;
7947 return $default;
7951 * Determine if a component callback exists and return the function name to call. Note that this
7952 * function will include the required library files so that the functioname returned can be
7953 * called directly.
7955 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7956 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7957 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7958 * @throws coding_exception if invalid component specfied
7960 function component_callback_exists($component, $function) {
7961 global $CFG; // This is needed for the inclusions.
7963 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7964 if (empty($cleancomponent)) {
7965 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7967 $component = $cleancomponent;
7969 list($type, $name) = core_component::normalize_component($component);
7970 $component = $type . '_' . $name;
7972 $oldfunction = $name.'_'.$function;
7973 $function = $component.'_'.$function;
7975 $dir = core_component::get_component_directory($component);
7976 if (empty($dir)) {
7977 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7980 // Load library and look for function.
7981 if (file_exists($dir.'/lib.php')) {
7982 require_once($dir.'/lib.php');
7985 if (!function_exists($function) and function_exists($oldfunction)) {
7986 if ($type !== 'mod' and $type !== 'core') {
7987 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7989 $function = $oldfunction;
7992 if (function_exists($function)) {
7993 return $function;
7995 return false;
7999 * Call the specified callback method on the provided class.
8001 * If the callback returns null, then the default value is returned instead.
8002 * If the class does not exist, then the default value is returned.
8004 * @param string $classname The name of the class to call upon.
8005 * @param string $methodname The name of the staticically defined method on the class.
8006 * @param array $params The arguments to pass into the method.
8007 * @param mixed $default The default value.
8008 * @return mixed The return value.
8010 function component_class_callback($classname, $methodname, array $params, $default = null) {
8011 if (!class_exists($classname)) {
8012 return $default;
8015 if (!method_exists($classname, $methodname)) {
8016 return $default;
8019 $fullfunction = $classname . '::' . $methodname;
8020 $result = call_user_func_array($fullfunction, $params);
8022 if (null === $result) {
8023 return $default;
8024 } else {
8025 return $result;
8030 * Checks whether a plugin supports a specified feature.
8032 * @param string $type Plugin type e.g. 'mod'
8033 * @param string $name Plugin name e.g. 'forum'
8034 * @param string $feature Feature code (FEATURE_xx constant)
8035 * @param mixed $default default value if feature support unknown
8036 * @return mixed Feature result (false if not supported, null if feature is unknown,
8037 * otherwise usually true but may have other feature-specific value such as array)
8038 * @throws coding_exception
8040 function plugin_supports($type, $name, $feature, $default = null) {
8041 global $CFG;
8043 if ($type === 'mod' and $name === 'NEWMODULE') {
8044 // Somebody forgot to rename the module template.
8045 return false;
8048 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
8049 if (empty($component)) {
8050 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8053 $function = null;
8055 if ($type === 'mod') {
8056 // We need this special case because we support subplugins in modules,
8057 // otherwise it would end up in infinite loop.
8058 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8059 include_once("$CFG->dirroot/mod/$name/lib.php");
8060 $function = $component.'_supports';
8061 if (!function_exists($function)) {
8062 // Legacy non-frankenstyle function name.
8063 $function = $name.'_supports';
8067 } else {
8068 if (!$path = core_component::get_plugin_directory($type, $name)) {
8069 // Non existent plugin type.
8070 return false;
8072 if (file_exists("$path/lib.php")) {
8073 include_once("$path/lib.php");
8074 $function = $component.'_supports';
8078 if ($function and function_exists($function)) {
8079 $supports = $function($feature);
8080 if (is_null($supports)) {
8081 // Plugin does not know - use default.
8082 return $default;
8083 } else {
8084 return $supports;
8088 // Plugin does not care, so use default.
8089 return $default;
8093 * Returns true if the current version of PHP is greater that the specified one.
8095 * @todo Check PHP version being required here is it too low?
8097 * @param string $version The version of php being tested.
8098 * @return bool
8100 function check_php_version($version='5.2.4') {
8101 return (version_compare(phpversion(), $version) >= 0);
8105 * Determine if moodle installation requires update.
8107 * Checks version numbers of main code and all plugins to see
8108 * if there are any mismatches.
8110 * @return bool
8112 function moodle_needs_upgrading() {
8113 global $CFG;
8115 if (empty($CFG->version)) {
8116 return true;
8119 // There is no need to purge plugininfo caches here because
8120 // these caches are not used during upgrade and they are purged after
8121 // every upgrade.
8123 if (empty($CFG->allversionshash)) {
8124 return true;
8127 $hash = core_component::get_all_versions_hash();
8129 return ($hash !== $CFG->allversionshash);
8133 * Returns the major version of this site
8135 * Moodle version numbers consist of three numbers separated by a dot, for
8136 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
8137 * called major version. This function extracts the major version from either
8138 * $CFG->release (default) or eventually from the $release variable defined in
8139 * the main version.php.
8141 * @param bool $fromdisk should the version if source code files be used
8142 * @return string|false the major version like '2.3', false if could not be determined
8144 function moodle_major_version($fromdisk = false) {
8145 global $CFG;
8147 if ($fromdisk) {
8148 $release = null;
8149 require($CFG->dirroot.'/version.php');
8150 if (empty($release)) {
8151 return false;
8154 } else {
8155 if (empty($CFG->release)) {
8156 return false;
8158 $release = $CFG->release;
8161 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8162 return $matches[0];
8163 } else {
8164 return false;
8168 // MISCELLANEOUS.
8171 * Gets the system locale
8173 * @return string Retuns the current locale.
8175 function moodle_getlocale() {
8176 global $CFG;
8178 // Fetch the correct locale based on ostype.
8179 if ($CFG->ostype == 'WINDOWS') {
8180 $stringtofetch = 'localewin';
8181 } else {
8182 $stringtofetch = 'locale';
8185 if (!empty($CFG->locale)) { // Override locale for all language packs.
8186 return $CFG->locale;
8189 return get_string($stringtofetch, 'langconfig');
8193 * Sets the system locale
8195 * @category string
8196 * @param string $locale Can be used to force a locale
8198 function moodle_setlocale($locale='') {
8199 global $CFG;
8201 static $currentlocale = ''; // Last locale caching.
8203 $oldlocale = $currentlocale;
8205 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8206 if (!empty($locale)) {
8207 $currentlocale = $locale;
8208 } else {
8209 $currentlocale = moodle_getlocale();
8212 // Do nothing if locale already set up.
8213 if ($oldlocale == $currentlocale) {
8214 return;
8217 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8218 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8219 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8221 // Get current values.
8222 $monetary= setlocale (LC_MONETARY, 0);
8223 $numeric = setlocale (LC_NUMERIC, 0);
8224 $ctype = setlocale (LC_CTYPE, 0);
8225 if ($CFG->ostype != 'WINDOWS') {
8226 $messages= setlocale (LC_MESSAGES, 0);
8228 // Set locale to all.
8229 $result = setlocale (LC_ALL, $currentlocale);
8230 // If setting of locale fails try the other utf8 or utf-8 variant,
8231 // some operating systems support both (Debian), others just one (OSX).
8232 if ($result === false) {
8233 if (stripos($currentlocale, '.UTF-8') !== false) {
8234 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8235 setlocale (LC_ALL, $newlocale);
8236 } else if (stripos($currentlocale, '.UTF8') !== false) {
8237 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8238 setlocale (LC_ALL, $newlocale);
8241 // Set old values.
8242 setlocale (LC_MONETARY, $monetary);
8243 setlocale (LC_NUMERIC, $numeric);
8244 if ($CFG->ostype != 'WINDOWS') {
8245 setlocale (LC_MESSAGES, $messages);
8247 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8248 // To workaround a well-known PHP problem with Turkish letter Ii.
8249 setlocale (LC_CTYPE, $ctype);
8254 * Count words in a string.
8256 * Words are defined as things between whitespace.
8258 * @category string
8259 * @param string $string The text to be searched for words.
8260 * @return int The count of words in the specified string
8262 function count_words($string) {
8263 $string = strip_tags($string);
8264 // Decode HTML entities.
8265 $string = html_entity_decode($string);
8266 // Replace underscores (which are classed as word characters) with spaces.
8267 $string = preg_replace('/_/u', ' ', $string);
8268 // Remove any characters that shouldn't be treated as word boundaries.
8269 $string = preg_replace('/[\'"’-]/u', '', $string);
8270 // Remove dots and commas from within numbers only.
8271 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
8273 return count(preg_split('/\w\b/u', $string)) - 1;
8277 * Count letters in a string.
8279 * Letters are defined as chars not in tags and different from whitespace.
8281 * @category string
8282 * @param string $string The text to be searched for letters.
8283 * @return int The count of letters in the specified text.
8285 function count_letters($string) {
8286 $string = strip_tags($string); // Tags are out now.
8287 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8289 return core_text::strlen($string);
8293 * Generate and return a random string of the specified length.
8295 * @param int $length The length of the string to be created.
8296 * @return string
8298 function random_string($length=15) {
8299 $randombytes = random_bytes_emulate($length);
8300 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8301 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8302 $pool .= '0123456789';
8303 $poollen = strlen($pool);
8304 $string = '';
8305 for ($i = 0; $i < $length; $i++) {
8306 $rand = ord($randombytes[$i]);
8307 $string .= substr($pool, ($rand%($poollen)), 1);
8309 return $string;
8313 * Generate a complex random string (useful for md5 salts)
8315 * This function is based on the above {@link random_string()} however it uses a
8316 * larger pool of characters and generates a string between 24 and 32 characters
8318 * @param int $length Optional if set generates a string to exactly this length
8319 * @return string
8321 function complex_random_string($length=null) {
8322 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8323 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8324 $poollen = strlen($pool);
8325 if ($length===null) {
8326 $length = floor(rand(24, 32));
8328 $randombytes = random_bytes_emulate($length);
8329 $string = '';
8330 for ($i = 0; $i < $length; $i++) {
8331 $rand = ord($randombytes[$i]);
8332 $string .= $pool[($rand%$poollen)];
8334 return $string;
8338 * Try to generates cryptographically secure pseudo-random bytes.
8340 * Note this is achieved by fallbacking between:
8341 * - PHP 7 random_bytes().
8342 * - OpenSSL openssl_random_pseudo_bytes().
8343 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8345 * @param int $length requested length in bytes
8346 * @return string binary data
8348 function random_bytes_emulate($length) {
8349 global $CFG;
8350 if ($length <= 0) {
8351 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8352 return '';
8354 if (function_exists('random_bytes')) {
8355 // Use PHP 7 goodness.
8356 $hash = @random_bytes($length);
8357 if ($hash !== false) {
8358 return $hash;
8361 if (function_exists('openssl_random_pseudo_bytes')) {
8362 // If you have the openssl extension enabled.
8363 $hash = openssl_random_pseudo_bytes($length);
8364 if ($hash !== false) {
8365 return $hash;
8369 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8370 $staticdata = serialize($CFG) . serialize($_SERVER);
8371 $hash = '';
8372 do {
8373 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8374 } while (strlen($hash) < $length);
8376 return substr($hash, 0, $length);
8380 * Given some text (which may contain HTML) and an ideal length,
8381 * this function truncates the text neatly on a word boundary if possible
8383 * @category string
8384 * @param string $text text to be shortened
8385 * @param int $ideal ideal string length
8386 * @param boolean $exact if false, $text will not be cut mid-word
8387 * @param string $ending The string to append if the passed string is truncated
8388 * @return string $truncate shortened string
8390 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8391 // If the plain text is shorter than the maximum length, return the whole text.
8392 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8393 return $text;
8396 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8397 // and only tag in its 'line'.
8398 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8400 $totallength = core_text::strlen($ending);
8401 $truncate = '';
8403 // This array stores information about open and close tags and their position
8404 // in the truncated string. Each item in the array is an object with fields
8405 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8406 // (byte position in truncated text).
8407 $tagdetails = array();
8409 foreach ($lines as $linematchings) {
8410 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8411 if (!empty($linematchings[1])) {
8412 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8413 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8414 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8415 // Record closing tag.
8416 $tagdetails[] = (object) array(
8417 'open' => false,
8418 'tag' => core_text::strtolower($tagmatchings[1]),
8419 'pos' => core_text::strlen($truncate),
8422 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8423 // Record opening tag.
8424 $tagdetails[] = (object) array(
8425 'open' => true,
8426 'tag' => core_text::strtolower($tagmatchings[1]),
8427 'pos' => core_text::strlen($truncate),
8429 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8430 $tagdetails[] = (object) array(
8431 'open' => true,
8432 'tag' => core_text::strtolower('if'),
8433 'pos' => core_text::strlen($truncate),
8435 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8436 $tagdetails[] = (object) array(
8437 'open' => false,
8438 'tag' => core_text::strtolower('if'),
8439 'pos' => core_text::strlen($truncate),
8443 // Add html-tag to $truncate'd text.
8444 $truncate .= $linematchings[1];
8447 // Calculate the length of the plain text part of the line; handle entities as one character.
8448 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8449 if ($totallength + $contentlength > $ideal) {
8450 // The number of characters which are left.
8451 $left = $ideal - $totallength;
8452 $entitieslength = 0;
8453 // Search for html entities.
8454 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)) {
8455 // Calculate the real length of all entities in the legal range.
8456 foreach ($entities[0] as $entity) {
8457 if ($entity[1]+1-$entitieslength <= $left) {
8458 $left--;
8459 $entitieslength += core_text::strlen($entity[0]);
8460 } else {
8461 // No more characters left.
8462 break;
8466 $breakpos = $left + $entitieslength;
8468 // If the words shouldn't be cut in the middle...
8469 if (!$exact) {
8470 // Search the last occurence of a space.
8471 for (; $breakpos > 0; $breakpos--) {
8472 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8473 if ($char === '.' or $char === ' ') {
8474 $breakpos += 1;
8475 break;
8476 } else if (strlen($char) > 2) {
8477 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8478 $breakpos += 1;
8479 break;
8484 if ($breakpos == 0) {
8485 // This deals with the test_shorten_text_no_spaces case.
8486 $breakpos = $left + $entitieslength;
8487 } else if ($breakpos > $left + $entitieslength) {
8488 // This deals with the previous for loop breaking on the first char.
8489 $breakpos = $left + $entitieslength;
8492 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8493 // Maximum length is reached, so get off the loop.
8494 break;
8495 } else {
8496 $truncate .= $linematchings[2];
8497 $totallength += $contentlength;
8500 // If the maximum length is reached, get off the loop.
8501 if ($totallength >= $ideal) {
8502 break;
8506 // Add the defined ending to the text.
8507 $truncate .= $ending;
8509 // Now calculate the list of open html tags based on the truncate position.
8510 $opentags = array();
8511 foreach ($tagdetails as $taginfo) {
8512 if ($taginfo->open) {
8513 // Add tag to the beginning of $opentags list.
8514 array_unshift($opentags, $taginfo->tag);
8515 } else {
8516 // Can have multiple exact same open tags, close the last one.
8517 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8518 if ($pos !== false) {
8519 unset($opentags[$pos]);
8524 // Close all unclosed html-tags.
8525 foreach ($opentags as $tag) {
8526 if ($tag === 'if') {
8527 $truncate .= '<!--<![endif]-->';
8528 } else {
8529 $truncate .= '</' . $tag . '>';
8533 return $truncate;
8537 * Shortens a given filename by removing characters positioned after the ideal string length.
8538 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8539 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8541 * @param string $filename file name
8542 * @param int $length ideal string length
8543 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8544 * @return string $shortened shortened file name
8546 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8547 $shortened = $filename;
8548 // Extract a part of the filename if it's char size exceeds the ideal string length.
8549 if (core_text::strlen($filename) > $length) {
8550 // Exclude extension if present in filename.
8551 $mimetypes = get_mimetypes_array();
8552 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8553 if ($extension && !empty($mimetypes[$extension])) {
8554 $basename = pathinfo($filename, PATHINFO_FILENAME);
8555 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8556 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8557 $shortened .= '.' . $extension;
8558 } else {
8559 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8560 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8563 return $shortened;
8567 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8569 * @param array $path The paths to reduce the length.
8570 * @param int $length Ideal string length
8571 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8572 * @return array $result Shortened paths in array.
8574 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8575 $result = null;
8577 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8578 $carry[] = shorten_filename($singlepath, $length, $includehash);
8579 return $carry;
8580 }, []);
8582 return $result;
8586 * Given dates in seconds, how many weeks is the date from startdate
8587 * The first week is 1, the second 2 etc ...
8589 * @param int $startdate Timestamp for the start date
8590 * @param int $thedate Timestamp for the end date
8591 * @return string
8593 function getweek ($startdate, $thedate) {
8594 if ($thedate < $startdate) {
8595 return 0;
8598 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8602 * Returns a randomly generated password of length $maxlen. inspired by
8604 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8605 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8607 * @param int $maxlen The maximum size of the password being generated.
8608 * @return string
8610 function generate_password($maxlen=10) {
8611 global $CFG;
8613 if (empty($CFG->passwordpolicy)) {
8614 $fillers = PASSWORD_DIGITS;
8615 $wordlist = file($CFG->wordlist);
8616 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8617 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8618 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8619 $password = $word1 . $filler1 . $word2;
8620 } else {
8621 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8622 $digits = $CFG->minpassworddigits;
8623 $lower = $CFG->minpasswordlower;
8624 $upper = $CFG->minpasswordupper;
8625 $nonalphanum = $CFG->minpasswordnonalphanum;
8626 $total = $lower + $upper + $digits + $nonalphanum;
8627 // Var minlength should be the greater one of the two ( $minlen and $total ).
8628 $minlen = $minlen < $total ? $total : $minlen;
8629 // Var maxlen can never be smaller than minlen.
8630 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8631 $additional = $maxlen - $total;
8633 // Make sure we have enough characters to fulfill
8634 // complexity requirements.
8635 $passworddigits = PASSWORD_DIGITS;
8636 while ($digits > strlen($passworddigits)) {
8637 $passworddigits .= PASSWORD_DIGITS;
8639 $passwordlower = PASSWORD_LOWER;
8640 while ($lower > strlen($passwordlower)) {
8641 $passwordlower .= PASSWORD_LOWER;
8643 $passwordupper = PASSWORD_UPPER;
8644 while ($upper > strlen($passwordupper)) {
8645 $passwordupper .= PASSWORD_UPPER;
8647 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8648 while ($nonalphanum > strlen($passwordnonalphanum)) {
8649 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8652 // Now mix and shuffle it all.
8653 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8654 substr(str_shuffle ($passwordupper), 0, $upper) .
8655 substr(str_shuffle ($passworddigits), 0, $digits) .
8656 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8657 substr(str_shuffle ($passwordlower .
8658 $passwordupper .
8659 $passworddigits .
8660 $passwordnonalphanum), 0 , $additional));
8663 return substr ($password, 0, $maxlen);
8667 * Given a float, prints it nicely.
8668 * Localized floats must not be used in calculations!
8670 * The stripzeros feature is intended for making numbers look nicer in small
8671 * areas where it is not necessary to indicate the degree of accuracy by showing
8672 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8673 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8675 * @param float $float The float to print
8676 * @param int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision).
8677 * @param bool $localized use localized decimal separator
8678 * @param bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after
8679 * the decimal point are always striped if $decimalpoints is -1.
8680 * @return string locale float
8682 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8683 if (is_null($float)) {
8684 return '';
8686 if ($localized) {
8687 $separator = get_string('decsep', 'langconfig');
8688 } else {
8689 $separator = '.';
8691 if ($decimalpoints == -1) {
8692 // The following counts the number of decimals.
8693 // It is safe as both floatval() and round() functions have same behaviour when non-numeric values are provided.
8694 $floatval = floatval($float);
8695 for ($decimalpoints = 0; $floatval != round($float, $decimalpoints); $decimalpoints++);
8698 $result = number_format($float, $decimalpoints, $separator, '');
8699 if ($stripzeros) {
8700 // Remove zeros and final dot if not needed.
8701 $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
8703 return $result;
8707 * Converts locale specific floating point/comma number back to standard PHP float value
8708 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8710 * @param string $localefloat locale aware float representation
8711 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8712 * @return mixed float|bool - false or the parsed float.
8714 function unformat_float($localefloat, $strict = false) {
8715 $localefloat = trim($localefloat);
8717 if ($localefloat == '') {
8718 return null;
8721 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8722 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8724 if ($strict && !is_numeric($localefloat)) {
8725 return false;
8728 return (float)$localefloat;
8732 * Given a simple array, this shuffles it up just like shuffle()
8733 * Unlike PHP's shuffle() this function works on any machine.
8735 * @param array $array The array to be rearranged
8736 * @return array
8738 function swapshuffle($array) {
8740 $last = count($array) - 1;
8741 for ($i = 0; $i <= $last; $i++) {
8742 $from = rand(0, $last);
8743 $curr = $array[$i];
8744 $array[$i] = $array[$from];
8745 $array[$from] = $curr;
8747 return $array;
8751 * Like {@link swapshuffle()}, but works on associative arrays
8753 * @param array $array The associative array to be rearranged
8754 * @return array
8756 function swapshuffle_assoc($array) {
8758 $newarray = array();
8759 $newkeys = swapshuffle(array_keys($array));
8761 foreach ($newkeys as $newkey) {
8762 $newarray[$newkey] = $array[$newkey];
8764 return $newarray;
8768 * Given an arbitrary array, and a number of draws,
8769 * this function returns an array with that amount
8770 * of items. The indexes are retained.
8772 * @todo Finish documenting this function
8774 * @param array $array
8775 * @param int $draws
8776 * @return array
8778 function draw_rand_array($array, $draws) {
8780 $return = array();
8782 $last = count($array);
8784 if ($draws > $last) {
8785 $draws = $last;
8788 while ($draws > 0) {
8789 $last--;
8791 $keys = array_keys($array);
8792 $rand = rand(0, $last);
8794 $return[$keys[$rand]] = $array[$keys[$rand]];
8795 unset($array[$keys[$rand]]);
8797 $draws--;
8800 return $return;
8804 * Calculate the difference between two microtimes
8806 * @param string $a The first Microtime
8807 * @param string $b The second Microtime
8808 * @return string
8810 function microtime_diff($a, $b) {
8811 list($adec, $asec) = explode(' ', $a);
8812 list($bdec, $bsec) = explode(' ', $b);
8813 return $bsec - $asec + $bdec - $adec;
8817 * Given a list (eg a,b,c,d,e) this function returns
8818 * an array of 1->a, 2->b, 3->c etc
8820 * @param string $list The string to explode into array bits
8821 * @param string $separator The separator used within the list string
8822 * @return array The now assembled array
8824 function make_menu_from_list($list, $separator=',') {
8826 $array = array_reverse(explode($separator, $list), true);
8827 foreach ($array as $key => $item) {
8828 $outarray[$key+1] = trim($item);
8830 return $outarray;
8834 * Creates an array that represents all the current grades that
8835 * can be chosen using the given grading type.
8837 * Negative numbers
8838 * are scales, zero is no grade, and positive numbers are maximum
8839 * grades.
8841 * @todo Finish documenting this function or better deprecated this completely!
8843 * @param int $gradingtype
8844 * @return array
8846 function make_grades_menu($gradingtype) {
8847 global $DB;
8849 $grades = array();
8850 if ($gradingtype < 0) {
8851 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8852 return make_menu_from_list($scale->scale);
8854 } else if ($gradingtype > 0) {
8855 for ($i=$gradingtype; $i>=0; $i--) {
8856 $grades[$i] = $i .' / '. $gradingtype;
8858 return $grades;
8860 return $grades;
8864 * make_unique_id_code
8866 * @todo Finish documenting this function
8868 * @uses $_SERVER
8869 * @param string $extra Extra string to append to the end of the code
8870 * @return string
8872 function make_unique_id_code($extra = '') {
8874 $hostname = 'unknownhost';
8875 if (!empty($_SERVER['HTTP_HOST'])) {
8876 $hostname = $_SERVER['HTTP_HOST'];
8877 } else if (!empty($_ENV['HTTP_HOST'])) {
8878 $hostname = $_ENV['HTTP_HOST'];
8879 } else if (!empty($_SERVER['SERVER_NAME'])) {
8880 $hostname = $_SERVER['SERVER_NAME'];
8881 } else if (!empty($_ENV['SERVER_NAME'])) {
8882 $hostname = $_ENV['SERVER_NAME'];
8885 $date = gmdate("ymdHis");
8887 $random = random_string(6);
8889 if ($extra) {
8890 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8891 } else {
8892 return $hostname .'+'. $date .'+'. $random;
8898 * Function to check the passed address is within the passed subnet
8900 * The parameter is a comma separated string of subnet definitions.
8901 * Subnet strings can be in one of three formats:
8902 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8903 * 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)
8904 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8905 * Code for type 1 modified from user posted comments by mediator at
8906 * {@link http://au.php.net/manual/en/function.ip2long.php}
8908 * @param string $addr The address you are checking
8909 * @param string $subnetstr The string of subnet addresses
8910 * @return bool
8912 function address_in_subnet($addr, $subnetstr) {
8914 if ($addr == '0.0.0.0') {
8915 return false;
8917 $subnets = explode(',', $subnetstr);
8918 $found = false;
8919 $addr = trim($addr);
8920 $addr = cleanremoteaddr($addr, false); // Normalise.
8921 if ($addr === null) {
8922 return false;
8924 $addrparts = explode(':', $addr);
8926 $ipv6 = strpos($addr, ':');
8928 foreach ($subnets as $subnet) {
8929 $subnet = trim($subnet);
8930 if ($subnet === '') {
8931 continue;
8934 if (strpos($subnet, '/') !== false) {
8935 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8936 list($ip, $mask) = explode('/', $subnet);
8937 $mask = trim($mask);
8938 if (!is_number($mask)) {
8939 continue; // Incorect mask number, eh?
8941 $ip = cleanremoteaddr($ip, false); // Normalise.
8942 if ($ip === null) {
8943 continue;
8945 if (strpos($ip, ':') !== false) {
8946 // IPv6.
8947 if (!$ipv6) {
8948 continue;
8950 if ($mask > 128 or $mask < 0) {
8951 continue; // Nonsense.
8953 if ($mask == 0) {
8954 return true; // Any address.
8956 if ($mask == 128) {
8957 if ($ip === $addr) {
8958 return true;
8960 continue;
8962 $ipparts = explode(':', $ip);
8963 $modulo = $mask % 16;
8964 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8965 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8966 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8967 if ($modulo == 0) {
8968 return true;
8970 $pos = ($mask-$modulo)/16;
8971 $ipnet = hexdec($ipparts[$pos]);
8972 $addrnet = hexdec($addrparts[$pos]);
8973 $mask = 0xffff << (16 - $modulo);
8974 if (($addrnet & $mask) == ($ipnet & $mask)) {
8975 return true;
8979 } else {
8980 // IPv4.
8981 if ($ipv6) {
8982 continue;
8984 if ($mask > 32 or $mask < 0) {
8985 continue; // Nonsense.
8987 if ($mask == 0) {
8988 return true;
8990 if ($mask == 32) {
8991 if ($ip === $addr) {
8992 return true;
8994 continue;
8996 $mask = 0xffffffff << (32 - $mask);
8997 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8998 return true;
9002 } else if (strpos($subnet, '-') !== false) {
9003 // 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.
9004 $parts = explode('-', $subnet);
9005 if (count($parts) != 2) {
9006 continue;
9009 if (strpos($subnet, ':') !== false) {
9010 // IPv6.
9011 if (!$ipv6) {
9012 continue;
9014 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9015 if ($ipstart === null) {
9016 continue;
9018 $ipparts = explode(':', $ipstart);
9019 $start = hexdec(array_pop($ipparts));
9020 $ipparts[] = trim($parts[1]);
9021 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
9022 if ($ipend === null) {
9023 continue;
9025 $ipparts[7] = '';
9026 $ipnet = implode(':', $ipparts);
9027 if (strpos($addr, $ipnet) !== 0) {
9028 continue;
9030 $ipparts = explode(':', $ipend);
9031 $end = hexdec($ipparts[7]);
9033 $addrend = hexdec($addrparts[7]);
9035 if (($addrend >= $start) and ($addrend <= $end)) {
9036 return true;
9039 } else {
9040 // IPv4.
9041 if ($ipv6) {
9042 continue;
9044 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9045 if ($ipstart === null) {
9046 continue;
9048 $ipparts = explode('.', $ipstart);
9049 $ipparts[3] = trim($parts[1]);
9050 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
9051 if ($ipend === null) {
9052 continue;
9055 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9056 return true;
9060 } else {
9061 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9062 if (strpos($subnet, ':') !== false) {
9063 // IPv6.
9064 if (!$ipv6) {
9065 continue;
9067 $parts = explode(':', $subnet);
9068 $count = count($parts);
9069 if ($parts[$count-1] === '') {
9070 unset($parts[$count-1]); // Trim trailing :'s.
9071 $count--;
9072 $subnet = implode('.', $parts);
9074 $isip = cleanremoteaddr($subnet, false); // Normalise.
9075 if ($isip !== null) {
9076 if ($isip === $addr) {
9077 return true;
9079 continue;
9080 } else if ($count > 8) {
9081 continue;
9083 $zeros = array_fill(0, 8-$count, '0');
9084 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9085 if (address_in_subnet($addr, $subnet)) {
9086 return true;
9089 } else {
9090 // IPv4.
9091 if ($ipv6) {
9092 continue;
9094 $parts = explode('.', $subnet);
9095 $count = count($parts);
9096 if ($parts[$count-1] === '') {
9097 unset($parts[$count-1]); // Trim trailing .
9098 $count--;
9099 $subnet = implode('.', $parts);
9101 if ($count == 4) {
9102 $subnet = cleanremoteaddr($subnet, false); // Normalise.
9103 if ($subnet === $addr) {
9104 return true;
9106 continue;
9107 } else if ($count > 4) {
9108 continue;
9110 $zeros = array_fill(0, 4-$count, '0');
9111 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9112 if (address_in_subnet($addr, $subnet)) {
9113 return true;
9119 return false;
9123 * For outputting debugging info
9125 * @param string $string The string to write
9126 * @param string $eol The end of line char(s) to use
9127 * @param string $sleep Period to make the application sleep
9128 * This ensures any messages have time to display before redirect
9130 function mtrace($string, $eol="\n", $sleep=0) {
9131 global $CFG;
9133 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
9134 $fn = $CFG->mtrace_wrapper;
9135 $fn($string, $eol);
9136 return;
9137 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
9138 // We must explicitly call the add_line function here.
9139 // Uses of fwrite to STDOUT are not picked up by ob_start.
9140 if ($output = \core\task\logmanager::add_line("{$string}{$eol}")) {
9141 fwrite(STDOUT, $output);
9143 } else {
9144 echo $string . $eol;
9147 // Flush again.
9148 flush();
9150 // Delay to keep message on user's screen in case of subsequent redirect.
9151 if ($sleep) {
9152 sleep($sleep);
9157 * Replace 1 or more slashes or backslashes to 1 slash
9159 * @param string $path The path to strip
9160 * @return string the path with double slashes removed
9162 function cleardoubleslashes ($path) {
9163 return preg_replace('/(\/|\\\){1,}/', '/', $path);
9167 * Is the current ip in a given list?
9169 * @param string $list
9170 * @return bool
9172 function remoteip_in_list($list) {
9173 $inlist = false;
9174 $clientip = getremoteaddr(null);
9176 if (!$clientip) {
9177 // Ensure access on cli.
9178 return true;
9181 $list = explode("\n", $list);
9182 foreach ($list as $line) {
9183 $tokens = explode('#', $line);
9184 $subnet = trim($tokens[0]);
9185 if (address_in_subnet($clientip, $subnet)) {
9186 $inlist = true;
9187 break;
9190 return $inlist;
9194 * Returns most reliable client address
9196 * @param string $default If an address can't be determined, then return this
9197 * @return string The remote IP address
9199 function getremoteaddr($default='0.0.0.0') {
9200 global $CFG;
9202 if (empty($CFG->getremoteaddrconf)) {
9203 // This will happen, for example, before just after the upgrade, as the
9204 // user is redirected to the admin screen.
9205 $variablestoskip = 0;
9206 } else {
9207 $variablestoskip = $CFG->getremoteaddrconf;
9209 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
9210 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9211 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9212 return $address ? $address : $default;
9215 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
9216 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9217 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9218 $address = $forwardedaddresses[0];
9220 if (substr_count($address, ":") > 1) {
9221 // Remove port and brackets from IPv6.
9222 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9223 $address = $matches[1];
9225 } else {
9226 // Remove port from IPv4.
9227 if (substr_count($address, ":") == 1) {
9228 $parts = explode(":", $address);
9229 $address = $parts[0];
9233 $address = cleanremoteaddr($address);
9234 return $address ? $address : $default;
9237 if (!empty($_SERVER['REMOTE_ADDR'])) {
9238 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9239 return $address ? $address : $default;
9240 } else {
9241 return $default;
9246 * Cleans an ip address. Internal addresses are now allowed.
9247 * (Originally local addresses were not allowed.)
9249 * @param string $addr IPv4 or IPv6 address
9250 * @param bool $compress use IPv6 address compression
9251 * @return string normalised ip address string, null if error
9253 function cleanremoteaddr($addr, $compress=false) {
9254 $addr = trim($addr);
9256 if (strpos($addr, ':') !== false) {
9257 // Can be only IPv6.
9258 $parts = explode(':', $addr);
9259 $count = count($parts);
9261 if (strpos($parts[$count-1], '.') !== false) {
9262 // Legacy ipv4 notation.
9263 $last = array_pop($parts);
9264 $ipv4 = cleanremoteaddr($last, true);
9265 if ($ipv4 === null) {
9266 return null;
9268 $bits = explode('.', $ipv4);
9269 $parts[] = dechex($bits[0]).dechex($bits[1]);
9270 $parts[] = dechex($bits[2]).dechex($bits[3]);
9271 $count = count($parts);
9272 $addr = implode(':', $parts);
9275 if ($count < 3 or $count > 8) {
9276 return null; // Severly malformed.
9279 if ($count != 8) {
9280 if (strpos($addr, '::') === false) {
9281 return null; // Malformed.
9283 // Uncompress.
9284 $insertat = array_search('', $parts, true);
9285 $missing = array_fill(0, 1 + 8 - $count, '0');
9286 array_splice($parts, $insertat, 1, $missing);
9287 foreach ($parts as $key => $part) {
9288 if ($part === '') {
9289 $parts[$key] = '0';
9294 $adr = implode(':', $parts);
9295 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9296 return null; // Incorrect format - sorry.
9299 // Normalise 0s and case.
9300 $parts = array_map('hexdec', $parts);
9301 $parts = array_map('dechex', $parts);
9303 $result = implode(':', $parts);
9305 if (!$compress) {
9306 return $result;
9309 if ($result === '0:0:0:0:0:0:0:0') {
9310 return '::'; // All addresses.
9313 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9314 if ($compressed !== $result) {
9315 return $compressed;
9318 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9319 if ($compressed !== $result) {
9320 return $compressed;
9323 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9324 if ($compressed !== $result) {
9325 return $compressed;
9328 return $result;
9331 // First get all things that look like IPv4 addresses.
9332 $parts = array();
9333 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9334 return null;
9336 unset($parts[0]);
9338 foreach ($parts as $key => $match) {
9339 if ($match > 255) {
9340 return null;
9342 $parts[$key] = (int)$match; // Normalise 0s.
9345 return implode('.', $parts);
9350 * Is IP address a public address?
9352 * @param string $ip The ip to check
9353 * @return bool true if the ip is public
9355 function ip_is_public($ip) {
9356 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9360 * This function will make a complete copy of anything it's given,
9361 * regardless of whether it's an object or not.
9363 * @param mixed $thing Something you want cloned
9364 * @return mixed What ever it is you passed it
9366 function fullclone($thing) {
9367 return unserialize(serialize($thing));
9371 * Used to make sure that $min <= $value <= $max
9373 * Make sure that value is between min, and max
9375 * @param int $min The minimum value
9376 * @param int $value The value to check
9377 * @param int $max The maximum value
9378 * @return int
9380 function bounded_number($min, $value, $max) {
9381 if ($value < $min) {
9382 return $min;
9384 if ($value > $max) {
9385 return $max;
9387 return $value;
9391 * Check if there is a nested array within the passed array
9393 * @param array $array
9394 * @return bool true if there is a nested array false otherwise
9396 function array_is_nested($array) {
9397 foreach ($array as $value) {
9398 if (is_array($value)) {
9399 return true;
9402 return false;
9406 * get_performance_info() pairs up with init_performance_info()
9407 * loaded in setup.php. Returns an array with 'html' and 'txt'
9408 * values ready for use, and each of the individual stats provided
9409 * separately as well.
9411 * @return array
9413 function get_performance_info() {
9414 global $CFG, $PERF, $DB, $PAGE;
9416 $info = array();
9417 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9419 $info['html'] = '';
9420 if (!empty($CFG->themedesignermode)) {
9421 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9422 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9424 $info['html'] .= '<ul class="list-unstyled ml-1 row">'; // Holds userfriendly HTML representation.
9426 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9428 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9429 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9431 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9432 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9434 if (function_exists('memory_get_usage')) {
9435 $info['memory_total'] = memory_get_usage();
9436 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9437 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9438 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9439 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9442 if (function_exists('memory_get_peak_usage')) {
9443 $info['memory_peak'] = memory_get_peak_usage();
9444 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9445 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9448 $info['html'] .= '</ul><ul class="list-unstyled ml-1 row">';
9449 $inc = get_included_files();
9450 $info['includecount'] = count($inc);
9451 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9452 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9454 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9455 // We can not track more performance before installation or before PAGE init, sorry.
9456 return $info;
9459 $filtermanager = filter_manager::instance();
9460 if (method_exists($filtermanager, 'get_performance_summary')) {
9461 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9462 $info = array_merge($filterinfo, $info);
9463 foreach ($filterinfo as $key => $value) {
9464 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9465 $info['txt'] .= "$key: $value ";
9469 $stringmanager = get_string_manager();
9470 if (method_exists($stringmanager, 'get_performance_summary')) {
9471 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9472 $info = array_merge($filterinfo, $info);
9473 foreach ($filterinfo as $key => $value) {
9474 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9475 $info['txt'] .= "$key: $value ";
9479 if (!empty($PERF->logwrites)) {
9480 $info['logwrites'] = $PERF->logwrites;
9481 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9482 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9485 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9486 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9487 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9489 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9490 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9491 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9493 if (function_exists('posix_times')) {
9494 $ptimes = posix_times();
9495 if (is_array($ptimes)) {
9496 foreach ($ptimes as $key => $val) {
9497 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9499 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9500 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9501 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9505 // Grab the load average for the last minute.
9506 // /proc will only work under some linux configurations
9507 // while uptime is there under MacOSX/Darwin and other unices.
9508 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9509 list($serverload) = explode(' ', $loadavg[0]);
9510 unset($loadavg);
9511 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9512 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9513 $serverload = $matches[1];
9514 } else {
9515 trigger_error('Could not parse uptime output!');
9518 if (!empty($serverload)) {
9519 $info['serverload'] = $serverload;
9520 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9521 $info['txt'] .= "serverload: {$info['serverload']} ";
9524 // Display size of session if session started.
9525 if ($si = \core\session\manager::get_performance_info()) {
9526 $info['sessionsize'] = $si['size'];
9527 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9528 $info['txt'] .= $si['txt'];
9531 $info['html'] .= '</ul>';
9532 if ($stats = cache_helper::get_stats()) {
9533 $html = '<ul class="cachesused list-unstyled ml-1 row">';
9534 $html .= '<li class="cache-stats-heading font-weight-bold">Caches used (hits/misses/sets)</li>';
9535 $html .= '</ul><ul class="cachesused list-unstyled ml-1">';
9536 $text = 'Caches used (hits/misses/sets): ';
9537 $hits = 0;
9538 $misses = 0;
9539 $sets = 0;
9540 foreach ($stats as $definition => $details) {
9541 switch ($details['mode']) {
9542 case cache_store::MODE_APPLICATION:
9543 $modeclass = 'application';
9544 $mode = ' <span title="application cache">[a]</span>';
9545 break;
9546 case cache_store::MODE_SESSION:
9547 $modeclass = 'session';
9548 $mode = ' <span title="session cache">[s]</span>';
9549 break;
9550 case cache_store::MODE_REQUEST:
9551 $modeclass = 'request';
9552 $mode = ' <span title="request cache">[r]</span>';
9553 break;
9555 $html .= '<li class="d-inline-flex"><ul class="cache-definition-stats list-unstyled ml-1 mb-1 cache-mode-'.$modeclass.' card d-inline-block">';
9556 $html .= '<li class="cache-definition-stats-heading p-t-1 card-header bg-dark bg-inverse font-weight-bold">' .
9557 $definition . $mode.'</li>';
9558 $text .= "$definition {";
9559 foreach ($details['stores'] as $store => $data) {
9560 $hits += $data['hits'];
9561 $misses += $data['misses'];
9562 $sets += $data['sets'];
9563 if ($data['hits'] == 0 and $data['misses'] > 0) {
9564 $cachestoreclass = 'nohits text-danger';
9565 } else if ($data['hits'] < $data['misses']) {
9566 $cachestoreclass = 'lowhits text-warning';
9567 } else {
9568 $cachestoreclass = 'hihits text-success';
9570 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9571 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">" .
9572 "$store: $data[hits] / $data[misses] / $data[sets]</li>";
9573 // This makes boxes of same sizes.
9574 if (count($details['stores']) == 1) {
9575 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">&nbsp;</li>";
9578 $html .= '</ul></li>';
9579 $text .= '} ';
9581 $html .= '</ul> ';
9582 $html .= "<div class='cache-total-stats row'>Total: $hits / $misses / $sets</div>";
9583 $info['cachesused'] = "$hits / $misses / $sets";
9584 $info['html'] .= $html;
9585 $info['txt'] .= $text.'. ';
9586 } else {
9587 $info['cachesused'] = '0 / 0 / 0';
9588 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9589 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9592 $info['html'] = '<div class="performanceinfo siteinfo container-fluid">'.$info['html'].'</div>';
9593 return $info;
9597 * Delete directory or only its content
9599 * @param string $dir directory path
9600 * @param bool $contentonly
9601 * @return bool success, true also if dir does not exist
9603 function remove_dir($dir, $contentonly=false) {
9604 if (!file_exists($dir)) {
9605 // Nothing to do.
9606 return true;
9608 if (!$handle = opendir($dir)) {
9609 return false;
9611 $result = true;
9612 while (false!==($item = readdir($handle))) {
9613 if ($item != '.' && $item != '..') {
9614 if (is_dir($dir.'/'.$item)) {
9615 $result = remove_dir($dir.'/'.$item) && $result;
9616 } else {
9617 $result = unlink($dir.'/'.$item) && $result;
9621 closedir($handle);
9622 if ($contentonly) {
9623 clearstatcache(); // Make sure file stat cache is properly invalidated.
9624 return $result;
9626 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9627 clearstatcache(); // Make sure file stat cache is properly invalidated.
9628 return $result;
9632 * Detect if an object or a class contains a given property
9633 * will take an actual object or the name of a class
9635 * @param mix $obj Name of class or real object to test
9636 * @param string $property name of property to find
9637 * @return bool true if property exists
9639 function object_property_exists( $obj, $property ) {
9640 if (is_string( $obj )) {
9641 $properties = get_class_vars( $obj );
9642 } else {
9643 $properties = get_object_vars( $obj );
9645 return array_key_exists( $property, $properties );
9649 * Converts an object into an associative array
9651 * This function converts an object into an associative array by iterating
9652 * over its public properties. Because this function uses the foreach
9653 * construct, Iterators are respected. It works recursively on arrays of objects.
9654 * Arrays and simple values are returned as is.
9656 * If class has magic properties, it can implement IteratorAggregate
9657 * and return all available properties in getIterator()
9659 * @param mixed $var
9660 * @return array
9662 function convert_to_array($var) {
9663 $result = array();
9665 // Loop over elements/properties.
9666 foreach ($var as $key => $value) {
9667 // Recursively convert objects.
9668 if (is_object($value) || is_array($value)) {
9669 $result[$key] = convert_to_array($value);
9670 } else {
9671 // Simple values are untouched.
9672 $result[$key] = $value;
9675 return $result;
9679 * Detect a custom script replacement in the data directory that will
9680 * replace an existing moodle script
9682 * @return string|bool full path name if a custom script exists, false if no custom script exists
9684 function custom_script_path() {
9685 global $CFG, $SCRIPT;
9687 if ($SCRIPT === null) {
9688 // Probably some weird external script.
9689 return false;
9692 $scriptpath = $CFG->customscripts . $SCRIPT;
9694 // Check the custom script exists.
9695 if (file_exists($scriptpath) and is_file($scriptpath)) {
9696 return $scriptpath;
9697 } else {
9698 return false;
9703 * Returns whether or not the user object is a remote MNET user. This function
9704 * is in moodlelib because it does not rely on loading any of the MNET code.
9706 * @param object $user A valid user object
9707 * @return bool True if the user is from a remote Moodle.
9709 function is_mnet_remote_user($user) {
9710 global $CFG;
9712 if (!isset($CFG->mnet_localhost_id)) {
9713 include_once($CFG->dirroot . '/mnet/lib.php');
9714 $env = new mnet_environment();
9715 $env->init();
9716 unset($env);
9719 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9723 * This function will search for browser prefereed languages, setting Moodle
9724 * to use the best one available if $SESSION->lang is undefined
9726 function setup_lang_from_browser() {
9727 global $CFG, $SESSION, $USER;
9729 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9730 // Lang is defined in session or user profile, nothing to do.
9731 return;
9734 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9735 return;
9738 // Extract and clean langs from headers.
9739 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9740 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9741 $rawlangs = explode(',', $rawlangs); // Convert to array.
9742 $langs = array();
9744 $order = 1.0;
9745 foreach ($rawlangs as $lang) {
9746 if (strpos($lang, ';') === false) {
9747 $langs[(string)$order] = $lang;
9748 $order = $order-0.01;
9749 } else {
9750 $parts = explode(';', $lang);
9751 $pos = strpos($parts[1], '=');
9752 $langs[substr($parts[1], $pos+1)] = $parts[0];
9755 krsort($langs, SORT_NUMERIC);
9757 // Look for such langs under standard locations.
9758 foreach ($langs as $lang) {
9759 // Clean it properly for include.
9760 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9761 if (get_string_manager()->translation_exists($lang, false)) {
9762 // Lang exists, set it in session.
9763 $SESSION->lang = $lang;
9764 // We have finished. Go out.
9765 break;
9768 return;
9772 * Check if $url matches anything in proxybypass list
9774 * Any errors just result in the proxy being used (least bad)
9776 * @param string $url url to check
9777 * @return boolean true if we should bypass the proxy
9779 function is_proxybypass( $url ) {
9780 global $CFG;
9782 // Sanity check.
9783 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9784 return false;
9787 // Get the host part out of the url.
9788 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9789 return false;
9792 // Get the possible bypass hosts into an array.
9793 $matches = explode( ',', $CFG->proxybypass );
9795 // Check for a match.
9796 // (IPs need to match the left hand side and hosts the right of the url,
9797 // but we can recklessly check both as there can't be a false +ve).
9798 foreach ($matches as $match) {
9799 $match = trim($match);
9801 // Try for IP match (Left side).
9802 $lhs = substr($host, 0, strlen($match));
9803 if (strcasecmp($match, $lhs)==0) {
9804 return true;
9807 // Try for host match (Right side).
9808 $rhs = substr($host, -strlen($match));
9809 if (strcasecmp($match, $rhs)==0) {
9810 return true;
9814 // Nothing matched.
9815 return false;
9819 * Check if the passed navigation is of the new style
9821 * @param mixed $navigation
9822 * @return bool true for yes false for no
9824 function is_newnav($navigation) {
9825 if (is_array($navigation) && !empty($navigation['newnav'])) {
9826 return true;
9827 } else {
9828 return false;
9833 * Checks whether the given variable name is defined as a variable within the given object.
9835 * This will NOT work with stdClass objects, which have no class variables.
9837 * @param string $var The variable name
9838 * @param object $object The object to check
9839 * @return boolean
9841 function in_object_vars($var, $object) {
9842 $classvars = get_class_vars(get_class($object));
9843 $classvars = array_keys($classvars);
9844 return in_array($var, $classvars);
9848 * Returns an array without repeated objects.
9849 * This function is similar to array_unique, but for arrays that have objects as values
9851 * @param array $array
9852 * @param bool $keepkeyassoc
9853 * @return array
9855 function object_array_unique($array, $keepkeyassoc = true) {
9856 $duplicatekeys = array();
9857 $tmp = array();
9859 foreach ($array as $key => $val) {
9860 // Convert objects to arrays, in_array() does not support objects.
9861 if (is_object($val)) {
9862 $val = (array)$val;
9865 if (!in_array($val, $tmp)) {
9866 $tmp[] = $val;
9867 } else {
9868 $duplicatekeys[] = $key;
9872 foreach ($duplicatekeys as $key) {
9873 unset($array[$key]);
9876 return $keepkeyassoc ? $array : array_values($array);
9880 * Is a userid the primary administrator?
9882 * @param int $userid int id of user to check
9883 * @return boolean
9885 function is_primary_admin($userid) {
9886 $primaryadmin = get_admin();
9888 if ($userid == $primaryadmin->id) {
9889 return true;
9890 } else {
9891 return false;
9896 * Returns the site identifier
9898 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9900 function get_site_identifier() {
9901 global $CFG;
9902 // Check to see if it is missing. If so, initialise it.
9903 if (empty($CFG->siteidentifier)) {
9904 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9906 // Return it.
9907 return $CFG->siteidentifier;
9911 * Check whether the given password has no more than the specified
9912 * number of consecutive identical characters.
9914 * @param string $password password to be checked against the password policy
9915 * @param integer $maxchars maximum number of consecutive identical characters
9916 * @return bool
9918 function check_consecutive_identical_characters($password, $maxchars) {
9920 if ($maxchars < 1) {
9921 return true; // Zero 0 is to disable this check.
9923 if (strlen($password) <= $maxchars) {
9924 return true; // Too short to fail this test.
9927 $previouschar = '';
9928 $consecutivecount = 1;
9929 foreach (str_split($password) as $char) {
9930 if ($char != $previouschar) {
9931 $consecutivecount = 1;
9932 } else {
9933 $consecutivecount++;
9934 if ($consecutivecount > $maxchars) {
9935 return false; // Check failed already.
9939 $previouschar = $char;
9942 return true;
9946 * Helper function to do partial function binding.
9947 * so we can use it for preg_replace_callback, for example
9948 * this works with php functions, user functions, static methods and class methods
9949 * it returns you a callback that you can pass on like so:
9951 * $callback = partial('somefunction', $arg1, $arg2);
9952 * or
9953 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9954 * or even
9955 * $obj = new someclass();
9956 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9958 * and then the arguments that are passed through at calltime are appended to the argument list.
9960 * @param mixed $function a php callback
9961 * @param mixed $arg1,... $argv arguments to partially bind with
9962 * @return array Array callback
9964 function partial() {
9965 if (!class_exists('partial')) {
9967 * Used to manage function binding.
9968 * @copyright 2009 Penny Leach
9969 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9971 class partial{
9972 /** @var array */
9973 public $values = array();
9974 /** @var string The function to call as a callback. */
9975 public $func;
9977 * Constructor
9978 * @param string $func
9979 * @param array $args
9981 public function __construct($func, $args) {
9982 $this->values = $args;
9983 $this->func = $func;
9986 * Calls the callback function.
9987 * @return mixed
9989 public function method() {
9990 $args = func_get_args();
9991 return call_user_func_array($this->func, array_merge($this->values, $args));
9995 $args = func_get_args();
9996 $func = array_shift($args);
9997 $p = new partial($func, $args);
9998 return array($p, 'method');
10002 * helper function to load up and initialise the mnet environment
10003 * this must be called before you use mnet functions.
10005 * @return mnet_environment the equivalent of old $MNET global
10007 function get_mnet_environment() {
10008 global $CFG;
10009 require_once($CFG->dirroot . '/mnet/lib.php');
10010 static $instance = null;
10011 if (empty($instance)) {
10012 $instance = new mnet_environment();
10013 $instance->init();
10015 return $instance;
10019 * during xmlrpc server code execution, any code wishing to access
10020 * information about the remote peer must use this to get it.
10022 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
10024 function get_mnet_remote_client() {
10025 if (!defined('MNET_SERVER')) {
10026 debugging(get_string('notinxmlrpcserver', 'mnet'));
10027 return false;
10029 global $MNET_REMOTE_CLIENT;
10030 if (isset($MNET_REMOTE_CLIENT)) {
10031 return $MNET_REMOTE_CLIENT;
10033 return false;
10037 * during the xmlrpc server code execution, this will be called
10038 * to setup the object returned by {@link get_mnet_remote_client}
10040 * @param mnet_remote_client $client the client to set up
10041 * @throws moodle_exception
10043 function set_mnet_remote_client($client) {
10044 if (!defined('MNET_SERVER')) {
10045 throw new moodle_exception('notinxmlrpcserver', 'mnet');
10047 global $MNET_REMOTE_CLIENT;
10048 $MNET_REMOTE_CLIENT = $client;
10052 * return the jump url for a given remote user
10053 * this is used for rewriting forum post links in emails, etc
10055 * @param stdclass $user the user to get the idp url for
10057 function mnet_get_idp_jump_url($user) {
10058 global $CFG;
10060 static $mnetjumps = array();
10061 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
10062 $idp = mnet_get_peer_host($user->mnethostid);
10063 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
10064 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
10066 return $mnetjumps[$user->mnethostid];
10070 * Gets the homepage to use for the current user
10072 * @return int One of HOMEPAGE_*
10074 function get_home_page() {
10075 global $CFG;
10077 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
10078 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
10079 return HOMEPAGE_MY;
10080 } else {
10081 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
10084 return HOMEPAGE_SITE;
10088 * Gets the name of a course to be displayed when showing a list of courses.
10089 * By default this is just $course->fullname but user can configure it. The
10090 * result of this function should be passed through print_string.
10091 * @param stdClass|core_course_list_element $course Moodle course object
10092 * @return string Display name of course (either fullname or short + fullname)
10094 function get_course_display_name_for_list($course) {
10095 global $CFG;
10096 if (!empty($CFG->courselistshortnames)) {
10097 if (!($course instanceof stdClass)) {
10098 $course = (object)convert_to_array($course);
10100 return get_string('courseextendednamedisplay', '', $course);
10101 } else {
10102 return $course->fullname;
10107 * Safe analogue of unserialize() that can only parse arrays
10109 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
10110 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
10111 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
10113 * @param string $expression
10114 * @return array|bool either parsed array or false if parsing was impossible.
10116 function unserialize_array($expression) {
10117 $subs = [];
10118 // Find nested arrays, parse them and store in $subs , substitute with special string.
10119 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
10120 $key = '--SUB' . count($subs) . '--';
10121 $subs[$key] = unserialize_array($matches[2]);
10122 if ($subs[$key] === false) {
10123 return false;
10125 $expression = str_replace($matches[2], $key . ';', $expression);
10128 // Check the expression is an array.
10129 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
10130 return false;
10132 // Get the size and elements of an array (key;value;key;value;....).
10133 $parts = explode(';', $matches1[2]);
10134 $size = intval($matches1[1]);
10135 if (count($parts) < $size * 2 + 1) {
10136 return false;
10138 // Analyze each part and make sure it is an integer or string or a substitute.
10139 $value = [];
10140 for ($i = 0; $i < $size * 2; $i++) {
10141 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
10142 $parts[$i] = (int)$matches2[1];
10143 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
10144 $parts[$i] = $matches3[2];
10145 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
10146 $parts[$i] = $subs[$parts[$i]];
10147 } else {
10148 return false;
10151 // Combine keys and values.
10152 for ($i = 0; $i < $size * 2; $i += 2) {
10153 $value[$parts[$i]] = $parts[$i+1];
10155 return $value;
10159 * The lang_string class
10161 * This special class is used to create an object representation of a string request.
10162 * It is special because processing doesn't occur until the object is first used.
10163 * The class was created especially to aid performance in areas where strings were
10164 * required to be generated but were not necessarily used.
10165 * As an example the admin tree when generated uses over 1500 strings, of which
10166 * normally only 1/3 are ever actually printed at any time.
10167 * The performance advantage is achieved by not actually processing strings that
10168 * arn't being used, as such reducing the processing required for the page.
10170 * How to use the lang_string class?
10171 * There are two methods of using the lang_string class, first through the
10172 * forth argument of the get_string function, and secondly directly.
10173 * The following are examples of both.
10174 * 1. Through get_string calls e.g.
10175 * $string = get_string($identifier, $component, $a, true);
10176 * $string = get_string('yes', 'moodle', null, true);
10177 * 2. Direct instantiation
10178 * $string = new lang_string($identifier, $component, $a, $lang);
10179 * $string = new lang_string('yes');
10181 * How do I use a lang_string object?
10182 * The lang_string object makes use of a magic __toString method so that you
10183 * are able to use the object exactly as you would use a string in most cases.
10184 * This means you are able to collect it into a variable and then directly
10185 * echo it, or concatenate it into another string, or similar.
10186 * The other thing you can do is manually get the string by calling the
10187 * lang_strings out method e.g.
10188 * $string = new lang_string('yes');
10189 * $string->out();
10190 * Also worth noting is that the out method can take one argument, $lang which
10191 * allows the developer to change the language on the fly.
10193 * When should I use a lang_string object?
10194 * The lang_string object is designed to be used in any situation where a
10195 * string may not be needed, but needs to be generated.
10196 * The admin tree is a good example of where lang_string objects should be
10197 * used.
10198 * A more practical example would be any class that requries strings that may
10199 * not be printed (after all classes get renderer by renderers and who knows
10200 * what they will do ;))
10202 * When should I not use a lang_string object?
10203 * Don't use lang_strings when you are going to use a string immediately.
10204 * There is no need as it will be processed immediately and there will be no
10205 * advantage, and in fact perhaps a negative hit as a class has to be
10206 * instantiated for a lang_string object, however get_string won't require
10207 * that.
10209 * Limitations:
10210 * 1. You cannot use a lang_string object as an array offset. Doing so will
10211 * result in PHP throwing an error. (You can use it as an object property!)
10213 * @package core
10214 * @category string
10215 * @copyright 2011 Sam Hemelryk
10216 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10218 class lang_string {
10220 /** @var string The strings identifier */
10221 protected $identifier;
10222 /** @var string The strings component. Default '' */
10223 protected $component = '';
10224 /** @var array|stdClass Any arguments required for the string. Default null */
10225 protected $a = null;
10226 /** @var string The language to use when processing the string. Default null */
10227 protected $lang = null;
10229 /** @var string The processed string (once processed) */
10230 protected $string = null;
10233 * A special boolean. If set to true then the object has been woken up and
10234 * cannot be regenerated. If this is set then $this->string MUST be used.
10235 * @var bool
10237 protected $forcedstring = false;
10240 * Constructs a lang_string object
10242 * This function should do as little processing as possible to ensure the best
10243 * performance for strings that won't be used.
10245 * @param string $identifier The strings identifier
10246 * @param string $component The strings component
10247 * @param stdClass|array $a Any arguments the string requires
10248 * @param string $lang The language to use when processing the string.
10249 * @throws coding_exception
10251 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10252 if (empty($component)) {
10253 $component = 'moodle';
10256 $this->identifier = $identifier;
10257 $this->component = $component;
10258 $this->lang = $lang;
10260 // We MUST duplicate $a to ensure that it if it changes by reference those
10261 // changes are not carried across.
10262 // To do this we always ensure $a or its properties/values are strings
10263 // and that any properties/values that arn't convertable are forgotten.
10264 if (!empty($a)) {
10265 if (is_scalar($a)) {
10266 $this->a = $a;
10267 } else if ($a instanceof lang_string) {
10268 $this->a = $a->out();
10269 } else if (is_object($a) or is_array($a)) {
10270 $a = (array)$a;
10271 $this->a = array();
10272 foreach ($a as $key => $value) {
10273 // Make sure conversion errors don't get displayed (results in '').
10274 if (is_array($value)) {
10275 $this->a[$key] = '';
10276 } else if (is_object($value)) {
10277 if (method_exists($value, '__toString')) {
10278 $this->a[$key] = $value->__toString();
10279 } else {
10280 $this->a[$key] = '';
10282 } else {
10283 $this->a[$key] = (string)$value;
10289 if (debugging(false, DEBUG_DEVELOPER)) {
10290 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10291 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10293 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10294 throw new coding_exception('Invalid string compontent. Please check your string definition');
10296 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10297 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10303 * Processes the string.
10305 * This function actually processes the string, stores it in the string property
10306 * and then returns it.
10307 * You will notice that this function is VERY similar to the get_string method.
10308 * That is because it is pretty much doing the same thing.
10309 * However as this function is an upgrade it isn't as tolerant to backwards
10310 * compatibility.
10312 * @return string
10313 * @throws coding_exception
10315 protected function get_string() {
10316 global $CFG;
10318 // Check if we need to process the string.
10319 if ($this->string === null) {
10320 // Check the quality of the identifier.
10321 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10322 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);
10325 // Process the string.
10326 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10327 // Debugging feature lets you display string identifier and component.
10328 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10329 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10332 // Return the string.
10333 return $this->string;
10337 * Returns the string
10339 * @param string $lang The langauge to use when processing the string
10340 * @return string
10342 public function out($lang = null) {
10343 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10344 if ($this->forcedstring) {
10345 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10346 return $this->get_string();
10348 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10349 return $translatedstring->out();
10351 return $this->get_string();
10355 * Magic __toString method for printing a string
10357 * @return string
10359 public function __toString() {
10360 return $this->get_string();
10364 * Magic __set_state method used for var_export
10366 * @return string
10368 public function __set_state() {
10369 return $this->get_string();
10373 * Prepares the lang_string for sleep and stores only the forcedstring and
10374 * string properties... the string cannot be regenerated so we need to ensure
10375 * it is generated for this.
10377 * @return string
10379 public function __sleep() {
10380 $this->get_string();
10381 $this->forcedstring = true;
10382 return array('forcedstring', 'string', 'lang');
10386 * Returns the identifier.
10388 * @return string
10390 public function get_identifier() {
10391 return $this->identifier;
10395 * Returns the component.
10397 * @return string
10399 public function get_component() {
10400 return $this->component;
10405 * Get human readable name describing the given callable.
10407 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10408 * It does not check if the callable actually exists.
10410 * @param callable|string|array $callable
10411 * @return string|bool Human readable name of callable, or false if not a valid callable.
10413 function get_callable_name($callable) {
10415 if (!is_callable($callable, true, $name)) {
10416 return false;
10418 } else {
10419 return $name;
10424 * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10425 * Never put your faith on this function and rely on its accuracy as there might be false positives.
10426 * It just performs some simple checks, and mainly is used for places where we want to hide some options
10427 * such as site registration when $CFG->wwwroot is not publicly accessible.
10428 * Good thing is there is no false negative.
10430 * @return bool
10432 function site_is_public() {
10433 global $CFG;
10435 $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
10437 if ($host === 'localhost' || preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10438 $ispublic = false;
10439 } else if (\core\ip_utils::is_ip_address($host) && !ip_is_public($host)) {
10440 $ispublic = false;
10441 } else {
10442 $ispublic = true;
10445 return $ispublic;