MDL-66197 core: correct get parent language
[moodle.git] / lib / moodlelib.php
blob9f1430d26aaf14028940324164f5ff9484b95764
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 * Hub directory url (should be moodle.org)
492 define('HUB_HUBDIRECTORYURL', "https://hubdirectory.moodle.org");
496 * Moodle.net url (should be moodle.net)
498 define('HUB_MOODLEORGHUBURL', "https://moodle.net");
499 define('HUB_OLDMOODLEORGHUBURL', "http://hub.moodle.org");
502 * Moodle mobile app service name
504 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
507 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
509 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
512 * Course display settings: display all sections on one page.
514 define('COURSE_DISPLAY_SINGLEPAGE', 0);
516 * Course display settings: split pages into a page per section.
518 define('COURSE_DISPLAY_MULTIPAGE', 1);
521 * Authentication constant: String used in password field when password is not stored.
523 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
526 * Email from header to never include via information.
528 define('EMAIL_VIA_NEVER', 0);
531 * Email from header to always include via information.
533 define('EMAIL_VIA_ALWAYS', 1);
536 * Email from header to only include via information if the address is no-reply.
538 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
540 // PARAMETER HANDLING.
543 * Returns a particular value for the named variable, taken from
544 * POST or GET. If the parameter doesn't exist then an error is
545 * thrown because we require this variable.
547 * This function should be used to initialise all required values
548 * in a script that are based on parameters. Usually it will be
549 * used like this:
550 * $id = required_param('id', PARAM_INT);
552 * Please note the $type parameter is now required and the value can not be array.
554 * @param string $parname the name of the page parameter we want
555 * @param string $type expected type of parameter
556 * @return mixed
557 * @throws coding_exception
559 function required_param($parname, $type) {
560 if (func_num_args() != 2 or empty($parname) or empty($type)) {
561 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
563 // POST has precedence.
564 if (isset($_POST[$parname])) {
565 $param = $_POST[$parname];
566 } else if (isset($_GET[$parname])) {
567 $param = $_GET[$parname];
568 } else {
569 print_error('missingparam', '', '', $parname);
572 if (is_array($param)) {
573 debugging('Invalid array parameter detected in required_param(): '.$parname);
574 // TODO: switch to fatal error in Moodle 2.3.
575 return required_param_array($parname, $type);
578 return clean_param($param, $type);
582 * Returns a particular array value for the named variable, taken from
583 * POST or GET. If the parameter doesn't exist then an error is
584 * thrown because we require this variable.
586 * This function should be used to initialise all required values
587 * in a script that are based on parameters. Usually it will be
588 * used like this:
589 * $ids = required_param_array('ids', PARAM_INT);
591 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
593 * @param string $parname the name of the page parameter we want
594 * @param string $type expected type of parameter
595 * @return array
596 * @throws coding_exception
598 function required_param_array($parname, $type) {
599 if (func_num_args() != 2 or empty($parname) or empty($type)) {
600 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
602 // POST has precedence.
603 if (isset($_POST[$parname])) {
604 $param = $_POST[$parname];
605 } else if (isset($_GET[$parname])) {
606 $param = $_GET[$parname];
607 } else {
608 print_error('missingparam', '', '', $parname);
610 if (!is_array($param)) {
611 print_error('missingparam', '', '', $parname);
614 $result = array();
615 foreach ($param as $key => $value) {
616 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
617 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
618 continue;
620 $result[$key] = clean_param($value, $type);
623 return $result;
627 * Returns a particular value for the named variable, taken from
628 * POST or GET, otherwise returning a given default.
630 * This function should be used to initialise all optional values
631 * in a script that are based on parameters. Usually it will be
632 * used like this:
633 * $name = optional_param('name', 'Fred', PARAM_TEXT);
635 * Please note the $type parameter is now required and the value can not be array.
637 * @param string $parname the name of the page parameter we want
638 * @param mixed $default the default value to return if nothing is found
639 * @param string $type expected type of parameter
640 * @return mixed
641 * @throws coding_exception
643 function optional_param($parname, $default, $type) {
644 if (func_num_args() != 3 or empty($parname) or empty($type)) {
645 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
648 // POST has precedence.
649 if (isset($_POST[$parname])) {
650 $param = $_POST[$parname];
651 } else if (isset($_GET[$parname])) {
652 $param = $_GET[$parname];
653 } else {
654 return $default;
657 if (is_array($param)) {
658 debugging('Invalid array parameter detected in required_param(): '.$parname);
659 // TODO: switch to $default in Moodle 2.3.
660 return optional_param_array($parname, $default, $type);
663 return clean_param($param, $type);
667 * Returns a particular array value for the named variable, taken from
668 * POST or GET, otherwise returning a given default.
670 * This function should be used to initialise all optional values
671 * in a script that are based on parameters. Usually it will be
672 * used like this:
673 * $ids = optional_param('id', array(), PARAM_INT);
675 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
677 * @param string $parname the name of the page parameter we want
678 * @param mixed $default the default value to return if nothing is found
679 * @param string $type expected type of parameter
680 * @return array
681 * @throws coding_exception
683 function optional_param_array($parname, $default, $type) {
684 if (func_num_args() != 3 or empty($parname) or empty($type)) {
685 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
688 // POST has precedence.
689 if (isset($_POST[$parname])) {
690 $param = $_POST[$parname];
691 } else if (isset($_GET[$parname])) {
692 $param = $_GET[$parname];
693 } else {
694 return $default;
696 if (!is_array($param)) {
697 debugging('optional_param_array() expects array parameters only: '.$parname);
698 return $default;
701 $result = array();
702 foreach ($param as $key => $value) {
703 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
704 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
705 continue;
707 $result[$key] = clean_param($value, $type);
710 return $result;
714 * Strict validation of parameter values, the values are only converted
715 * to requested PHP type. Internally it is using clean_param, the values
716 * before and after cleaning must be equal - otherwise
717 * an invalid_parameter_exception is thrown.
718 * Objects and classes are not accepted.
720 * @param mixed $param
721 * @param string $type PARAM_ constant
722 * @param bool $allownull are nulls valid value?
723 * @param string $debuginfo optional debug information
724 * @return mixed the $param value converted to PHP type
725 * @throws invalid_parameter_exception if $param is not of given type
727 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
728 if (is_null($param)) {
729 if ($allownull == NULL_ALLOWED) {
730 return null;
731 } else {
732 throw new invalid_parameter_exception($debuginfo);
735 if (is_array($param) or is_object($param)) {
736 throw new invalid_parameter_exception($debuginfo);
739 $cleaned = clean_param($param, $type);
741 if ($type == PARAM_FLOAT) {
742 // Do not detect precision loss here.
743 if (is_float($param) or is_int($param)) {
744 // These always fit.
745 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
746 throw new invalid_parameter_exception($debuginfo);
748 } else if ((string)$param !== (string)$cleaned) {
749 // Conversion to string is usually lossless.
750 throw new invalid_parameter_exception($debuginfo);
753 return $cleaned;
757 * Makes sure array contains only the allowed types, this function does not validate array key names!
759 * <code>
760 * $options = clean_param($options, PARAM_INT);
761 * </code>
763 * @param array $param the variable array we are cleaning
764 * @param string $type expected format of param after cleaning.
765 * @param bool $recursive clean recursive arrays
766 * @return array
767 * @throws coding_exception
769 function clean_param_array(array $param = null, $type, $recursive = false) {
770 // Convert null to empty array.
771 $param = (array)$param;
772 foreach ($param as $key => $value) {
773 if (is_array($value)) {
774 if ($recursive) {
775 $param[$key] = clean_param_array($value, $type, true);
776 } else {
777 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
779 } else {
780 $param[$key] = clean_param($value, $type);
783 return $param;
787 * Used by {@link optional_param()} and {@link required_param()} to
788 * clean the variables and/or cast to specific types, based on
789 * an options field.
790 * <code>
791 * $course->format = clean_param($course->format, PARAM_ALPHA);
792 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
793 * </code>
795 * @param mixed $param the variable we are cleaning
796 * @param string $type expected format of param after cleaning.
797 * @return mixed
798 * @throws coding_exception
800 function clean_param($param, $type) {
801 global $CFG;
803 if (is_array($param)) {
804 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
805 } else if (is_object($param)) {
806 if (method_exists($param, '__toString')) {
807 $param = $param->__toString();
808 } else {
809 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
813 switch ($type) {
814 case PARAM_RAW:
815 // No cleaning at all.
816 $param = fix_utf8($param);
817 return $param;
819 case PARAM_RAW_TRIMMED:
820 // No cleaning, but strip leading and trailing whitespace.
821 $param = fix_utf8($param);
822 return trim($param);
824 case PARAM_CLEAN:
825 // General HTML cleaning, try to use more specific type if possible this is deprecated!
826 // Please use more specific type instead.
827 if (is_numeric($param)) {
828 return $param;
830 $param = fix_utf8($param);
831 // Sweep for scripts, etc.
832 return clean_text($param);
834 case PARAM_CLEANHTML:
835 // Clean html fragment.
836 $param = fix_utf8($param);
837 // Sweep for scripts, etc.
838 $param = clean_text($param, FORMAT_HTML);
839 return trim($param);
841 case PARAM_INT:
842 // Convert to integer.
843 return (int)$param;
845 case PARAM_FLOAT:
846 // Convert to float.
847 return (float)$param;
849 case PARAM_LOCALISEDFLOAT:
850 // Convert to float.
851 return unformat_float($param, true);
853 case PARAM_ALPHA:
854 // Remove everything not `a-z`.
855 return preg_replace('/[^a-zA-Z]/i', '', $param);
857 case PARAM_ALPHAEXT:
858 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
859 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
861 case PARAM_ALPHANUM:
862 // Remove everything not `a-zA-Z0-9`.
863 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
865 case PARAM_ALPHANUMEXT:
866 // Remove everything not `a-zA-Z0-9_-`.
867 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
869 case PARAM_SEQUENCE:
870 // Remove everything not `0-9,`.
871 return preg_replace('/[^0-9,]/i', '', $param);
873 case PARAM_BOOL:
874 // Convert to 1 or 0.
875 $tempstr = strtolower($param);
876 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
877 $param = 1;
878 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
879 $param = 0;
880 } else {
881 $param = empty($param) ? 0 : 1;
883 return $param;
885 case PARAM_NOTAGS:
886 // Strip all tags.
887 $param = fix_utf8($param);
888 return strip_tags($param);
890 case PARAM_TEXT:
891 // Leave only tags needed for multilang.
892 $param = fix_utf8($param);
893 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
894 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
895 do {
896 if (strpos($param, '</lang>') !== false) {
897 // Old and future mutilang syntax.
898 $param = strip_tags($param, '<lang>');
899 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
900 break;
902 $open = false;
903 foreach ($matches[0] as $match) {
904 if ($match === '</lang>') {
905 if ($open) {
906 $open = false;
907 continue;
908 } else {
909 break 2;
912 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
913 break 2;
914 } else {
915 $open = true;
918 if ($open) {
919 break;
921 return $param;
923 } else if (strpos($param, '</span>') !== false) {
924 // Current problematic multilang syntax.
925 $param = strip_tags($param, '<span>');
926 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
927 break;
929 $open = false;
930 foreach ($matches[0] as $match) {
931 if ($match === '</span>') {
932 if ($open) {
933 $open = false;
934 continue;
935 } else {
936 break 2;
939 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
940 break 2;
941 } else {
942 $open = true;
945 if ($open) {
946 break;
948 return $param;
950 } while (false);
951 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
952 return strip_tags($param);
954 case PARAM_COMPONENT:
955 // We do not want any guessing here, either the name is correct or not
956 // please note only normalised component names are accepted.
957 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
958 return '';
960 if (strpos($param, '__') !== false) {
961 return '';
963 if (strpos($param, 'mod_') === 0) {
964 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
965 if (substr_count($param, '_') != 1) {
966 return '';
969 return $param;
971 case PARAM_PLUGIN:
972 case PARAM_AREA:
973 // We do not want any guessing here, either the name is correct or not.
974 if (!is_valid_plugin_name($param)) {
975 return '';
977 return $param;
979 case PARAM_SAFEDIR:
980 // Remove everything not a-zA-Z0-9_- .
981 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
983 case PARAM_SAFEPATH:
984 // Remove everything not a-zA-Z0-9/_- .
985 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
987 case PARAM_FILE:
988 // Strip all suspicious characters from filename.
989 $param = fix_utf8($param);
990 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
991 if ($param === '.' || $param === '..') {
992 $param = '';
994 return $param;
996 case PARAM_PATH:
997 // Strip all suspicious characters from file path.
998 $param = fix_utf8($param);
999 $param = str_replace('\\', '/', $param);
1001 // Explode the path and clean each element using the PARAM_FILE rules.
1002 $breadcrumb = explode('/', $param);
1003 foreach ($breadcrumb as $key => $crumb) {
1004 if ($crumb === '.' && $key === 0) {
1005 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1006 } else {
1007 $crumb = clean_param($crumb, PARAM_FILE);
1009 $breadcrumb[$key] = $crumb;
1011 $param = implode('/', $breadcrumb);
1013 // Remove multiple current path (./././) and multiple slashes (///).
1014 $param = preg_replace('~//+~', '/', $param);
1015 $param = preg_replace('~/(\./)+~', '/', $param);
1016 return $param;
1018 case PARAM_HOST:
1019 // Allow FQDN or IPv4 dotted quad.
1020 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1021 // Match ipv4 dotted quad.
1022 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1023 // Confirm values are ok.
1024 if ( $match[0] > 255
1025 || $match[1] > 255
1026 || $match[3] > 255
1027 || $match[4] > 255 ) {
1028 // Hmmm, what kind of dotted quad is this?
1029 $param = '';
1031 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1032 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1033 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1035 // All is ok - $param is respected.
1036 } else {
1037 // All is not ok...
1038 $param='';
1040 return $param;
1042 case PARAM_URL:
1043 // Allow safe urls.
1044 $param = fix_utf8($param);
1045 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1046 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1047 // All is ok, param is respected.
1048 } else {
1049 // Not really ok.
1050 $param ='';
1052 return $param;
1054 case PARAM_LOCALURL:
1055 // Allow http absolute, root relative and relative URLs within wwwroot.
1056 $param = clean_param($param, PARAM_URL);
1057 if (!empty($param)) {
1059 if ($param === $CFG->wwwroot) {
1060 // Exact match;
1061 } else if (preg_match(':^/:', $param)) {
1062 // Root-relative, ok!
1063 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1064 // Absolute, and matches our wwwroot.
1065 } else {
1066 // Relative - let's make sure there are no tricks.
1067 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1068 // Looks ok.
1069 } else {
1070 $param = '';
1074 return $param;
1076 case PARAM_PEM:
1077 $param = trim($param);
1078 // PEM formatted strings may contain letters/numbers and the symbols:
1079 // forward slash: /
1080 // plus sign: +
1081 // equal sign: =
1082 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1083 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1084 list($wholething, $body) = $matches;
1085 unset($wholething, $matches);
1086 $b64 = clean_param($body, PARAM_BASE64);
1087 if (!empty($b64)) {
1088 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1089 } else {
1090 return '';
1093 return '';
1095 case PARAM_BASE64:
1096 if (!empty($param)) {
1097 // PEM formatted strings may contain letters/numbers and the symbols
1098 // forward slash: /
1099 // plus sign: +
1100 // equal sign: =.
1101 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1102 return '';
1104 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1105 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1106 // than (or equal to) 64 characters long.
1107 for ($i=0, $j=count($lines); $i < $j; $i++) {
1108 if ($i + 1 == $j) {
1109 if (64 < strlen($lines[$i])) {
1110 return '';
1112 continue;
1115 if (64 != strlen($lines[$i])) {
1116 return '';
1119 return implode("\n", $lines);
1120 } else {
1121 return '';
1124 case PARAM_TAG:
1125 $param = fix_utf8($param);
1126 // Please note it is not safe to use the tag name directly anywhere,
1127 // it must be processed with s(), urlencode() before embedding anywhere.
1128 // Remove some nasties.
1129 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1130 // Convert many whitespace chars into one.
1131 $param = preg_replace('/\s+/u', ' ', $param);
1132 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1133 return $param;
1135 case PARAM_TAGLIST:
1136 $param = fix_utf8($param);
1137 $tags = explode(',', $param);
1138 $result = array();
1139 foreach ($tags as $tag) {
1140 $res = clean_param($tag, PARAM_TAG);
1141 if ($res !== '') {
1142 $result[] = $res;
1145 if ($result) {
1146 return implode(',', $result);
1147 } else {
1148 return '';
1151 case PARAM_CAPABILITY:
1152 if (get_capability_info($param)) {
1153 return $param;
1154 } else {
1155 return '';
1158 case PARAM_PERMISSION:
1159 $param = (int)$param;
1160 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1161 return $param;
1162 } else {
1163 return CAP_INHERIT;
1166 case PARAM_AUTH:
1167 $param = clean_param($param, PARAM_PLUGIN);
1168 if (empty($param)) {
1169 return '';
1170 } else if (exists_auth_plugin($param)) {
1171 return $param;
1172 } else {
1173 return '';
1176 case PARAM_LANG:
1177 $param = clean_param($param, PARAM_SAFEDIR);
1178 if (get_string_manager()->translation_exists($param)) {
1179 return $param;
1180 } else {
1181 // Specified language is not installed or param malformed.
1182 return '';
1185 case PARAM_THEME:
1186 $param = clean_param($param, PARAM_PLUGIN);
1187 if (empty($param)) {
1188 return '';
1189 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1190 return $param;
1191 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1192 return $param;
1193 } else {
1194 // Specified theme is not installed.
1195 return '';
1198 case PARAM_USERNAME:
1199 $param = fix_utf8($param);
1200 $param = trim($param);
1201 // Convert uppercase to lowercase MDL-16919.
1202 $param = core_text::strtolower($param);
1203 if (empty($CFG->extendedusernamechars)) {
1204 $param = str_replace(" " , "", $param);
1205 // Regular expression, eliminate all chars EXCEPT:
1206 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1207 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1209 return $param;
1211 case PARAM_EMAIL:
1212 $param = fix_utf8($param);
1213 if (validate_email($param)) {
1214 return $param;
1215 } else {
1216 return '';
1219 case PARAM_STRINGID:
1220 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1221 return $param;
1222 } else {
1223 return '';
1226 case PARAM_TIMEZONE:
1227 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1228 $param = fix_utf8($param);
1229 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1230 if (preg_match($timezonepattern, $param)) {
1231 return $param;
1232 } else {
1233 return '';
1236 default:
1237 // Doh! throw error, switched parameters in optional_param or another serious problem.
1238 print_error("unknownparamtype", '', '', $type);
1243 * Whether the PARAM_* type is compatible in RTL.
1245 * Being compatible with RTL means that the data they contain can flow
1246 * from right-to-left or left-to-right without compromising the user experience.
1248 * Take URLs for example, they are not RTL compatible as they should always
1249 * flow from the left to the right. This also applies to numbers, email addresses,
1250 * configuration snippets, base64 strings, etc...
1252 * This function tries to best guess which parameters can contain localised strings.
1254 * @param string $paramtype Constant PARAM_*.
1255 * @return bool
1257 function is_rtl_compatible($paramtype) {
1258 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1262 * Makes sure the data is using valid utf8, invalid characters are discarded.
1264 * Note: this function is not intended for full objects with methods and private properties.
1266 * @param mixed $value
1267 * @return mixed with proper utf-8 encoding
1269 function fix_utf8($value) {
1270 if (is_null($value) or $value === '') {
1271 return $value;
1273 } else if (is_string($value)) {
1274 if ((string)(int)$value === $value) {
1275 // Shortcut.
1276 return $value;
1278 // No null bytes expected in our data, so let's remove it.
1279 $value = str_replace("\0", '', $value);
1281 // Note: this duplicates min_fix_utf8() intentionally.
1282 static $buggyiconv = null;
1283 if ($buggyiconv === null) {
1284 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1287 if ($buggyiconv) {
1288 if (function_exists('mb_convert_encoding')) {
1289 $subst = mb_substitute_character();
1290 mb_substitute_character('');
1291 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1292 mb_substitute_character($subst);
1294 } else {
1295 // Warn admins on admin/index.php page.
1296 $result = $value;
1299 } else {
1300 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1303 return $result;
1305 } else if (is_array($value)) {
1306 foreach ($value as $k => $v) {
1307 $value[$k] = fix_utf8($v);
1309 return $value;
1311 } else if (is_object($value)) {
1312 // Do not modify original.
1313 $value = clone($value);
1314 foreach ($value as $k => $v) {
1315 $value->$k = fix_utf8($v);
1317 return $value;
1319 } else {
1320 // This is some other type, no utf-8 here.
1321 return $value;
1326 * Return true if given value is integer or string with integer value
1328 * @param mixed $value String or Int
1329 * @return bool true if number, false if not
1331 function is_number($value) {
1332 if (is_int($value)) {
1333 return true;
1334 } else if (is_string($value)) {
1335 return ((string)(int)$value) === $value;
1336 } else {
1337 return false;
1342 * Returns host part from url.
1344 * @param string $url full url
1345 * @return string host, null if not found
1347 function get_host_from_url($url) {
1348 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1349 if ($matches) {
1350 return $matches[1];
1352 return null;
1356 * Tests whether anything was returned by text editor
1358 * This function is useful for testing whether something you got back from
1359 * the HTML editor actually contains anything. Sometimes the HTML editor
1360 * appear to be empty, but actually you get back a <br> tag or something.
1362 * @param string $string a string containing HTML.
1363 * @return boolean does the string contain any actual content - that is text,
1364 * images, objects, etc.
1366 function html_is_blank($string) {
1367 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1371 * Set a key in global configuration
1373 * Set a key/value pair in both this session's {@link $CFG} global variable
1374 * and in the 'config' database table for future sessions.
1376 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1377 * In that case it doesn't affect $CFG.
1379 * A NULL value will delete the entry.
1381 * NOTE: this function is called from lib/db/upgrade.php
1383 * @param string $name the key to set
1384 * @param string $value the value to set (without magic quotes)
1385 * @param string $plugin (optional) the plugin scope, default null
1386 * @return bool true or exception
1388 function set_config($name, $value, $plugin=null) {
1389 global $CFG, $DB;
1391 if (empty($plugin)) {
1392 if (!array_key_exists($name, $CFG->config_php_settings)) {
1393 // So it's defined for this invocation at least.
1394 if (is_null($value)) {
1395 unset($CFG->$name);
1396 } else {
1397 // Settings from db are always strings.
1398 $CFG->$name = (string)$value;
1402 if ($DB->get_field('config', 'name', array('name' => $name))) {
1403 if ($value === null) {
1404 $DB->delete_records('config', array('name' => $name));
1405 } else {
1406 $DB->set_field('config', 'value', $value, array('name' => $name));
1408 } else {
1409 if ($value !== null) {
1410 $config = new stdClass();
1411 $config->name = $name;
1412 $config->value = $value;
1413 $DB->insert_record('config', $config, false);
1416 if ($name === 'siteidentifier') {
1417 cache_helper::update_site_identifier($value);
1419 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1420 } else {
1421 // Plugin scope.
1422 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1423 if ($value===null) {
1424 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1425 } else {
1426 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1428 } else {
1429 if ($value !== null) {
1430 $config = new stdClass();
1431 $config->plugin = $plugin;
1432 $config->name = $name;
1433 $config->value = $value;
1434 $DB->insert_record('config_plugins', $config, false);
1437 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1440 return true;
1444 * Get configuration values from the global config table
1445 * or the config_plugins table.
1447 * If called with one parameter, it will load all the config
1448 * variables for one plugin, and return them as an object.
1450 * If called with 2 parameters it will return a string single
1451 * value or false if the value is not found.
1453 * NOTE: this function is called from lib/db/upgrade.php
1455 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1456 * that we need only fetch it once per request.
1457 * @param string $plugin full component name
1458 * @param string $name default null
1459 * @return mixed hash-like object or single value, return false no config found
1460 * @throws dml_exception
1462 function get_config($plugin, $name = null) {
1463 global $CFG, $DB;
1465 static $siteidentifier = null;
1467 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1468 $forced =& $CFG->config_php_settings;
1469 $iscore = true;
1470 $plugin = 'core';
1471 } else {
1472 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1473 $forced =& $CFG->forced_plugin_settings[$plugin];
1474 } else {
1475 $forced = array();
1477 $iscore = false;
1480 if ($siteidentifier === null) {
1481 try {
1482 // This may fail during installation.
1483 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1484 // install the database.
1485 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1486 } catch (dml_exception $ex) {
1487 // Set siteidentifier to false. We don't want to trip this continually.
1488 $siteidentifier = false;
1489 throw $ex;
1493 if (!empty($name)) {
1494 if (array_key_exists($name, $forced)) {
1495 return (string)$forced[$name];
1496 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1497 return $siteidentifier;
1501 $cache = cache::make('core', 'config');
1502 $result = $cache->get($plugin);
1503 if ($result === false) {
1504 // The user is after a recordset.
1505 if (!$iscore) {
1506 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1507 } else {
1508 // This part is not really used any more, but anyway...
1509 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1511 $cache->set($plugin, $result);
1514 if (!empty($name)) {
1515 if (array_key_exists($name, $result)) {
1516 return $result[$name];
1518 return false;
1521 if ($plugin === 'core') {
1522 $result['siteidentifier'] = $siteidentifier;
1525 foreach ($forced as $key => $value) {
1526 if (is_null($value) or is_array($value) or is_object($value)) {
1527 // We do not want any extra mess here, just real settings that could be saved in db.
1528 unset($result[$key]);
1529 } else {
1530 // Convert to string as if it went through the DB.
1531 $result[$key] = (string)$value;
1535 return (object)$result;
1539 * Removes a key from global configuration.
1541 * NOTE: this function is called from lib/db/upgrade.php
1543 * @param string $name the key to set
1544 * @param string $plugin (optional) the plugin scope
1545 * @return boolean whether the operation succeeded.
1547 function unset_config($name, $plugin=null) {
1548 global $CFG, $DB;
1550 if (empty($plugin)) {
1551 unset($CFG->$name);
1552 $DB->delete_records('config', array('name' => $name));
1553 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1554 } else {
1555 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1556 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1559 return true;
1563 * Remove all the config variables for a given plugin.
1565 * NOTE: this function is called from lib/db/upgrade.php
1567 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1568 * @return boolean whether the operation succeeded.
1570 function unset_all_config_for_plugin($plugin) {
1571 global $DB;
1572 // Delete from the obvious config_plugins first.
1573 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1574 // Next delete any suspect settings from config.
1575 $like = $DB->sql_like('name', '?', true, true, false, '|');
1576 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1577 $DB->delete_records_select('config', $like, $params);
1578 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1579 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1581 return true;
1585 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1587 * All users are verified if they still have the necessary capability.
1589 * @param string $value the value of the config setting.
1590 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1591 * @param bool $includeadmins include administrators.
1592 * @return array of user objects.
1594 function get_users_from_config($value, $capability, $includeadmins = true) {
1595 if (empty($value) or $value === '$@NONE@$') {
1596 return array();
1599 // We have to make sure that users still have the necessary capability,
1600 // it should be faster to fetch them all first and then test if they are present
1601 // instead of validating them one-by-one.
1602 $users = get_users_by_capability(context_system::instance(), $capability);
1603 if ($includeadmins) {
1604 $admins = get_admins();
1605 foreach ($admins as $admin) {
1606 $users[$admin->id] = $admin;
1610 if ($value === '$@ALL@$') {
1611 return $users;
1614 $result = array(); // Result in correct order.
1615 $allowed = explode(',', $value);
1616 foreach ($allowed as $uid) {
1617 if (isset($users[$uid])) {
1618 $user = $users[$uid];
1619 $result[$user->id] = $user;
1623 return $result;
1628 * Invalidates browser caches and cached data in temp.
1630 * @return void
1632 function purge_all_caches() {
1633 purge_caches();
1637 * Selectively invalidate different types of cache.
1639 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1640 * areas alone or in combination.
1642 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1643 * 'muc' Purge MUC caches?
1644 * 'theme' Purge theme cache?
1645 * 'lang' Purge language string cache?
1646 * 'js' Purge javascript cache?
1647 * 'filter' Purge text filter cache?
1648 * 'other' Purge all other caches?
1650 function purge_caches($options = []) {
1651 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1652 if (empty(array_filter($options))) {
1653 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1654 } else {
1655 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1657 if ($options['muc']) {
1658 cache_helper::purge_all();
1660 if ($options['theme']) {
1661 theme_reset_all_caches();
1663 if ($options['lang']) {
1664 get_string_manager()->reset_caches();
1666 if ($options['js']) {
1667 js_reset_all_caches();
1669 if ($options['template']) {
1670 template_reset_all_caches();
1672 if ($options['filter']) {
1673 reset_text_filters_cache();
1675 if ($options['other']) {
1676 purge_other_caches();
1681 * Purge all non-MUC caches not otherwise purged in purge_caches.
1683 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1684 * {@link phpunit_util::reset_dataroot()}
1686 function purge_other_caches() {
1687 global $DB, $CFG;
1688 core_text::reset_caches();
1689 if (class_exists('core_plugin_manager')) {
1690 core_plugin_manager::reset_caches();
1693 // Bump up cacherev field for all courses.
1694 try {
1695 increment_revision_number('course', 'cacherev', '');
1696 } catch (moodle_exception $e) {
1697 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1700 $DB->reset_caches();
1702 // Purge all other caches: rss, simplepie, etc.
1703 clearstatcache();
1704 remove_dir($CFG->cachedir.'', true);
1706 // Make sure cache dir is writable, throws exception if not.
1707 make_cache_directory('');
1709 // This is the only place where we purge local caches, we are only adding files there.
1710 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1711 remove_dir($CFG->localcachedir, true);
1712 set_config('localcachedirpurged', time());
1713 make_localcache_directory('', true);
1714 \core\task\manager::clear_static_caches();
1718 * Get volatile flags
1720 * @param string $type
1721 * @param int $changedsince default null
1722 * @return array records array
1724 function get_cache_flags($type, $changedsince = null) {
1725 global $DB;
1727 $params = array('type' => $type, 'expiry' => time());
1728 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1729 if ($changedsince !== null) {
1730 $params['changedsince'] = $changedsince;
1731 $sqlwhere .= " AND timemodified > :changedsince";
1733 $cf = array();
1734 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1735 foreach ($flags as $flag) {
1736 $cf[$flag->name] = $flag->value;
1739 return $cf;
1743 * Get volatile flags
1745 * @param string $type
1746 * @param string $name
1747 * @param int $changedsince default null
1748 * @return string|false The cache flag value or false
1750 function get_cache_flag($type, $name, $changedsince=null) {
1751 global $DB;
1753 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1755 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1756 if ($changedsince !== null) {
1757 $params['changedsince'] = $changedsince;
1758 $sqlwhere .= " AND timemodified > :changedsince";
1761 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1765 * Set a volatile flag
1767 * @param string $type the "type" namespace for the key
1768 * @param string $name the key to set
1769 * @param string $value the value to set (without magic quotes) - null will remove the flag
1770 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1771 * @return bool Always returns true
1773 function set_cache_flag($type, $name, $value, $expiry = null) {
1774 global $DB;
1776 $timemodified = time();
1777 if ($expiry === null || $expiry < $timemodified) {
1778 $expiry = $timemodified + 24 * 60 * 60;
1779 } else {
1780 $expiry = (int)$expiry;
1783 if ($value === null) {
1784 unset_cache_flag($type, $name);
1785 return true;
1788 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1789 // This is a potential problem in DEBUG_DEVELOPER.
1790 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1791 return true; // No need to update.
1793 $f->value = $value;
1794 $f->expiry = $expiry;
1795 $f->timemodified = $timemodified;
1796 $DB->update_record('cache_flags', $f);
1797 } else {
1798 $f = new stdClass();
1799 $f->flagtype = $type;
1800 $f->name = $name;
1801 $f->value = $value;
1802 $f->expiry = $expiry;
1803 $f->timemodified = $timemodified;
1804 $DB->insert_record('cache_flags', $f);
1806 return true;
1810 * Removes a single volatile flag
1812 * @param string $type the "type" namespace for the key
1813 * @param string $name the key to set
1814 * @return bool
1816 function unset_cache_flag($type, $name) {
1817 global $DB;
1818 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1819 return true;
1823 * Garbage-collect volatile flags
1825 * @return bool Always returns true
1827 function gc_cache_flags() {
1828 global $DB;
1829 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1830 return true;
1833 // USER PREFERENCE API.
1836 * Refresh user preference cache. This is used most often for $USER
1837 * object that is stored in session, but it also helps with performance in cron script.
1839 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1841 * @package core
1842 * @category preference
1843 * @access public
1844 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1845 * @param int $cachelifetime Cache life time on the current page (in seconds)
1846 * @throws coding_exception
1847 * @return null
1849 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1850 global $DB;
1851 // Static cache, we need to check on each page load, not only every 2 minutes.
1852 static $loadedusers = array();
1854 if (!isset($user->id)) {
1855 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1858 if (empty($user->id) or isguestuser($user->id)) {
1859 // No permanent storage for not-logged-in users and guest.
1860 if (!isset($user->preference)) {
1861 $user->preference = array();
1863 return;
1866 $timenow = time();
1868 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1869 // Already loaded at least once on this page. Are we up to date?
1870 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1871 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1872 return;
1874 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1875 // No change since the lastcheck on this page.
1876 $user->preference['_lastloaded'] = $timenow;
1877 return;
1881 // OK, so we have to reload all preferences.
1882 $loadedusers[$user->id] = true;
1883 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1884 $user->preference['_lastloaded'] = $timenow;
1888 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1890 * NOTE: internal function, do not call from other code.
1892 * @package core
1893 * @access private
1894 * @param integer $userid the user whose prefs were changed.
1896 function mark_user_preferences_changed($userid) {
1897 global $CFG;
1899 if (empty($userid) or isguestuser($userid)) {
1900 // No cache flags for guest and not-logged-in users.
1901 return;
1904 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1908 * Sets a preference for the specified user.
1910 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1912 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1914 * @package core
1915 * @category preference
1916 * @access public
1917 * @param string $name The key to set as preference for the specified user
1918 * @param string $value The value to set for the $name key in the specified user's
1919 * record, null means delete current value.
1920 * @param stdClass|int|null $user A moodle user object or id, null means current user
1921 * @throws coding_exception
1922 * @return bool Always true or exception
1924 function set_user_preference($name, $value, $user = null) {
1925 global $USER, $DB;
1927 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1928 throw new coding_exception('Invalid preference name in set_user_preference() call');
1931 if (is_null($value)) {
1932 // Null means delete current.
1933 return unset_user_preference($name, $user);
1934 } else if (is_object($value)) {
1935 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1936 } else if (is_array($value)) {
1937 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1939 // Value column maximum length is 1333 characters.
1940 $value = (string)$value;
1941 if (core_text::strlen($value) > 1333) {
1942 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1945 if (is_null($user)) {
1946 $user = $USER;
1947 } else if (isset($user->id)) {
1948 // It is a valid object.
1949 } else if (is_numeric($user)) {
1950 $user = (object)array('id' => (int)$user);
1951 } else {
1952 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1955 check_user_preferences_loaded($user);
1957 if (empty($user->id) or isguestuser($user->id)) {
1958 // No permanent storage for not-logged-in users and guest.
1959 $user->preference[$name] = $value;
1960 return true;
1963 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1964 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1965 // Preference already set to this value.
1966 return true;
1968 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1970 } else {
1971 $preference = new stdClass();
1972 $preference->userid = $user->id;
1973 $preference->name = $name;
1974 $preference->value = $value;
1975 $DB->insert_record('user_preferences', $preference);
1978 // Update value in cache.
1979 $user->preference[$name] = $value;
1980 // Update the $USER in case where we've not a direct reference to $USER.
1981 if ($user !== $USER && $user->id == $USER->id) {
1982 $USER->preference[$name] = $value;
1985 // Set reload flag for other sessions.
1986 mark_user_preferences_changed($user->id);
1988 return true;
1992 * Sets a whole array of preferences for the current user
1994 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1996 * @package core
1997 * @category preference
1998 * @access public
1999 * @param array $prefarray An array of key/value pairs to be set
2000 * @param stdClass|int|null $user A moodle user object or id, null means current user
2001 * @return bool Always true or exception
2003 function set_user_preferences(array $prefarray, $user = null) {
2004 foreach ($prefarray as $name => $value) {
2005 set_user_preference($name, $value, $user);
2007 return true;
2011 * Unsets a preference completely by deleting it from the database
2013 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2015 * @package core
2016 * @category preference
2017 * @access public
2018 * @param string $name The key to unset as preference for the specified user
2019 * @param stdClass|int|null $user A moodle user object or id, null means current user
2020 * @throws coding_exception
2021 * @return bool Always true or exception
2023 function unset_user_preference($name, $user = null) {
2024 global $USER, $DB;
2026 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2027 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2030 if (is_null($user)) {
2031 $user = $USER;
2032 } else if (isset($user->id)) {
2033 // It is a valid object.
2034 } else if (is_numeric($user)) {
2035 $user = (object)array('id' => (int)$user);
2036 } else {
2037 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2040 check_user_preferences_loaded($user);
2042 if (empty($user->id) or isguestuser($user->id)) {
2043 // No permanent storage for not-logged-in user and guest.
2044 unset($user->preference[$name]);
2045 return true;
2048 // Delete from DB.
2049 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2051 // Delete the preference from cache.
2052 unset($user->preference[$name]);
2053 // Update the $USER in case where we've not a direct reference to $USER.
2054 if ($user !== $USER && $user->id == $USER->id) {
2055 unset($USER->preference[$name]);
2058 // Set reload flag for other sessions.
2059 mark_user_preferences_changed($user->id);
2061 return true;
2065 * Used to fetch user preference(s)
2067 * If no arguments are supplied this function will return
2068 * all of the current user preferences as an array.
2070 * If a name is specified then this function
2071 * attempts to return that particular preference value. If
2072 * none is found, then the optional value $default is returned,
2073 * otherwise null.
2075 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2077 * @package core
2078 * @category preference
2079 * @access public
2080 * @param string $name Name of the key to use in finding a preference value
2081 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2082 * @param stdClass|int|null $user A moodle user object or id, null means current user
2083 * @throws coding_exception
2084 * @return string|mixed|null A string containing the value of a single preference. An
2085 * array with all of the preferences or null
2087 function get_user_preferences($name = null, $default = null, $user = null) {
2088 global $USER;
2090 if (is_null($name)) {
2091 // All prefs.
2092 } else if (is_numeric($name) or $name === '_lastloaded') {
2093 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2096 if (is_null($user)) {
2097 $user = $USER;
2098 } else if (isset($user->id)) {
2099 // Is a valid object.
2100 } else if (is_numeric($user)) {
2101 if ($USER->id == $user) {
2102 $user = $USER;
2103 } else {
2104 $user = (object)array('id' => (int)$user);
2106 } else {
2107 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2110 check_user_preferences_loaded($user);
2112 if (empty($name)) {
2113 // All values.
2114 return $user->preference;
2115 } else if (isset($user->preference[$name])) {
2116 // The single string value.
2117 return $user->preference[$name];
2118 } else {
2119 // Default value (null if not specified).
2120 return $default;
2124 // FUNCTIONS FOR HANDLING TIME.
2127 * Given Gregorian date parts in user time produce a GMT timestamp.
2129 * @package core
2130 * @category time
2131 * @param int $year The year part to create timestamp of
2132 * @param int $month The month part to create timestamp of
2133 * @param int $day The day part to create timestamp of
2134 * @param int $hour The hour part to create timestamp of
2135 * @param int $minute The minute part to create timestamp of
2136 * @param int $second The second part to create timestamp of
2137 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2138 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2139 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2140 * applied only if timezone is 99 or string.
2141 * @return int GMT timestamp
2143 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2144 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2145 $date->setDate((int)$year, (int)$month, (int)$day);
2146 $date->setTime((int)$hour, (int)$minute, (int)$second);
2148 $time = $date->getTimestamp();
2150 if ($time === false) {
2151 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2152 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2155 // Moodle BC DST stuff.
2156 if (!$applydst) {
2157 $time += dst_offset_on($time, $timezone);
2160 return $time;
2165 * Format a date/time (seconds) as weeks, days, hours etc as needed
2167 * Given an amount of time in seconds, returns string
2168 * formatted nicely as years, days, hours etc as needed
2170 * @package core
2171 * @category time
2172 * @uses MINSECS
2173 * @uses HOURSECS
2174 * @uses DAYSECS
2175 * @uses YEARSECS
2176 * @param int $totalsecs Time in seconds
2177 * @param stdClass $str Should be a time object
2178 * @return string A nicely formatted date/time string
2180 function format_time($totalsecs, $str = null) {
2182 $totalsecs = abs($totalsecs);
2184 if (!$str) {
2185 // Create the str structure the slow way.
2186 $str = new stdClass();
2187 $str->day = get_string('day');
2188 $str->days = get_string('days');
2189 $str->hour = get_string('hour');
2190 $str->hours = get_string('hours');
2191 $str->min = get_string('min');
2192 $str->mins = get_string('mins');
2193 $str->sec = get_string('sec');
2194 $str->secs = get_string('secs');
2195 $str->year = get_string('year');
2196 $str->years = get_string('years');
2199 $years = floor($totalsecs/YEARSECS);
2200 $remainder = $totalsecs - ($years*YEARSECS);
2201 $days = floor($remainder/DAYSECS);
2202 $remainder = $totalsecs - ($days*DAYSECS);
2203 $hours = floor($remainder/HOURSECS);
2204 $remainder = $remainder - ($hours*HOURSECS);
2205 $mins = floor($remainder/MINSECS);
2206 $secs = $remainder - ($mins*MINSECS);
2208 $ss = ($secs == 1) ? $str->sec : $str->secs;
2209 $sm = ($mins == 1) ? $str->min : $str->mins;
2210 $sh = ($hours == 1) ? $str->hour : $str->hours;
2211 $sd = ($days == 1) ? $str->day : $str->days;
2212 $sy = ($years == 1) ? $str->year : $str->years;
2214 $oyears = '';
2215 $odays = '';
2216 $ohours = '';
2217 $omins = '';
2218 $osecs = '';
2220 if ($years) {
2221 $oyears = $years .' '. $sy;
2223 if ($days) {
2224 $odays = $days .' '. $sd;
2226 if ($hours) {
2227 $ohours = $hours .' '. $sh;
2229 if ($mins) {
2230 $omins = $mins .' '. $sm;
2232 if ($secs) {
2233 $osecs = $secs .' '. $ss;
2236 if ($years) {
2237 return trim($oyears .' '. $odays);
2239 if ($days) {
2240 return trim($odays .' '. $ohours);
2242 if ($hours) {
2243 return trim($ohours .' '. $omins);
2245 if ($mins) {
2246 return trim($omins .' '. $osecs);
2248 if ($secs) {
2249 return $osecs;
2251 return get_string('now');
2255 * Returns a formatted string that represents a date in user time.
2257 * @package core
2258 * @category time
2259 * @param int $date the timestamp in UTC, as obtained from the database.
2260 * @param string $format strftime format. You should probably get this using
2261 * get_string('strftime...', 'langconfig');
2262 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2263 * not 99 then daylight saving will not be added.
2264 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2265 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2266 * If false then the leading zero is maintained.
2267 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2268 * @return string the formatted date/time.
2270 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2271 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2272 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2276 * Returns a html "time" tag with both the exact user date with timezone information
2277 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2279 * @package core
2280 * @category time
2281 * @param int $date the timestamp in UTC, as obtained from the database.
2282 * @param string $format strftime format. You should probably get this using
2283 * get_string('strftime...', 'langconfig');
2284 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2285 * not 99 then daylight saving will not be added.
2286 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2287 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2288 * If false then the leading zero is maintained.
2289 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2290 * @return string the formatted date/time.
2292 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2293 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2294 if (CLI_SCRIPT && !PHPUNIT_TEST) {
2295 return $userdatestr;
2297 $machinedate = new DateTime();
2298 $machinedate->setTimestamp(intval($date));
2299 $machinedate->setTimezone(core_date::get_user_timezone_object());
2301 return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2305 * Returns a formatted date ensuring it is UTF-8.
2307 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2308 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2310 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2311 * @param string $format strftime format.
2312 * @param int|float|string $tz the user timezone
2313 * @return string the formatted date/time.
2314 * @since Moodle 2.3.3
2316 function date_format_string($date, $format, $tz = 99) {
2317 global $CFG;
2319 $localewincharset = null;
2320 // Get the calendar type user is using.
2321 if ($CFG->ostype == 'WINDOWS') {
2322 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2323 $localewincharset = $calendartype->locale_win_charset();
2326 if ($localewincharset) {
2327 $format = core_text::convert($format, 'utf-8', $localewincharset);
2330 date_default_timezone_set(core_date::get_user_timezone($tz));
2331 $datestring = strftime($format, $date);
2332 core_date::set_default_server_timezone();
2334 if ($localewincharset) {
2335 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2338 return $datestring;
2342 * Given a $time timestamp in GMT (seconds since epoch),
2343 * returns an array that represents the Gregorian date in user time
2345 * @package core
2346 * @category time
2347 * @param int $time Timestamp in GMT
2348 * @param float|int|string $timezone user timezone
2349 * @return array An array that represents the date in user time
2351 function usergetdate($time, $timezone=99) {
2352 date_default_timezone_set(core_date::get_user_timezone($timezone));
2353 $result = getdate($time);
2354 core_date::set_default_server_timezone();
2356 return $result;
2360 * Given a GMT timestamp (seconds since epoch), offsets it by
2361 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2363 * NOTE: this function does not include DST properly,
2364 * you should use the PHP date stuff instead!
2366 * @package core
2367 * @category time
2368 * @param int $date Timestamp in GMT
2369 * @param float|int|string $timezone user timezone
2370 * @return int
2372 function usertime($date, $timezone=99) {
2373 $userdate = new DateTime('@' . $date);
2374 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2375 $dst = dst_offset_on($date, $timezone);
2377 return $date - $userdate->getOffset() + $dst;
2381 * Get a formatted string representation of an interval between two unix timestamps.
2383 * E.g.
2384 * $intervalstring = get_time_interval_string(12345600, 12345660);
2385 * Will produce the string:
2386 * '0d 0h 1m'
2388 * @param int $time1 unix timestamp
2389 * @param int $time2 unix timestamp
2390 * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2391 * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2393 function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
2394 $dtdate = new DateTime();
2395 $dtdate->setTimeStamp($time1);
2396 $dtdate2 = new DateTime();
2397 $dtdate2->setTimeStamp($time2);
2398 $interval = $dtdate2->diff($dtdate);
2399 $format = empty($format) ? get_string('dateintervaldayshoursmins', 'langconfig') : $format;
2400 return $interval->format($format);
2404 * Given a time, return the GMT timestamp of the most recent midnight
2405 * for the current user.
2407 * @package core
2408 * @category time
2409 * @param int $date Timestamp in GMT
2410 * @param float|int|string $timezone user timezone
2411 * @return int Returns a GMT timestamp
2413 function usergetmidnight($date, $timezone=99) {
2415 $userdate = usergetdate($date, $timezone);
2417 // Time of midnight of this user's day, in GMT.
2418 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2423 * Returns a string that prints the user's timezone
2425 * @package core
2426 * @category time
2427 * @param float|int|string $timezone user timezone
2428 * @return string
2430 function usertimezone($timezone=99) {
2431 $tz = core_date::get_user_timezone($timezone);
2432 return core_date::get_localised_timezone($tz);
2436 * Returns a float or a string which denotes the user's timezone
2437 * 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)
2438 * means that for this timezone there are also DST rules to be taken into account
2439 * Checks various settings and picks the most dominant of those which have a value
2441 * @package core
2442 * @category time
2443 * @param float|int|string $tz timezone to calculate GMT time offset before
2444 * calculating user timezone, 99 is default user timezone
2445 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2446 * @return float|string
2448 function get_user_timezone($tz = 99) {
2449 global $USER, $CFG;
2451 $timezones = array(
2452 $tz,
2453 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2454 isset($USER->timezone) ? $USER->timezone : 99,
2455 isset($CFG->timezone) ? $CFG->timezone : 99,
2458 $tz = 99;
2460 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2461 foreach ($timezones as $nextvalue) {
2462 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2463 $tz = $nextvalue;
2466 return is_numeric($tz) ? (float) $tz : $tz;
2470 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2471 * - Note: Daylight saving only works for string timezones and not for float.
2473 * @package core
2474 * @category time
2475 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2476 * @param int|float|string $strtimezone user timezone
2477 * @return int
2479 function dst_offset_on($time, $strtimezone = null) {
2480 $tz = core_date::get_user_timezone($strtimezone);
2481 $date = new DateTime('@' . $time);
2482 $date->setTimezone(new DateTimeZone($tz));
2483 if ($date->format('I') == '1') {
2484 if ($tz === 'Australia/Lord_Howe') {
2485 return 1800;
2487 return 3600;
2489 return 0;
2493 * Calculates when the day appears in specific month
2495 * @package core
2496 * @category time
2497 * @param int $startday starting day of the month
2498 * @param int $weekday The day when week starts (normally taken from user preferences)
2499 * @param int $month The month whose day is sought
2500 * @param int $year The year of the month whose day is sought
2501 * @return int
2503 function find_day_in_month($startday, $weekday, $month, $year) {
2504 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2506 $daysinmonth = days_in_month($month, $year);
2507 $daysinweek = count($calendartype->get_weekdays());
2509 if ($weekday == -1) {
2510 // Don't care about weekday, so return:
2511 // abs($startday) if $startday != -1
2512 // $daysinmonth otherwise.
2513 return ($startday == -1) ? $daysinmonth : abs($startday);
2516 // From now on we 're looking for a specific weekday.
2517 // Give "end of month" its actual value, since we know it.
2518 if ($startday == -1) {
2519 $startday = -1 * $daysinmonth;
2522 // Starting from day $startday, the sign is the direction.
2523 if ($startday < 1) {
2524 $startday = abs($startday);
2525 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2527 // This is the last such weekday of the month.
2528 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2529 if ($lastinmonth > $daysinmonth) {
2530 $lastinmonth -= $daysinweek;
2533 // Find the first such weekday <= $startday.
2534 while ($lastinmonth > $startday) {
2535 $lastinmonth -= $daysinweek;
2538 return $lastinmonth;
2539 } else {
2540 $indexweekday = dayofweek($startday, $month, $year);
2542 $diff = $weekday - $indexweekday;
2543 if ($diff < 0) {
2544 $diff += $daysinweek;
2547 // This is the first such weekday of the month equal to or after $startday.
2548 $firstfromindex = $startday + $diff;
2550 return $firstfromindex;
2555 * Calculate the number of days in a given month
2557 * @package core
2558 * @category time
2559 * @param int $month The month whose day count is sought
2560 * @param int $year The year of the month whose day count is sought
2561 * @return int
2563 function days_in_month($month, $year) {
2564 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2565 return $calendartype->get_num_days_in_month($year, $month);
2569 * Calculate the position in the week of a specific calendar day
2571 * @package core
2572 * @category time
2573 * @param int $day The day of the date whose position in the week is sought
2574 * @param int $month The month of the date whose position in the week is sought
2575 * @param int $year The year of the date whose position in the week is sought
2576 * @return int
2578 function dayofweek($day, $month, $year) {
2579 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2580 return $calendartype->get_weekday($year, $month, $day);
2583 // USER AUTHENTICATION AND LOGIN.
2586 * Returns full login url.
2588 * Any form submissions for authentication to this URL must include username,
2589 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2591 * @return string login url
2593 function get_login_url() {
2594 global $CFG;
2596 return "$CFG->wwwroot/login/index.php";
2600 * This function checks that the current user is logged in and has the
2601 * required privileges
2603 * This function checks that the current user is logged in, and optionally
2604 * whether they are allowed to be in a particular course and view a particular
2605 * course module.
2606 * If they are not logged in, then it redirects them to the site login unless
2607 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2608 * case they are automatically logged in as guests.
2609 * If $courseid is given and the user is not enrolled in that course then the
2610 * user is redirected to the course enrolment page.
2611 * If $cm is given and the course module is hidden and the user is not a teacher
2612 * in the course then the user is redirected to the course home page.
2614 * When $cm parameter specified, this function sets page layout to 'module'.
2615 * You need to change it manually later if some other layout needed.
2617 * @package core_access
2618 * @category access
2620 * @param mixed $courseorid id of the course or course object
2621 * @param bool $autologinguest default true
2622 * @param object $cm course module object
2623 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2624 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2625 * in order to keep redirects working properly. MDL-14495
2626 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2627 * @return mixed Void, exit, and die depending on path
2628 * @throws coding_exception
2629 * @throws require_login_exception
2630 * @throws moodle_exception
2632 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2633 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2635 // Must not redirect when byteserving already started.
2636 if (!empty($_SERVER['HTTP_RANGE'])) {
2637 $preventredirect = true;
2640 if (AJAX_SCRIPT) {
2641 // We cannot redirect for AJAX scripts either.
2642 $preventredirect = true;
2645 // Setup global $COURSE, themes, language and locale.
2646 if (!empty($courseorid)) {
2647 if (is_object($courseorid)) {
2648 $course = $courseorid;
2649 } else if ($courseorid == SITEID) {
2650 $course = clone($SITE);
2651 } else {
2652 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2654 if ($cm) {
2655 if ($cm->course != $course->id) {
2656 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2658 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2659 if (!($cm instanceof cm_info)) {
2660 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2661 // db queries so this is not really a performance concern, however it is obviously
2662 // better if you use get_fast_modinfo to get the cm before calling this.
2663 $modinfo = get_fast_modinfo($course);
2664 $cm = $modinfo->get_cm($cm->id);
2667 } else {
2668 // Do not touch global $COURSE via $PAGE->set_course(),
2669 // the reasons is we need to be able to call require_login() at any time!!
2670 $course = $SITE;
2671 if ($cm) {
2672 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2676 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2677 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2678 // risk leading the user back to the AJAX request URL.
2679 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2680 $setwantsurltome = false;
2683 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2684 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2685 if ($preventredirect) {
2686 throw new require_login_session_timeout_exception();
2687 } else {
2688 if ($setwantsurltome) {
2689 $SESSION->wantsurl = qualified_me();
2691 redirect(get_login_url());
2695 // If the user is not even logged in yet then make sure they are.
2696 if (!isloggedin()) {
2697 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2698 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2699 // Misconfigured site guest, just redirect to login page.
2700 redirect(get_login_url());
2701 exit; // Never reached.
2703 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2704 complete_user_login($guest);
2705 $USER->autologinguest = true;
2706 $SESSION->lang = $lang;
2707 } else {
2708 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2709 if ($preventredirect) {
2710 throw new require_login_exception('You are not logged in');
2713 if ($setwantsurltome) {
2714 $SESSION->wantsurl = qualified_me();
2717 $referer = get_local_referer(false);
2718 if (!empty($referer)) {
2719 $SESSION->fromurl = $referer;
2722 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2723 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2724 foreach($authsequence as $authname) {
2725 $authplugin = get_auth_plugin($authname);
2726 $authplugin->pre_loginpage_hook();
2727 if (isloggedin()) {
2728 if ($cm) {
2729 $modinfo = get_fast_modinfo($course);
2730 $cm = $modinfo->get_cm($cm->id);
2732 set_access_log_user();
2733 break;
2737 // If we're still not logged in then go to the login page
2738 if (!isloggedin()) {
2739 redirect(get_login_url());
2740 exit; // Never reached.
2745 // Loginas as redirection if needed.
2746 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2747 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2748 if ($USER->loginascontext->instanceid != $course->id) {
2749 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2754 // Check whether the user should be changing password (but only if it is REALLY them).
2755 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2756 $userauth = get_auth_plugin($USER->auth);
2757 if ($userauth->can_change_password() and !$preventredirect) {
2758 if ($setwantsurltome) {
2759 $SESSION->wantsurl = qualified_me();
2761 if ($changeurl = $userauth->change_password_url()) {
2762 // Use plugin custom url.
2763 redirect($changeurl);
2764 } else {
2765 // Use moodle internal method.
2766 redirect($CFG->wwwroot .'/login/change_password.php');
2768 } else if ($userauth->can_change_password()) {
2769 throw new moodle_exception('forcepasswordchangenotice');
2770 } else {
2771 throw new moodle_exception('nopasswordchangeforced', 'auth');
2775 // Check that the user account is properly set up. If we can't redirect to
2776 // edit their profile and this is not a WS request, perform just the lax check.
2777 // It will allow them to use filepicker on the profile edit page.
2779 if ($preventredirect && !WS_SERVER) {
2780 $usernotfullysetup = user_not_fully_set_up($USER, false);
2781 } else {
2782 $usernotfullysetup = user_not_fully_set_up($USER, true);
2785 if ($usernotfullysetup) {
2786 if ($preventredirect) {
2787 throw new moodle_exception('usernotfullysetup');
2789 if ($setwantsurltome) {
2790 $SESSION->wantsurl = qualified_me();
2792 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2795 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2796 sesskey();
2798 if (\core\session\manager::is_loggedinas()) {
2799 // During a "logged in as" session we should force all content to be cleaned because the
2800 // logged in user will be viewing potentially malicious user generated content.
2801 // See MDL-63786 for more details.
2802 $CFG->forceclean = true;
2805 $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2807 // Do not bother admins with any formalities, except for activities pending deletion.
2808 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2809 // Set the global $COURSE.
2810 if ($cm) {
2811 $PAGE->set_cm($cm, $course);
2812 $PAGE->set_pagelayout('incourse');
2813 } else if (!empty($courseorid)) {
2814 $PAGE->set_course($course);
2816 // Set accesstime or the user will appear offline which messes up messaging.
2817 // Do not update access time for webservice or ajax requests.
2818 if (!WS_SERVER && !AJAX_SCRIPT) {
2819 user_accesstime_log($course->id);
2822 foreach ($afterlogins as $plugintype => $plugins) {
2823 foreach ($plugins as $pluginfunction) {
2824 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2827 return;
2830 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2831 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2832 if (!defined('NO_SITEPOLICY_CHECK')) {
2833 define('NO_SITEPOLICY_CHECK', false);
2836 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2837 // Do not test if the script explicitly asked for skipping the site policies check.
2838 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2839 $manager = new \core_privacy\local\sitepolicy\manager();
2840 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2841 if ($preventredirect) {
2842 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2844 if ($setwantsurltome) {
2845 $SESSION->wantsurl = qualified_me();
2847 redirect($policyurl);
2851 // Fetch the system context, the course context, and prefetch its child contexts.
2852 $sysctx = context_system::instance();
2853 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2854 if ($cm) {
2855 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2856 } else {
2857 $cmcontext = null;
2860 // If the site is currently under maintenance, then print a message.
2861 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2862 if ($preventredirect) {
2863 throw new require_login_exception('Maintenance in progress');
2865 $PAGE->set_context(null);
2866 print_maintenance_message();
2869 // Make sure the course itself is not hidden.
2870 if ($course->id == SITEID) {
2871 // Frontpage can not be hidden.
2872 } else {
2873 if (is_role_switched($course->id)) {
2874 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2875 } else {
2876 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2877 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2878 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2879 if ($preventredirect) {
2880 throw new require_login_exception('Course is hidden');
2882 $PAGE->set_context(null);
2883 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2884 // the navigation will mess up when trying to find it.
2885 navigation_node::override_active_url(new moodle_url('/'));
2886 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2891 // Is the user enrolled?
2892 if ($course->id == SITEID) {
2893 // Everybody is enrolled on the frontpage.
2894 } else {
2895 if (\core\session\manager::is_loggedinas()) {
2896 // Make sure the REAL person can access this course first.
2897 $realuser = \core\session\manager::get_realuser();
2898 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2899 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2900 if ($preventredirect) {
2901 throw new require_login_exception('Invalid course login-as access');
2903 $PAGE->set_context(null);
2904 echo $OUTPUT->header();
2905 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2909 $access = false;
2911 if (is_role_switched($course->id)) {
2912 // Ok, user had to be inside this course before the switch.
2913 $access = true;
2915 } else if (is_viewing($coursecontext, $USER)) {
2916 // Ok, no need to mess with enrol.
2917 $access = true;
2919 } else {
2920 if (isset($USER->enrol['enrolled'][$course->id])) {
2921 if ($USER->enrol['enrolled'][$course->id] > time()) {
2922 $access = true;
2923 if (isset($USER->enrol['tempguest'][$course->id])) {
2924 unset($USER->enrol['tempguest'][$course->id]);
2925 remove_temp_course_roles($coursecontext);
2927 } else {
2928 // Expired.
2929 unset($USER->enrol['enrolled'][$course->id]);
2932 if (isset($USER->enrol['tempguest'][$course->id])) {
2933 if ($USER->enrol['tempguest'][$course->id] == 0) {
2934 $access = true;
2935 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2936 $access = true;
2937 } else {
2938 // Expired.
2939 unset($USER->enrol['tempguest'][$course->id]);
2940 remove_temp_course_roles($coursecontext);
2944 if (!$access) {
2945 // Cache not ok.
2946 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2947 if ($until !== false) {
2948 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2949 if ($until == 0) {
2950 $until = ENROL_MAX_TIMESTAMP;
2952 $USER->enrol['enrolled'][$course->id] = $until;
2953 $access = true;
2955 } else if (core_course_category::can_view_course_info($course)) {
2956 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2957 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2958 $enrols = enrol_get_plugins(true);
2959 // First ask all enabled enrol instances in course if they want to auto enrol user.
2960 foreach ($instances as $instance) {
2961 if (!isset($enrols[$instance->enrol])) {
2962 continue;
2964 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2965 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2966 if ($until !== false) {
2967 if ($until == 0) {
2968 $until = ENROL_MAX_TIMESTAMP;
2970 $USER->enrol['enrolled'][$course->id] = $until;
2971 $access = true;
2972 break;
2975 // If not enrolled yet try to gain temporary guest access.
2976 if (!$access) {
2977 foreach ($instances as $instance) {
2978 if (!isset($enrols[$instance->enrol])) {
2979 continue;
2981 // Get a duration for the guest access, a timestamp in the future or false.
2982 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2983 if ($until !== false and $until > time()) {
2984 $USER->enrol['tempguest'][$course->id] = $until;
2985 $access = true;
2986 break;
2990 } else {
2991 // User is not enrolled and is not allowed to browse courses here.
2992 if ($preventredirect) {
2993 throw new require_login_exception('Course is not available');
2995 $PAGE->set_context(null);
2996 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2997 // the navigation will mess up when trying to find it.
2998 navigation_node::override_active_url(new moodle_url('/'));
2999 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3004 if (!$access) {
3005 if ($preventredirect) {
3006 throw new require_login_exception('Not enrolled');
3008 if ($setwantsurltome) {
3009 $SESSION->wantsurl = qualified_me();
3011 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3015 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3016 if ($cm && $cm->deletioninprogress) {
3017 if ($preventredirect) {
3018 throw new moodle_exception('activityisscheduledfordeletion');
3020 require_once($CFG->dirroot . '/course/lib.php');
3021 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3024 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3025 if ($cm && !$cm->uservisible) {
3026 if ($preventredirect) {
3027 throw new require_login_exception('Activity is hidden');
3029 // Get the error message that activity is not available and why (if explanation can be shown to the user).
3030 $PAGE->set_course($course);
3031 $renderer = $PAGE->get_renderer('course');
3032 $message = $renderer->course_section_cm_unavailable_error_message($cm);
3033 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
3036 // Set the global $COURSE.
3037 if ($cm) {
3038 $PAGE->set_cm($cm, $course);
3039 $PAGE->set_pagelayout('incourse');
3040 } else if (!empty($courseorid)) {
3041 $PAGE->set_course($course);
3044 foreach ($afterlogins as $plugintype => $plugins) {
3045 foreach ($plugins as $pluginfunction) {
3046 $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3050 // Finally access granted, update lastaccess times.
3051 // Do not update access time for webservice or ajax requests.
3052 if (!WS_SERVER && !AJAX_SCRIPT) {
3053 user_accesstime_log($course->id);
3058 * A convenience function for where we must be logged in as admin
3059 * @return void
3061 function require_admin() {
3062 require_login(null, false);
3063 require_capability('moodle/site:config', context_system::instance());
3067 * This function just makes sure a user is logged out.
3069 * @package core_access
3070 * @category access
3072 function require_logout() {
3073 global $USER, $DB;
3075 if (!isloggedin()) {
3076 // This should not happen often, no need for hooks or events here.
3077 \core\session\manager::terminate_current();
3078 return;
3081 // Execute hooks before action.
3082 $authplugins = array();
3083 $authsequence = get_enabled_auth_plugins();
3084 foreach ($authsequence as $authname) {
3085 $authplugins[$authname] = get_auth_plugin($authname);
3086 $authplugins[$authname]->prelogout_hook();
3089 // Store info that gets removed during logout.
3090 $sid = session_id();
3091 $event = \core\event\user_loggedout::create(
3092 array(
3093 'userid' => $USER->id,
3094 'objectid' => $USER->id,
3095 'other' => array('sessionid' => $sid),
3098 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3099 $event->add_record_snapshot('sessions', $session);
3102 // Clone of $USER object to be used by auth plugins.
3103 $user = fullclone($USER);
3105 // Delete session record and drop $_SESSION content.
3106 \core\session\manager::terminate_current();
3108 // Trigger event AFTER action.
3109 $event->trigger();
3111 // Hook to execute auth plugins redirection after event trigger.
3112 foreach ($authplugins as $authplugin) {
3113 $authplugin->postlogout_hook($user);
3118 * Weaker version of require_login()
3120 * This is a weaker version of {@link require_login()} which only requires login
3121 * when called from within a course rather than the site page, unless
3122 * the forcelogin option is turned on.
3123 * @see require_login()
3125 * @package core_access
3126 * @category access
3128 * @param mixed $courseorid The course object or id in question
3129 * @param bool $autologinguest Allow autologin guests if that is wanted
3130 * @param object $cm Course activity module if known
3131 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3132 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3133 * in order to keep redirects working properly. MDL-14495
3134 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3135 * @return void
3136 * @throws coding_exception
3138 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3139 global $CFG, $PAGE, $SITE;
3140 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3141 or (!is_object($courseorid) and $courseorid == SITEID));
3142 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3143 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3144 // db queries so this is not really a performance concern, however it is obviously
3145 // better if you use get_fast_modinfo to get the cm before calling this.
3146 if (is_object($courseorid)) {
3147 $course = $courseorid;
3148 } else {
3149 $course = clone($SITE);
3151 $modinfo = get_fast_modinfo($course);
3152 $cm = $modinfo->get_cm($cm->id);
3154 if (!empty($CFG->forcelogin)) {
3155 // Login required for both SITE and courses.
3156 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3158 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3159 // Always login for hidden activities.
3160 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3162 } else if (isloggedin() && !isguestuser()) {
3163 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3164 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3166 } else if ($issite) {
3167 // Login for SITE not required.
3168 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3169 if (!empty($courseorid)) {
3170 if (is_object($courseorid)) {
3171 $course = $courseorid;
3172 } else {
3173 $course = clone $SITE;
3175 if ($cm) {
3176 if ($cm->course != $course->id) {
3177 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3179 $PAGE->set_cm($cm, $course);
3180 $PAGE->set_pagelayout('incourse');
3181 } else {
3182 $PAGE->set_course($course);
3184 } else {
3185 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3186 $PAGE->set_course($PAGE->course);
3188 // Do not update access time for webservice or ajax requests.
3189 if (!WS_SERVER && !AJAX_SCRIPT) {
3190 user_accesstime_log(SITEID);
3192 return;
3194 } else {
3195 // Course login always required.
3196 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3201 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3203 * @param string $keyvalue the key value
3204 * @param string $script unique script identifier
3205 * @param int $instance instance id
3206 * @return stdClass the key entry in the user_private_key table
3207 * @since Moodle 3.2
3208 * @throws moodle_exception
3210 function validate_user_key($keyvalue, $script, $instance) {
3211 global $DB;
3213 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3214 print_error('invalidkey');
3217 if (!empty($key->validuntil) and $key->validuntil < time()) {
3218 print_error('expiredkey');
3221 if ($key->iprestriction) {
3222 $remoteaddr = getremoteaddr(null);
3223 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3224 print_error('ipmismatch');
3227 return $key;
3231 * Require key login. Function terminates with error if key not found or incorrect.
3233 * @uses NO_MOODLE_COOKIES
3234 * @uses PARAM_ALPHANUM
3235 * @param string $script unique script identifier
3236 * @param int $instance optional instance id
3237 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3238 * @return int Instance ID
3240 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3241 global $DB;
3243 if (!NO_MOODLE_COOKIES) {
3244 print_error('sessioncookiesdisable');
3247 // Extra safety.
3248 \core\session\manager::write_close();
3250 if (null === $keyvalue) {
3251 $keyvalue = required_param('key', PARAM_ALPHANUM);
3254 $key = validate_user_key($keyvalue, $script, $instance);
3256 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3257 print_error('invaliduserid');
3260 // Emulate normal session.
3261 enrol_check_plugins($user);
3262 \core\session\manager::set_user($user);
3264 // Note we are not using normal login.
3265 if (!defined('USER_KEY_LOGIN')) {
3266 define('USER_KEY_LOGIN', true);
3269 // Return instance id - it might be empty.
3270 return $key->instance;
3274 * Creates a new private user access key.
3276 * @param string $script unique target identifier
3277 * @param int $userid
3278 * @param int $instance optional instance id
3279 * @param string $iprestriction optional ip restricted access
3280 * @param int $validuntil key valid only until given data
3281 * @return string access key value
3283 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3284 global $DB;
3286 $key = new stdClass();
3287 $key->script = $script;
3288 $key->userid = $userid;
3289 $key->instance = $instance;
3290 $key->iprestriction = $iprestriction;
3291 $key->validuntil = $validuntil;
3292 $key->timecreated = time();
3294 // Something long and unique.
3295 $key->value = md5($userid.'_'.time().random_string(40));
3296 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3297 // Must be unique.
3298 $key->value = md5($userid.'_'.time().random_string(40));
3300 $DB->insert_record('user_private_key', $key);
3301 return $key->value;
3305 * Delete the user's new private user access keys for a particular script.
3307 * @param string $script unique target identifier
3308 * @param int $userid
3309 * @return void
3311 function delete_user_key($script, $userid) {
3312 global $DB;
3313 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3317 * Gets a private user access key (and creates one if one doesn't exist).
3319 * @param string $script unique target identifier
3320 * @param int $userid
3321 * @param int $instance optional instance id
3322 * @param string $iprestriction optional ip restricted access
3323 * @param int $validuntil key valid only until given date
3324 * @return string access key value
3326 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3327 global $DB;
3329 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3330 'instance' => $instance, 'iprestriction' => $iprestriction,
3331 'validuntil' => $validuntil))) {
3332 return $key->value;
3333 } else {
3334 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3340 * Modify the user table by setting the currently logged in user's last login to now.
3342 * @return bool Always returns true
3344 function update_user_login_times() {
3345 global $USER, $DB;
3347 if (isguestuser()) {
3348 // Do not update guest access times/ips for performance.
3349 return true;
3352 $now = time();
3354 $user = new stdClass();
3355 $user->id = $USER->id;
3357 // Make sure all users that logged in have some firstaccess.
3358 if ($USER->firstaccess == 0) {
3359 $USER->firstaccess = $user->firstaccess = $now;
3362 // Store the previous current as lastlogin.
3363 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3365 $USER->currentlogin = $user->currentlogin = $now;
3367 // Function user_accesstime_log() may not update immediately, better do it here.
3368 $USER->lastaccess = $user->lastaccess = $now;
3369 $USER->lastip = $user->lastip = getremoteaddr();
3371 // Note: do not call user_update_user() here because this is part of the login process,
3372 // the login event means that these fields were updated.
3373 $DB->update_record('user', $user);
3374 return true;
3378 * Determines if a user has completed setting up their account.
3380 * The lax mode (with $strict = false) has been introduced for special cases
3381 * only where we want to skip certain checks intentionally. This is valid in
3382 * certain mnet or ajax scenarios when the user cannot / should not be
3383 * redirected to edit their profile. In most cases, you should perform the
3384 * strict check.
3386 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3387 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3388 * @return bool
3390 function user_not_fully_set_up($user, $strict = true) {
3391 global $CFG;
3392 require_once($CFG->dirroot.'/user/profile/lib.php');
3394 if (isguestuser($user)) {
3395 return false;
3398 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3399 return true;
3402 if ($strict) {
3403 if (empty($user->id)) {
3404 // Strict mode can be used with existing accounts only.
3405 return true;
3407 if (!profile_has_required_custom_fields_set($user->id)) {
3408 return true;
3412 return false;
3416 * Check whether the user has exceeded the bounce threshold
3418 * @param stdClass $user A {@link $USER} object
3419 * @return bool true => User has exceeded bounce threshold
3421 function over_bounce_threshold($user) {
3422 global $CFG, $DB;
3424 if (empty($CFG->handlebounces)) {
3425 return false;
3428 if (empty($user->id)) {
3429 // No real (DB) user, nothing to do here.
3430 return false;
3433 // Set sensible defaults.
3434 if (empty($CFG->minbounces)) {
3435 $CFG->minbounces = 10;
3437 if (empty($CFG->bounceratio)) {
3438 $CFG->bounceratio = .20;
3440 $bouncecount = 0;
3441 $sendcount = 0;
3442 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3443 $bouncecount = $bounce->value;
3445 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3446 $sendcount = $send->value;
3448 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3452 * Used to increment or reset email sent count
3454 * @param stdClass $user object containing an id
3455 * @param bool $reset will reset the count to 0
3456 * @return void
3458 function set_send_count($user, $reset=false) {
3459 global $DB;
3461 if (empty($user->id)) {
3462 // No real (DB) user, nothing to do here.
3463 return;
3466 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3467 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3468 $DB->update_record('user_preferences', $pref);
3469 } else if (!empty($reset)) {
3470 // If it's not there and we're resetting, don't bother. Make a new one.
3471 $pref = new stdClass();
3472 $pref->name = 'email_send_count';
3473 $pref->value = 1;
3474 $pref->userid = $user->id;
3475 $DB->insert_record('user_preferences', $pref, false);
3480 * Increment or reset user's email bounce count
3482 * @param stdClass $user object containing an id
3483 * @param bool $reset will reset the count to 0
3485 function set_bounce_count($user, $reset=false) {
3486 global $DB;
3488 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3489 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3490 $DB->update_record('user_preferences', $pref);
3491 } else if (!empty($reset)) {
3492 // If it's not there and we're resetting, don't bother. Make a new one.
3493 $pref = new stdClass();
3494 $pref->name = 'email_bounce_count';
3495 $pref->value = 1;
3496 $pref->userid = $user->id;
3497 $DB->insert_record('user_preferences', $pref, false);
3502 * Determines if the logged in user is currently moving an activity
3504 * @param int $courseid The id of the course being tested
3505 * @return bool
3507 function ismoving($courseid) {
3508 global $USER;
3510 if (!empty($USER->activitycopy)) {
3511 return ($USER->activitycopycourse == $courseid);
3513 return false;
3517 * Returns a persons full name
3519 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3520 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3521 * specify one.
3523 * @param stdClass $user A {@link $USER} object to get full name of.
3524 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3525 * @return string
3527 function fullname($user, $override=false) {
3528 global $CFG, $SESSION;
3530 if (!isset($user->firstname) and !isset($user->lastname)) {
3531 return '';
3534 // Get all of the name fields.
3535 $allnames = get_all_user_name_fields();
3536 if ($CFG->debugdeveloper) {
3537 foreach ($allnames as $allname) {
3538 if (!property_exists($user, $allname)) {
3539 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3540 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3541 // Message has been sent, no point in sending the message multiple times.
3542 break;
3547 if (!$override) {
3548 if (!empty($CFG->forcefirstname)) {
3549 $user->firstname = $CFG->forcefirstname;
3551 if (!empty($CFG->forcelastname)) {
3552 $user->lastname = $CFG->forcelastname;
3556 if (!empty($SESSION->fullnamedisplay)) {
3557 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3560 $template = null;
3561 // If the fullnamedisplay setting is available, set the template to that.
3562 if (isset($CFG->fullnamedisplay)) {
3563 $template = $CFG->fullnamedisplay;
3565 // If the template is empty, or set to language, return the language string.
3566 if ((empty($template) || $template == 'language') && !$override) {
3567 return get_string('fullnamedisplay', null, $user);
3570 // Check to see if we are displaying according to the alternative full name format.
3571 if ($override) {
3572 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3573 // Default to show just the user names according to the fullnamedisplay string.
3574 return get_string('fullnamedisplay', null, $user);
3575 } else {
3576 // If the override is true, then change the template to use the complete name.
3577 $template = $CFG->alternativefullnameformat;
3581 $requirednames = array();
3582 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3583 foreach ($allnames as $allname) {
3584 if (strpos($template, $allname) !== false) {
3585 $requirednames[] = $allname;
3589 $displayname = $template;
3590 // Switch in the actual data into the template.
3591 foreach ($requirednames as $altname) {
3592 if (isset($user->$altname)) {
3593 // Using empty() on the below if statement causes breakages.
3594 if ((string)$user->$altname == '') {
3595 $displayname = str_replace($altname, 'EMPTY', $displayname);
3596 } else {
3597 $displayname = str_replace($altname, $user->$altname, $displayname);
3599 } else {
3600 $displayname = str_replace($altname, 'EMPTY', $displayname);
3603 // Tidy up any misc. characters (Not perfect, but gets most characters).
3604 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3605 // katakana and parenthesis.
3606 $patterns = array();
3607 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3608 // filled in by a user.
3609 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3610 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3611 // This regular expression is to remove any double spaces in the display name.
3612 $patterns[] = '/\s{2,}/u';
3613 foreach ($patterns as $pattern) {
3614 $displayname = preg_replace($pattern, ' ', $displayname);
3617 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3618 $displayname = trim($displayname);
3619 if (empty($displayname)) {
3620 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3621 // people in general feel is a good setting to fall back on.
3622 $displayname = $user->firstname;
3624 return $displayname;
3628 * A centralised location for the all name fields. Returns an array / sql string snippet.
3630 * @param bool $returnsql True for an sql select field snippet.
3631 * @param string $tableprefix table query prefix to use in front of each field.
3632 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3633 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3634 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3635 * @return array|string All name fields.
3637 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3638 // This array is provided in this order because when called by fullname() (above) if firstname is before
3639 // firstnamephonetic str_replace() will change the wrong placeholder.
3640 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3641 'lastnamephonetic' => 'lastnamephonetic',
3642 'middlename' => 'middlename',
3643 'alternatename' => 'alternatename',
3644 'firstname' => 'firstname',
3645 'lastname' => 'lastname');
3647 // Let's add a prefix to the array of user name fields if provided.
3648 if ($prefix) {
3649 foreach ($alternatenames as $key => $altname) {
3650 $alternatenames[$key] = $prefix . $altname;
3654 // If we want the end result to have firstname and lastname at the front / top of the result.
3655 if ($order) {
3656 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3657 for ($i = 0; $i < 2; $i++) {
3658 // Get the last element.
3659 $lastelement = end($alternatenames);
3660 // Remove it from the array.
3661 unset($alternatenames[$lastelement]);
3662 // Put the element back on the top of the array.
3663 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3667 // Create an sql field snippet if requested.
3668 if ($returnsql) {
3669 if ($tableprefix) {
3670 if ($fieldprefix) {
3671 foreach ($alternatenames as $key => $altname) {
3672 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3674 } else {
3675 foreach ($alternatenames as $key => $altname) {
3676 $alternatenames[$key] = $tableprefix . '.' . $altname;
3680 $alternatenames = implode(',', $alternatenames);
3682 return $alternatenames;
3686 * Reduces lines of duplicated code for getting user name fields.
3688 * See also {@link user_picture::unalias()}
3690 * @param object $addtoobject Object to add user name fields to.
3691 * @param object $secondobject Object that contains user name field information.
3692 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3693 * @param array $additionalfields Additional fields to be matched with data in the second object.
3694 * The key can be set to the user table field name.
3695 * @return object User name fields.
3697 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3698 $fields = get_all_user_name_fields(false, null, $prefix);
3699 if ($additionalfields) {
3700 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3701 // the key is a number and then sets the key to the array value.
3702 foreach ($additionalfields as $key => $value) {
3703 if (is_numeric($key)) {
3704 $additionalfields[$value] = $prefix . $value;
3705 unset($additionalfields[$key]);
3706 } else {
3707 $additionalfields[$key] = $prefix . $value;
3710 $fields = array_merge($fields, $additionalfields);
3712 foreach ($fields as $key => $field) {
3713 // Important that we have all of the user name fields present in the object that we are sending back.
3714 $addtoobject->$key = '';
3715 if (isset($secondobject->$field)) {
3716 $addtoobject->$key = $secondobject->$field;
3719 return $addtoobject;
3723 * Returns an array of values in order of occurance in a provided string.
3724 * The key in the result is the character postion in the string.
3726 * @param array $values Values to be found in the string format
3727 * @param string $stringformat The string which may contain values being searched for.
3728 * @return array An array of values in order according to placement in the string format.
3730 function order_in_string($values, $stringformat) {
3731 $valuearray = array();
3732 foreach ($values as $value) {
3733 $pattern = "/$value\b/";
3734 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3735 if (preg_match($pattern, $stringformat)) {
3736 $replacement = "thing";
3737 // Replace the value with something more unique to ensure we get the right position when using strpos().
3738 $newformat = preg_replace($pattern, $replacement, $stringformat);
3739 $position = strpos($newformat, $replacement);
3740 $valuearray[$position] = $value;
3743 ksort($valuearray);
3744 return $valuearray;
3748 * Checks if current user is shown any extra fields when listing users.
3750 * @param object $context Context
3751 * @param array $already Array of fields that we're going to show anyway
3752 * so don't bother listing them
3753 * @return array Array of field names from user table, not including anything
3754 * listed in $already
3756 function get_extra_user_fields($context, $already = array()) {
3757 global $CFG;
3759 // Only users with permission get the extra fields.
3760 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3761 return array();
3764 // Split showuseridentity on comma (filter needed in case the showuseridentity is empty).
3765 $extra = array_filter(explode(',', $CFG->showuseridentity));
3767 foreach ($extra as $key => $field) {
3768 if (in_array($field, $already)) {
3769 unset($extra[$key]);
3773 // If the identity fields are also among hidden fields, make sure the user can see them.
3774 $hiddenfields = array_filter(explode(',', $CFG->hiddenuserfields));
3775 $hiddenidentifiers = array_intersect($extra, $hiddenfields);
3777 if ($hiddenidentifiers) {
3778 if ($context->get_course_context(false)) {
3779 // We are somewhere inside a course.
3780 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3782 } else {
3783 // We are not inside a course.
3784 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
3787 if (!$canviewhiddenuserfields) {
3788 // Remove hidden identifiers from the list.
3789 $extra = array_diff($extra, $hiddenidentifiers);
3793 // Re-index the entries.
3794 $extra = array_values($extra);
3796 return $extra;
3800 * If the current user is to be shown extra user fields when listing or
3801 * selecting users, returns a string suitable for including in an SQL select
3802 * clause to retrieve those fields.
3804 * @param context $context Context
3805 * @param string $alias Alias of user table, e.g. 'u' (default none)
3806 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3807 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3808 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3810 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3811 $fields = get_extra_user_fields($context, $already);
3812 $result = '';
3813 // Add punctuation for alias.
3814 if ($alias !== '') {
3815 $alias .= '.';
3817 foreach ($fields as $field) {
3818 $result .= ', ' . $alias . $field;
3819 if ($prefix) {
3820 $result .= ' AS ' . $prefix . $field;
3823 return $result;
3827 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3828 * @param string $field Field name, e.g. 'phone1'
3829 * @return string Text description taken from language file, e.g. 'Phone number'
3831 function get_user_field_name($field) {
3832 // Some fields have language strings which are not the same as field name.
3833 switch ($field) {
3834 case 'url' : {
3835 return get_string('webpage');
3837 case 'icq' : {
3838 return get_string('icqnumber');
3840 case 'skype' : {
3841 return get_string('skypeid');
3843 case 'aim' : {
3844 return get_string('aimid');
3846 case 'yahoo' : {
3847 return get_string('yahooid');
3849 case 'msn' : {
3850 return get_string('msnid');
3852 case 'picture' : {
3853 return get_string('pictureofuser');
3856 // Otherwise just use the same lang string.
3857 return get_string($field);
3861 * Returns whether a given authentication plugin exists.
3863 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3864 * @return boolean Whether the plugin is available.
3866 function exists_auth_plugin($auth) {
3867 global $CFG;
3869 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3870 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3872 return false;
3876 * Checks if a given plugin is in the list of enabled authentication plugins.
3878 * @param string $auth Authentication plugin.
3879 * @return boolean Whether the plugin is enabled.
3881 function is_enabled_auth($auth) {
3882 if (empty($auth)) {
3883 return false;
3886 $enabled = get_enabled_auth_plugins();
3888 return in_array($auth, $enabled);
3892 * Returns an authentication plugin instance.
3894 * @param string $auth name of authentication plugin
3895 * @return auth_plugin_base An instance of the required authentication plugin.
3897 function get_auth_plugin($auth) {
3898 global $CFG;
3900 // Check the plugin exists first.
3901 if (! exists_auth_plugin($auth)) {
3902 print_error('authpluginnotfound', 'debug', '', $auth);
3905 // Return auth plugin instance.
3906 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3907 $class = "auth_plugin_$auth";
3908 return new $class;
3912 * Returns array of active auth plugins.
3914 * @param bool $fix fix $CFG->auth if needed
3915 * @return array
3917 function get_enabled_auth_plugins($fix=false) {
3918 global $CFG;
3920 $default = array('manual', 'nologin');
3922 if (empty($CFG->auth)) {
3923 $auths = array();
3924 } else {
3925 $auths = explode(',', $CFG->auth);
3928 if ($fix) {
3929 $auths = array_unique($auths);
3930 foreach ($auths as $k => $authname) {
3931 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3932 unset($auths[$k]);
3935 $newconfig = implode(',', $auths);
3936 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3937 set_config('auth', $newconfig);
3941 return (array_merge($default, $auths));
3945 * Returns true if an internal authentication method is being used.
3946 * if method not specified then, global default is assumed
3948 * @param string $auth Form of authentication required
3949 * @return bool
3951 function is_internal_auth($auth) {
3952 // Throws error if bad $auth.
3953 $authplugin = get_auth_plugin($auth);
3954 return $authplugin->is_internal();
3958 * Returns true if the user is a 'restored' one.
3960 * Used in the login process to inform the user and allow him/her to reset the password
3962 * @param string $username username to be checked
3963 * @return bool
3965 function is_restored_user($username) {
3966 global $CFG, $DB;
3968 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3972 * Returns an array of user fields
3974 * @return array User field/column names
3976 function get_user_fieldnames() {
3977 global $DB;
3979 $fieldarray = $DB->get_columns('user');
3980 unset($fieldarray['id']);
3981 $fieldarray = array_keys($fieldarray);
3983 return $fieldarray;
3987 * Creates a bare-bones user record
3989 * @todo Outline auth types and provide code example
3991 * @param string $username New user's username to add to record
3992 * @param string $password New user's password to add to record
3993 * @param string $auth Form of authentication required
3994 * @return stdClass A complete user object
3996 function create_user_record($username, $password, $auth = 'manual') {
3997 global $CFG, $DB;
3998 require_once($CFG->dirroot.'/user/profile/lib.php');
3999 require_once($CFG->dirroot.'/user/lib.php');
4001 // Just in case check text case.
4002 $username = trim(core_text::strtolower($username));
4004 $authplugin = get_auth_plugin($auth);
4005 $customfields = $authplugin->get_custom_user_profile_fields();
4006 $newuser = new stdClass();
4007 if ($newinfo = $authplugin->get_userinfo($username)) {
4008 $newinfo = truncate_userinfo($newinfo);
4009 foreach ($newinfo as $key => $value) {
4010 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
4011 $newuser->$key = $value;
4016 if (!empty($newuser->email)) {
4017 if (email_is_not_allowed($newuser->email)) {
4018 unset($newuser->email);
4022 if (!isset($newuser->city)) {
4023 $newuser->city = '';
4026 $newuser->auth = $auth;
4027 $newuser->username = $username;
4029 // Fix for MDL-8480
4030 // user CFG lang for user if $newuser->lang is empty
4031 // or $user->lang is not an installed language.
4032 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
4033 $newuser->lang = $CFG->lang;
4035 $newuser->confirmed = 1;
4036 $newuser->lastip = getremoteaddr();
4037 $newuser->timecreated = time();
4038 $newuser->timemodified = $newuser->timecreated;
4039 $newuser->mnethostid = $CFG->mnet_localhost_id;
4041 $newuser->id = user_create_user($newuser, false, false);
4043 // Save user profile data.
4044 profile_save_data($newuser);
4046 $user = get_complete_user_data('id', $newuser->id);
4047 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
4048 set_user_preference('auth_forcepasswordchange', 1, $user);
4050 // Set the password.
4051 update_internal_user_password($user, $password);
4053 // Trigger event.
4054 \core\event\user_created::create_from_userid($newuser->id)->trigger();
4056 return $user;
4060 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4062 * @param string $username user's username to update the record
4063 * @return stdClass A complete user object
4065 function update_user_record($username) {
4066 global $DB, $CFG;
4067 // Just in case check text case.
4068 $username = trim(core_text::strtolower($username));
4070 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
4071 return update_user_record_by_id($oldinfo->id);
4075 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4077 * @param int $id user id
4078 * @return stdClass A complete user object
4080 function update_user_record_by_id($id) {
4081 global $DB, $CFG;
4082 require_once($CFG->dirroot."/user/profile/lib.php");
4083 require_once($CFG->dirroot.'/user/lib.php');
4085 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
4086 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
4088 $newuser = array();
4089 $userauth = get_auth_plugin($oldinfo->auth);
4091 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
4092 $newinfo = truncate_userinfo($newinfo);
4093 $customfields = $userauth->get_custom_user_profile_fields();
4095 foreach ($newinfo as $key => $value) {
4096 $iscustom = in_array($key, $customfields);
4097 if (!$iscustom) {
4098 $key = strtolower($key);
4100 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4101 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4102 // Unknown or must not be changed.
4103 continue;
4105 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
4106 continue;
4108 $confval = $userauth->config->{'field_updatelocal_' . $key};
4109 $lockval = $userauth->config->{'field_lock_' . $key};
4110 if ($confval === 'onlogin') {
4111 // MDL-4207 Don't overwrite modified user profile values with
4112 // empty LDAP values when 'unlocked if empty' is set. The purpose
4113 // of the setting 'unlocked if empty' is to allow the user to fill
4114 // in a value for the selected field _if LDAP is giving
4115 // nothing_ for this field. Thus it makes sense to let this value
4116 // stand in until LDAP is giving a value for this field.
4117 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4118 if ($iscustom || (in_array($key, $userauth->userfields) &&
4119 ((string)$oldinfo->$key !== (string)$value))) {
4120 $newuser[$key] = (string)$value;
4125 if ($newuser) {
4126 $newuser['id'] = $oldinfo->id;
4127 $newuser['timemodified'] = time();
4128 user_update_user((object) $newuser, false, false);
4130 // Save user profile data.
4131 profile_save_data((object) $newuser);
4133 // Trigger event.
4134 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4138 return get_complete_user_data('id', $oldinfo->id);
4142 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4144 * @param array $info Array of user properties to truncate if needed
4145 * @return array The now truncated information that was passed in
4147 function truncate_userinfo(array $info) {
4148 // Define the limits.
4149 $limit = array(
4150 'username' => 100,
4151 'idnumber' => 255,
4152 'firstname' => 100,
4153 'lastname' => 100,
4154 'email' => 100,
4155 'icq' => 15,
4156 'phone1' => 20,
4157 'phone2' => 20,
4158 'institution' => 255,
4159 'department' => 255,
4160 'address' => 255,
4161 'city' => 120,
4162 'country' => 2,
4163 'url' => 255,
4166 // Apply where needed.
4167 foreach (array_keys($info) as $key) {
4168 if (!empty($limit[$key])) {
4169 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4173 return $info;
4177 * Marks user deleted in internal user database and notifies the auth plugin.
4178 * Also unenrols user from all roles and does other cleanup.
4180 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4182 * @param stdClass $user full user object before delete
4183 * @return boolean success
4184 * @throws coding_exception if invalid $user parameter detected
4186 function delete_user(stdClass $user) {
4187 global $CFG, $DB, $SESSION;
4188 require_once($CFG->libdir.'/grouplib.php');
4189 require_once($CFG->libdir.'/gradelib.php');
4190 require_once($CFG->dirroot.'/message/lib.php');
4191 require_once($CFG->dirroot.'/user/lib.php');
4193 // Make sure nobody sends bogus record type as parameter.
4194 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4195 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4198 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4199 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4200 debugging('Attempt to delete unknown user account.');
4201 return false;
4204 // There must be always exactly one guest record, originally the guest account was identified by username only,
4205 // now we use $CFG->siteguest for performance reasons.
4206 if ($user->username === 'guest' or isguestuser($user)) {
4207 debugging('Guest user account can not be deleted.');
4208 return false;
4211 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4212 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4213 if ($user->auth === 'manual' and is_siteadmin($user)) {
4214 debugging('Local administrator accounts can not be deleted.');
4215 return false;
4218 // Allow plugins to use this user object before we completely delete it.
4219 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4220 foreach ($pluginsfunction as $plugintype => $plugins) {
4221 foreach ($plugins as $pluginfunction) {
4222 $pluginfunction($user);
4227 // Keep user record before updating it, as we have to pass this to user_deleted event.
4228 $olduser = clone $user;
4230 // Keep a copy of user context, we need it for event.
4231 $usercontext = context_user::instance($user->id);
4233 // Delete all grades - backup is kept in grade_grades_history table.
4234 grade_user_delete($user->id);
4236 // TODO: remove from cohorts using standard API here.
4238 // Remove user tags.
4239 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4241 // Unconditionally unenrol from all courses.
4242 enrol_user_delete($user);
4244 // Unenrol from all roles in all contexts.
4245 // This might be slow but it is really needed - modules might do some extra cleanup!
4246 role_unassign_all(array('userid' => $user->id));
4248 // Now do a brute force cleanup.
4250 // Remove user's calendar subscriptions.
4251 $DB->delete_records('event_subscriptions', ['userid' => $user->id]);
4253 // Remove from all cohorts.
4254 $DB->delete_records('cohort_members', array('userid' => $user->id));
4256 // Remove from all groups.
4257 $DB->delete_records('groups_members', array('userid' => $user->id));
4259 // Brute force unenrol from all courses.
4260 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4262 // Purge user preferences.
4263 $DB->delete_records('user_preferences', array('userid' => $user->id));
4265 // Purge user extra profile info.
4266 $DB->delete_records('user_info_data', array('userid' => $user->id));
4268 // Purge log of previous password hashes.
4269 $DB->delete_records('user_password_history', array('userid' => $user->id));
4271 // Last course access not necessary either.
4272 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4273 // Remove all user tokens.
4274 $DB->delete_records('external_tokens', array('userid' => $user->id));
4276 // Unauthorise the user for all services.
4277 $DB->delete_records('external_services_users', array('userid' => $user->id));
4279 // Remove users private keys.
4280 $DB->delete_records('user_private_key', array('userid' => $user->id));
4282 // Remove users customised pages.
4283 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4285 // Delete user from $SESSION->bulk_users.
4286 if (isset($SESSION->bulk_users[$user->id])) {
4287 unset($SESSION->bulk_users[$user->id]);
4290 // Force logout - may fail if file based sessions used, sorry.
4291 \core\session\manager::kill_user_sessions($user->id);
4293 // Generate username from email address, or a fake email.
4294 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4295 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
4297 // Workaround for bulk deletes of users with the same email address.
4298 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4299 $delname++;
4302 // Mark internal user record as "deleted".
4303 $updateuser = new stdClass();
4304 $updateuser->id = $user->id;
4305 $updateuser->deleted = 1;
4306 $updateuser->username = $delname; // Remember it just in case.
4307 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4308 $updateuser->idnumber = ''; // Clear this field to free it up.
4309 $updateuser->picture = 0;
4310 $updateuser->timemodified = time();
4312 // Don't trigger update event, as user is being deleted.
4313 user_update_user($updateuser, false, false);
4315 // Delete all content associated with the user context, but not the context itself.
4316 $usercontext->delete_content();
4318 // Delete any search data.
4319 \core_search\manager::context_deleted($usercontext);
4321 // Any plugin that needs to cleanup should register this event.
4322 // Trigger event.
4323 $event = \core\event\user_deleted::create(
4324 array(
4325 'objectid' => $user->id,
4326 'relateduserid' => $user->id,
4327 'context' => $usercontext,
4328 'other' => array(
4329 'username' => $user->username,
4330 'email' => $user->email,
4331 'idnumber' => $user->idnumber,
4332 'picture' => $user->picture,
4333 'mnethostid' => $user->mnethostid
4337 $event->add_record_snapshot('user', $olduser);
4338 $event->trigger();
4340 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4341 // should know about this updated property persisted to the user's table.
4342 $user->timemodified = $updateuser->timemodified;
4344 // Notify auth plugin - do not block the delete even when plugin fails.
4345 $authplugin = get_auth_plugin($user->auth);
4346 $authplugin->user_delete($user);
4348 return true;
4352 * Retrieve the guest user object.
4354 * @return stdClass A {@link $USER} object
4356 function guest_user() {
4357 global $CFG, $DB;
4359 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4360 $newuser->confirmed = 1;
4361 $newuser->lang = $CFG->lang;
4362 $newuser->lastip = getremoteaddr();
4365 return $newuser;
4369 * Authenticates a user against the chosen authentication mechanism
4371 * Given a username and password, this function looks them
4372 * up using the currently selected authentication mechanism,
4373 * and if the authentication is successful, it returns a
4374 * valid $user object from the 'user' table.
4376 * Uses auth_ functions from the currently active auth module
4378 * After authenticate_user_login() returns success, you will need to
4379 * log that the user has logged in, and call complete_user_login() to set
4380 * the session up.
4382 * Note: this function works only with non-mnet accounts!
4384 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4385 * @param string $password User's password
4386 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4387 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4388 * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4389 * @return stdClass|false A {@link $USER} object or false if error
4391 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4392 global $CFG, $DB;
4393 require_once("$CFG->libdir/authlib.php");
4395 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4396 // we have found the user
4398 } else if (!empty($CFG->authloginviaemail)) {
4399 if ($email = clean_param($username, PARAM_EMAIL)) {
4400 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4401 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4402 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4403 if (count($users) === 1) {
4404 // Use email for login only if unique.
4405 $user = reset($users);
4406 $user = get_complete_user_data('id', $user->id);
4407 $username = $user->username;
4409 unset($users);
4413 // Make sure this request came from the login form.
4414 if (!\core\session\manager::validate_login_token($logintoken)) {
4415 $failurereason = AUTH_LOGIN_FAILED;
4417 // Trigger login failed event.
4418 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4419 'other' => array('username' => $username, 'reason' => $failurereason)));
4420 $event->trigger();
4421 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4422 return false;
4425 $authsenabled = get_enabled_auth_plugins();
4427 if ($user) {
4428 // Use manual if auth not set.
4429 $auth = empty($user->auth) ? 'manual' : $user->auth;
4431 if (in_array($user->auth, $authsenabled)) {
4432 $authplugin = get_auth_plugin($user->auth);
4433 $authplugin->pre_user_login_hook($user);
4436 if (!empty($user->suspended)) {
4437 $failurereason = AUTH_LOGIN_SUSPENDED;
4439 // Trigger login failed event.
4440 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4441 'other' => array('username' => $username, 'reason' => $failurereason)));
4442 $event->trigger();
4443 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4444 return false;
4446 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4447 // Legacy way to suspend user.
4448 $failurereason = AUTH_LOGIN_SUSPENDED;
4450 // Trigger login failed event.
4451 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4452 'other' => array('username' => $username, 'reason' => $failurereason)));
4453 $event->trigger();
4454 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4455 return false;
4457 $auths = array($auth);
4459 } else {
4460 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4461 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4462 $failurereason = AUTH_LOGIN_NOUSER;
4464 // Trigger login failed event.
4465 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4466 'reason' => $failurereason)));
4467 $event->trigger();
4468 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4469 return false;
4472 // User does not exist.
4473 $auths = $authsenabled;
4474 $user = new stdClass();
4475 $user->id = 0;
4478 if ($ignorelockout) {
4479 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4480 // or this function is called from a SSO script.
4481 } else if ($user->id) {
4482 // Verify login lockout after other ways that may prevent user login.
4483 if (login_is_lockedout($user)) {
4484 $failurereason = AUTH_LOGIN_LOCKOUT;
4486 // Trigger login failed event.
4487 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4488 'other' => array('username' => $username, 'reason' => $failurereason)));
4489 $event->trigger();
4491 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4492 return false;
4494 } else {
4495 // We can not lockout non-existing accounts.
4498 foreach ($auths as $auth) {
4499 $authplugin = get_auth_plugin($auth);
4501 // On auth fail fall through to the next plugin.
4502 if (!$authplugin->user_login($username, $password)) {
4503 continue;
4506 // Successful authentication.
4507 if ($user->id) {
4508 // User already exists in database.
4509 if (empty($user->auth)) {
4510 // For some reason auth isn't set yet.
4511 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4512 $user->auth = $auth;
4515 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4516 // the current hash algorithm while we have access to the user's password.
4517 update_internal_user_password($user, $password);
4519 if ($authplugin->is_synchronised_with_external()) {
4520 // Update user record from external DB.
4521 $user = update_user_record_by_id($user->id);
4523 } else {
4524 // The user is authenticated but user creation may be disabled.
4525 if (!empty($CFG->authpreventaccountcreation)) {
4526 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4528 // Trigger login failed event.
4529 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4530 'reason' => $failurereason)));
4531 $event->trigger();
4533 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4534 $_SERVER['HTTP_USER_AGENT']);
4535 return false;
4536 } else {
4537 $user = create_user_record($username, $password, $auth);
4541 $authplugin->sync_roles($user);
4543 foreach ($authsenabled as $hau) {
4544 $hauth = get_auth_plugin($hau);
4545 $hauth->user_authenticated_hook($user, $username, $password);
4548 if (empty($user->id)) {
4549 $failurereason = AUTH_LOGIN_NOUSER;
4550 // Trigger login failed event.
4551 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4552 'reason' => $failurereason)));
4553 $event->trigger();
4554 return false;
4557 if (!empty($user->suspended)) {
4558 // Just in case some auth plugin suspended account.
4559 $failurereason = AUTH_LOGIN_SUSPENDED;
4560 // Trigger login failed event.
4561 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4562 'other' => array('username' => $username, 'reason' => $failurereason)));
4563 $event->trigger();
4564 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4565 return false;
4568 login_attempt_valid($user);
4569 $failurereason = AUTH_LOGIN_OK;
4570 return $user;
4573 // Failed if all the plugins have failed.
4574 if (debugging('', DEBUG_ALL)) {
4575 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4578 if ($user->id) {
4579 login_attempt_failed($user);
4580 $failurereason = AUTH_LOGIN_FAILED;
4581 // Trigger login failed event.
4582 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4583 'other' => array('username' => $username, 'reason' => $failurereason)));
4584 $event->trigger();
4585 } else {
4586 $failurereason = AUTH_LOGIN_NOUSER;
4587 // Trigger login failed event.
4588 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4589 'reason' => $failurereason)));
4590 $event->trigger();
4593 return false;
4597 * Call to complete the user login process after authenticate_user_login()
4598 * has succeeded. It will setup the $USER variable and other required bits
4599 * and pieces.
4601 * NOTE:
4602 * - It will NOT log anything -- up to the caller to decide what to log.
4603 * - this function does not set any cookies any more!
4605 * @param stdClass $user
4606 * @return stdClass A {@link $USER} object - BC only, do not use
4608 function complete_user_login($user) {
4609 global $CFG, $DB, $USER, $SESSION;
4611 \core\session\manager::login_user($user);
4613 // Reload preferences from DB.
4614 unset($USER->preference);
4615 check_user_preferences_loaded($USER);
4617 // Update login times.
4618 update_user_login_times();
4620 // Extra session prefs init.
4621 set_login_session_preferences();
4623 // Trigger login event.
4624 $event = \core\event\user_loggedin::create(
4625 array(
4626 'userid' => $USER->id,
4627 'objectid' => $USER->id,
4628 'other' => array('username' => $USER->username),
4631 $event->trigger();
4633 // Queue migrating the messaging data, if we need to.
4634 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4635 // Check if there are any legacy messages to migrate.
4636 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4637 \core_message\task\migrate_message_data::queue_task($USER->id);
4638 } else {
4639 set_user_preference('core_message_migrate_data', true, $USER->id);
4643 if (isguestuser()) {
4644 // No need to continue when user is THE guest.
4645 return $USER;
4648 if (CLI_SCRIPT) {
4649 // We can redirect to password change URL only in browser.
4650 return $USER;
4653 // Select password change url.
4654 $userauth = get_auth_plugin($USER->auth);
4656 // Check whether the user should be changing password.
4657 if (get_user_preferences('auth_forcepasswordchange', false)) {
4658 if ($userauth->can_change_password()) {
4659 if ($changeurl = $userauth->change_password_url()) {
4660 redirect($changeurl);
4661 } else {
4662 require_once($CFG->dirroot . '/login/lib.php');
4663 $SESSION->wantsurl = core_login_get_return_url();
4664 redirect($CFG->wwwroot.'/login/change_password.php');
4666 } else {
4667 print_error('nopasswordchangeforced', 'auth');
4670 return $USER;
4674 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4676 * @param string $password String to check.
4677 * @return boolean True if the $password matches the format of an md5 sum.
4679 function password_is_legacy_hash($password) {
4680 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4684 * Compare password against hash stored in user object to determine if it is valid.
4686 * If necessary it also updates the stored hash to the current format.
4688 * @param stdClass $user (Password property may be updated).
4689 * @param string $password Plain text password.
4690 * @return bool True if password is valid.
4692 function validate_internal_user_password($user, $password) {
4693 global $CFG;
4695 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4696 // Internal password is not used at all, it can not validate.
4697 return false;
4700 // If hash isn't a legacy (md5) hash, validate using the library function.
4701 if (!password_is_legacy_hash($user->password)) {
4702 return password_verify($password, $user->password);
4705 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4706 // is valid we can then update it to the new algorithm.
4708 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4709 $validated = false;
4711 if ($user->password === md5($password.$sitesalt)
4712 or $user->password === md5($password)
4713 or $user->password === md5(addslashes($password).$sitesalt)
4714 or $user->password === md5(addslashes($password))) {
4715 // Note: we are intentionally using the addslashes() here because we
4716 // need to accept old password hashes of passwords with magic quotes.
4717 $validated = true;
4719 } else {
4720 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4721 $alt = 'passwordsaltalt'.$i;
4722 if (!empty($CFG->$alt)) {
4723 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4724 $validated = true;
4725 break;
4731 if ($validated) {
4732 // If the password matches the existing md5 hash, update to the
4733 // current hash algorithm while we have access to the user's password.
4734 update_internal_user_password($user, $password);
4737 return $validated;
4741 * Calculate hash for a plain text password.
4743 * @param string $password Plain text password to be hashed.
4744 * @param bool $fasthash If true, use a low cost factor when generating the hash
4745 * This is much faster to generate but makes the hash
4746 * less secure. It is used when lots of hashes need to
4747 * be generated quickly.
4748 * @return string The hashed password.
4750 * @throws moodle_exception If a problem occurs while generating the hash.
4752 function hash_internal_user_password($password, $fasthash = false) {
4753 global $CFG;
4755 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4756 $options = ($fasthash) ? array('cost' => 4) : array();
4758 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4760 if ($generatedhash === false || $generatedhash === null) {
4761 throw new moodle_exception('Failed to generate password hash.');
4764 return $generatedhash;
4768 * Update password hash in user object (if necessary).
4770 * The password is updated if:
4771 * 1. The password has changed (the hash of $user->password is different
4772 * to the hash of $password).
4773 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4774 * md5 algorithm).
4776 * Updating the password will modify the $user object and the database
4777 * record to use the current hashing algorithm.
4778 * It will remove Web Services user tokens too.
4780 * @param stdClass $user User object (password property may be updated).
4781 * @param string $password Plain text password.
4782 * @param bool $fasthash If true, use a low cost factor when generating the hash
4783 * This is much faster to generate but makes the hash
4784 * less secure. It is used when lots of hashes need to
4785 * be generated quickly.
4786 * @return bool Always returns true.
4788 function update_internal_user_password($user, $password, $fasthash = false) {
4789 global $CFG, $DB;
4791 // Figure out what the hashed password should be.
4792 if (!isset($user->auth)) {
4793 debugging('User record in update_internal_user_password() must include field auth',
4794 DEBUG_DEVELOPER);
4795 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4797 $authplugin = get_auth_plugin($user->auth);
4798 if ($authplugin->prevent_local_passwords()) {
4799 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4800 } else {
4801 $hashedpassword = hash_internal_user_password($password, $fasthash);
4804 $algorithmchanged = false;
4806 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4807 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4808 $passwordchanged = ($user->password !== $hashedpassword);
4810 } else if (isset($user->password)) {
4811 // If verification fails then it means the password has changed.
4812 $passwordchanged = !password_verify($password, $user->password);
4813 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4814 } else {
4815 // While creating new user, password in unset in $user object, to avoid
4816 // saving it with user_create()
4817 $passwordchanged = true;
4820 if ($passwordchanged || $algorithmchanged) {
4821 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4822 $user->password = $hashedpassword;
4824 // Trigger event.
4825 $user = $DB->get_record('user', array('id' => $user->id));
4826 \core\event\user_password_updated::create_from_user($user)->trigger();
4828 // Remove WS user tokens.
4829 if (!empty($CFG->passwordchangetokendeletion)) {
4830 require_once($CFG->dirroot.'/webservice/lib.php');
4831 webservice::delete_user_ws_tokens($user->id);
4835 return true;
4839 * Get a complete user record, which includes all the info in the user record.
4841 * Intended for setting as $USER session variable
4843 * @param string $field The user field to be checked for a given value.
4844 * @param string $value The value to match for $field.
4845 * @param int $mnethostid
4846 * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4847 * found. Otherwise, it will just return false.
4848 * @return mixed False, or A {@link $USER} object.
4850 function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4851 global $CFG, $DB;
4853 if (!$field || !$value) {
4854 return false;
4857 // Change the field to lowercase.
4858 $field = core_text::strtolower($field);
4860 // List of case insensitive fields.
4861 $caseinsensitivefields = ['email'];
4863 // Username input is forced to lowercase and should be case sensitive.
4864 if ($field == 'username') {
4865 $value = core_text::strtolower($value);
4868 // Build the WHERE clause for an SQL query.
4869 $params = array('fieldval' => $value);
4871 // Do a case-insensitive query, if necessary.
4872 if (in_array($field, $caseinsensitivefields)) {
4873 $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4874 } else {
4875 $fieldselect = "$field = :fieldval";
4877 $constraints = "$fieldselect AND deleted <> 1";
4879 // If we are loading user data based on anything other than id,
4880 // we must also restrict our search based on mnet host.
4881 if ($field != 'id') {
4882 if (empty($mnethostid)) {
4883 // If empty, we restrict to local users.
4884 $mnethostid = $CFG->mnet_localhost_id;
4887 if (!empty($mnethostid)) {
4888 $params['mnethostid'] = $mnethostid;
4889 $constraints .= " AND mnethostid = :mnethostid";
4892 // Get all the basic user data.
4893 try {
4894 // Make sure that there's only a single record that matches our query.
4895 // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4896 // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4897 $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST);
4898 } catch (dml_exception $exception) {
4899 if ($throwexception) {
4900 throw $exception;
4901 } else {
4902 // Return false when no records or multiple records were found.
4903 return false;
4907 // Get various settings and preferences.
4909 // Preload preference cache.
4910 check_user_preferences_loaded($user);
4912 // Load course enrolment related stuff.
4913 $user->lastcourseaccess = array(); // During last session.
4914 $user->currentcourseaccess = array(); // During current session.
4915 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4916 foreach ($lastaccesses as $lastaccess) {
4917 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4921 $sql = "SELECT g.id, g.courseid
4922 FROM {groups} g, {groups_members} gm
4923 WHERE gm.groupid=g.id AND gm.userid=?";
4925 // This is a special hack to speedup calendar display.
4926 $user->groupmember = array();
4927 if (!isguestuser($user)) {
4928 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4929 foreach ($groups as $group) {
4930 if (!array_key_exists($group->courseid, $user->groupmember)) {
4931 $user->groupmember[$group->courseid] = array();
4933 $user->groupmember[$group->courseid][$group->id] = $group->id;
4938 // Add cohort theme.
4939 if (!empty($CFG->allowcohortthemes)) {
4940 require_once($CFG->dirroot . '/cohort/lib.php');
4941 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4942 $user->cohorttheme = $cohorttheme;
4946 // Add the custom profile fields to the user record.
4947 $user->profile = array();
4948 if (!isguestuser($user)) {
4949 require_once($CFG->dirroot.'/user/profile/lib.php');
4950 profile_load_custom_fields($user);
4953 // Rewrite some variables if necessary.
4954 if (!empty($user->description)) {
4955 // No need to cart all of it around.
4956 $user->description = true;
4958 if (isguestuser($user)) {
4959 // Guest language always same as site.
4960 $user->lang = $CFG->lang;
4961 // Name always in current language.
4962 $user->firstname = get_string('guestuser');
4963 $user->lastname = ' ';
4966 return $user;
4970 * Validate a password against the configured password policy
4972 * @param string $password the password to be checked against the password policy
4973 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4974 * @param stdClass $user the user object to perform password validation against. Defaults to null if not provided
4975 * @return bool true if the password is valid according to the policy. false otherwise.
4977 function check_password_policy($password, &$errmsg, $user = null) {
4978 global $CFG;
4980 if (!empty($CFG->passwordpolicy)) {
4981 $errmsg = '';
4982 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4983 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4985 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4986 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4988 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4989 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4991 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4992 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4994 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4995 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4997 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4998 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
5002 // Fire any additional password policy functions from plugins.
5003 // Plugin functions should output an error message string or empty string for success.
5004 $pluginsfunction = get_plugins_with_function('check_password_policy');
5005 foreach ($pluginsfunction as $plugintype => $plugins) {
5006 foreach ($plugins as $pluginfunction) {
5007 $pluginerr = $pluginfunction($password, $user);
5008 if ($pluginerr) {
5009 $errmsg .= '<div>'. $pluginerr .'</div>';
5014 if ($errmsg == '') {
5015 return true;
5016 } else {
5017 return false;
5023 * When logging in, this function is run to set certain preferences for the current SESSION.
5025 function set_login_session_preferences() {
5026 global $SESSION;
5028 $SESSION->justloggedin = true;
5030 unset($SESSION->lang);
5031 unset($SESSION->forcelang);
5032 unset($SESSION->load_navigation_admin);
5037 * Delete a course, including all related data from the database, and any associated files.
5039 * @param mixed $courseorid The id of the course or course object to delete.
5040 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5041 * @return bool true if all the removals succeeded. false if there were any failures. If this
5042 * method returns false, some of the removals will probably have succeeded, and others
5043 * failed, but you have no way of knowing which.
5045 function delete_course($courseorid, $showfeedback = true) {
5046 global $DB;
5048 if (is_object($courseorid)) {
5049 $courseid = $courseorid->id;
5050 $course = $courseorid;
5051 } else {
5052 $courseid = $courseorid;
5053 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
5054 return false;
5057 $context = context_course::instance($courseid);
5059 // Frontpage course can not be deleted!!
5060 if ($courseid == SITEID) {
5061 return false;
5064 // Allow plugins to use this course before we completely delete it.
5065 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
5066 foreach ($pluginsfunction as $plugintype => $plugins) {
5067 foreach ($plugins as $pluginfunction) {
5068 $pluginfunction($course);
5073 // Tell the search manager we are about to delete a course. This prevents us sending updates
5074 // for each individual context being deleted.
5075 \core_search\manager::course_deleting_start($courseid);
5077 $handler = core_course\customfield\course_handler::create();
5078 $handler->delete_instance($courseid);
5080 // Make the course completely empty.
5081 remove_course_contents($courseid, $showfeedback);
5083 // Delete the course and related context instance.
5084 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
5086 $DB->delete_records("course", array("id" => $courseid));
5087 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5089 // Reset all course related caches here.
5090 if (class_exists('format_base', false)) {
5091 format_base::reset_course_cache($courseid);
5094 // Tell search that we have deleted the course so it can delete course data from the index.
5095 \core_search\manager::course_deleting_finish($courseid);
5097 // Trigger a course deleted event.
5098 $event = \core\event\course_deleted::create(array(
5099 'objectid' => $course->id,
5100 'context' => $context,
5101 'other' => array(
5102 'shortname' => $course->shortname,
5103 'fullname' => $course->fullname,
5104 'idnumber' => $course->idnumber
5107 $event->add_record_snapshot('course', $course);
5108 $event->trigger();
5110 return true;
5114 * Clear a course out completely, deleting all content but don't delete the course itself.
5116 * This function does not verify any permissions.
5118 * Please note this function also deletes all user enrolments,
5119 * enrolment instances and role assignments by default.
5121 * $options:
5122 * - 'keep_roles_and_enrolments' - false by default
5123 * - 'keep_groups_and_groupings' - false by default
5125 * @param int $courseid The id of the course that is being deleted
5126 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5127 * @param array $options extra options
5128 * @return bool true if all the removals succeeded. false if there were any failures. If this
5129 * method returns false, some of the removals will probably have succeeded, and others
5130 * failed, but you have no way of knowing which.
5132 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5133 global $CFG, $DB, $OUTPUT;
5135 require_once($CFG->libdir.'/badgeslib.php');
5136 require_once($CFG->libdir.'/completionlib.php');
5137 require_once($CFG->libdir.'/questionlib.php');
5138 require_once($CFG->libdir.'/gradelib.php');
5139 require_once($CFG->dirroot.'/group/lib.php');
5140 require_once($CFG->dirroot.'/comment/lib.php');
5141 require_once($CFG->dirroot.'/rating/lib.php');
5142 require_once($CFG->dirroot.'/notes/lib.php');
5144 // Handle course badges.
5145 badges_handle_course_deletion($courseid);
5147 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5148 $strdeleted = get_string('deleted').' - ';
5150 // Some crazy wishlist of stuff we should skip during purging of course content.
5151 $options = (array)$options;
5153 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5154 $coursecontext = context_course::instance($courseid);
5155 $fs = get_file_storage();
5157 // Delete course completion information, this has to be done before grades and enrols.
5158 $cc = new completion_info($course);
5159 $cc->clear_criteria();
5160 if ($showfeedback) {
5161 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5164 // Remove all data from gradebook - this needs to be done before course modules
5165 // because while deleting this information, the system may need to reference
5166 // the course modules that own the grades.
5167 remove_course_grades($courseid, $showfeedback);
5168 remove_grade_letters($coursecontext, $showfeedback);
5170 // Delete course blocks in any all child contexts,
5171 // they may depend on modules so delete them first.
5172 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5173 foreach ($childcontexts as $childcontext) {
5174 blocks_delete_all_for_context($childcontext->id);
5176 unset($childcontexts);
5177 blocks_delete_all_for_context($coursecontext->id);
5178 if ($showfeedback) {
5179 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5182 // Get the list of all modules that are properly installed.
5183 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5185 // Delete every instance of every module,
5186 // this has to be done before deleting of course level stuff.
5187 $locations = core_component::get_plugin_list('mod');
5188 foreach ($locations as $modname => $moddir) {
5189 if ($modname === 'NEWMODULE') {
5190 continue;
5192 if (array_key_exists($modname, $allmodules)) {
5193 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5194 FROM {".$modname."} m
5195 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5196 WHERE m.course = :courseid";
5197 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5198 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5200 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5201 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5203 if ($instances) {
5204 foreach ($instances as $cm) {
5205 if ($cm->id) {
5206 // Delete activity context questions and question categories.
5207 question_delete_activity($cm, $showfeedback);
5208 // Notify the competency subsystem.
5209 \core_competency\api::hook_course_module_deleted($cm);
5211 if (function_exists($moddelete)) {
5212 // This purges all module data in related tables, extra user prefs, settings, etc.
5213 $moddelete($cm->modinstance);
5214 } else {
5215 // NOTE: we should not allow installation of modules with missing delete support!
5216 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5217 $DB->delete_records($modname, array('id' => $cm->modinstance));
5220 if ($cm->id) {
5221 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5222 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5223 $DB->delete_records('course_modules', array('id' => $cm->id));
5227 if ($instances and $showfeedback) {
5228 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5230 } else {
5231 // Ooops, this module is not properly installed, force-delete it in the next block.
5235 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5237 // Delete completion defaults.
5238 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5240 // Remove all data from availability and completion tables that is associated
5241 // with course-modules belonging to this course. Note this is done even if the
5242 // features are not enabled now, in case they were enabled previously.
5243 $DB->delete_records_select('course_modules_completion',
5244 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5245 array($courseid));
5247 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5248 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5249 $allmodulesbyid = array_flip($allmodules);
5250 foreach ($cms as $cm) {
5251 if (array_key_exists($cm->module, $allmodulesbyid)) {
5252 try {
5253 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5254 } catch (Exception $e) {
5255 // Ignore weird or missing table problems.
5258 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5259 $DB->delete_records('course_modules', array('id' => $cm->id));
5262 if ($showfeedback) {
5263 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5266 // Delete questions and question categories.
5267 question_delete_course($course, $showfeedback);
5268 if ($showfeedback) {
5269 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5272 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5273 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5274 foreach ($childcontexts as $childcontext) {
5275 $childcontext->delete();
5277 unset($childcontexts);
5279 // Remove all roles and enrolments by default.
5280 if (empty($options['keep_roles_and_enrolments'])) {
5281 // This hack is used in restore when deleting contents of existing course.
5282 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5283 enrol_course_delete($course);
5284 if ($showfeedback) {
5285 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5289 // Delete any groups, removing members and grouping/course links first.
5290 if (empty($options['keep_groups_and_groupings'])) {
5291 groups_delete_groupings($course->id, $showfeedback);
5292 groups_delete_groups($course->id, $showfeedback);
5295 // Filters be gone!
5296 filter_delete_all_for_context($coursecontext->id);
5298 // Notes, you shall not pass!
5299 note_delete_all($course->id);
5301 // Die comments!
5302 comment::delete_comments($coursecontext->id);
5304 // Ratings are history too.
5305 $delopt = new stdclass();
5306 $delopt->contextid = $coursecontext->id;
5307 $rm = new rating_manager();
5308 $rm->delete_ratings($delopt);
5310 // Delete course tags.
5311 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5313 // Notify the competency subsystem.
5314 \core_competency\api::hook_course_deleted($course);
5316 // Delete calendar events.
5317 $DB->delete_records('event', array('courseid' => $course->id));
5318 $fs->delete_area_files($coursecontext->id, 'calendar');
5320 // Delete all related records in other core tables that may have a courseid
5321 // This array stores the tables that need to be cleared, as
5322 // table_name => column_name that contains the course id.
5323 $tablestoclear = array(
5324 'backup_courses' => 'courseid', // Scheduled backup stuff.
5325 'user_lastaccess' => 'courseid', // User access info.
5327 foreach ($tablestoclear as $table => $col) {
5328 $DB->delete_records($table, array($col => $course->id));
5331 // Delete all course backup files.
5332 $fs->delete_area_files($coursecontext->id, 'backup');
5334 // Cleanup course record - remove links to deleted stuff.
5335 $oldcourse = new stdClass();
5336 $oldcourse->id = $course->id;
5337 $oldcourse->summary = '';
5338 $oldcourse->cacherev = 0;
5339 $oldcourse->legacyfiles = 0;
5340 if (!empty($options['keep_groups_and_groupings'])) {
5341 $oldcourse->defaultgroupingid = 0;
5343 $DB->update_record('course', $oldcourse);
5345 // Delete course sections.
5346 $DB->delete_records('course_sections', array('course' => $course->id));
5348 // Delete legacy, section and any other course files.
5349 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5351 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5352 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5353 // Easy, do not delete the context itself...
5354 $coursecontext->delete_content();
5355 } else {
5356 // Hack alert!!!!
5357 // We can not drop all context stuff because it would bork enrolments and roles,
5358 // there might be also files used by enrol plugins...
5361 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5362 // also some non-standard unsupported plugins may try to store something there.
5363 fulldelete($CFG->dataroot.'/'.$course->id);
5365 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5366 $cachemodinfo = cache::make('core', 'coursemodinfo');
5367 $cachemodinfo->delete($courseid);
5369 // Trigger a course content deleted event.
5370 $event = \core\event\course_content_deleted::create(array(
5371 'objectid' => $course->id,
5372 'context' => $coursecontext,
5373 'other' => array('shortname' => $course->shortname,
5374 'fullname' => $course->fullname,
5375 'options' => $options) // Passing this for legacy reasons.
5377 $event->add_record_snapshot('course', $course);
5378 $event->trigger();
5380 return true;
5384 * Change dates in module - used from course reset.
5386 * @param string $modname forum, assignment, etc
5387 * @param array $fields array of date fields from mod table
5388 * @param int $timeshift time difference
5389 * @param int $courseid
5390 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5391 * @return bool success
5393 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5394 global $CFG, $DB;
5395 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5397 $return = true;
5398 $params = array($timeshift, $courseid);
5399 foreach ($fields as $field) {
5400 $updatesql = "UPDATE {".$modname."}
5401 SET $field = $field + ?
5402 WHERE course=? AND $field<>0";
5403 if ($modid) {
5404 $updatesql .= ' AND id=?';
5405 $params[] = $modid;
5407 $return = $DB->execute($updatesql, $params) && $return;
5410 return $return;
5414 * This function will empty a course of user data.
5415 * It will retain the activities and the structure of the course.
5417 * @param object $data an object containing all the settings including courseid (without magic quotes)
5418 * @return array status array of array component, item, error
5420 function reset_course_userdata($data) {
5421 global $CFG, $DB;
5422 require_once($CFG->libdir.'/gradelib.php');
5423 require_once($CFG->libdir.'/completionlib.php');
5424 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5425 require_once($CFG->dirroot.'/group/lib.php');
5427 $data->courseid = $data->id;
5428 $context = context_course::instance($data->courseid);
5430 $eventparams = array(
5431 'context' => $context,
5432 'courseid' => $data->id,
5433 'other' => array(
5434 'reset_options' => (array) $data
5437 $event = \core\event\course_reset_started::create($eventparams);
5438 $event->trigger();
5440 // Calculate the time shift of dates.
5441 if (!empty($data->reset_start_date)) {
5442 // Time part of course startdate should be zero.
5443 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5444 } else {
5445 $data->timeshift = 0;
5448 // Result array: component, item, error.
5449 $status = array();
5451 // Start the resetting.
5452 $componentstr = get_string('general');
5454 // Move the course start time.
5455 if (!empty($data->reset_start_date) and $data->timeshift) {
5456 // Change course start data.
5457 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5458 // Update all course and group events - do not move activity events.
5459 $updatesql = "UPDATE {event}
5460 SET timestart = timestart + ?
5461 WHERE courseid=? AND instance=0";
5462 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5464 // Update any date activity restrictions.
5465 if ($CFG->enableavailability) {
5466 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5469 // Update completion expected dates.
5470 if ($CFG->enablecompletion) {
5471 $modinfo = get_fast_modinfo($data->courseid);
5472 $changed = false;
5473 foreach ($modinfo->get_cms() as $cm) {
5474 if ($cm->completion && !empty($cm->completionexpected)) {
5475 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5476 array('id' => $cm->id));
5477 $changed = true;
5481 // Clear course cache if changes made.
5482 if ($changed) {
5483 rebuild_course_cache($data->courseid, true);
5486 // Update course date completion criteria.
5487 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5490 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5493 if (!empty($data->reset_end_date)) {
5494 // If the user set a end date value respect it.
5495 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5496 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5497 // If there is a time shift apply it to the end date as well.
5498 $enddate = $data->reset_end_date_old + $data->timeshift;
5499 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5502 if (!empty($data->reset_events)) {
5503 $DB->delete_records('event', array('courseid' => $data->courseid));
5504 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5507 if (!empty($data->reset_notes)) {
5508 require_once($CFG->dirroot.'/notes/lib.php');
5509 note_delete_all($data->courseid);
5510 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5513 if (!empty($data->delete_blog_associations)) {
5514 require_once($CFG->dirroot.'/blog/lib.php');
5515 blog_remove_associations_for_course($data->courseid);
5516 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5519 if (!empty($data->reset_completion)) {
5520 // Delete course and activity completion information.
5521 $course = $DB->get_record('course', array('id' => $data->courseid));
5522 $cc = new completion_info($course);
5523 $cc->delete_all_completion_data();
5524 $status[] = array('component' => $componentstr,
5525 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5528 if (!empty($data->reset_competency_ratings)) {
5529 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5530 $status[] = array('component' => $componentstr,
5531 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5534 $componentstr = get_string('roles');
5536 if (!empty($data->reset_roles_overrides)) {
5537 $children = $context->get_child_contexts();
5538 foreach ($children as $child) {
5539 $child->delete_capabilities();
5541 $context->delete_capabilities();
5542 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5545 if (!empty($data->reset_roles_local)) {
5546 $children = $context->get_child_contexts();
5547 foreach ($children as $child) {
5548 role_unassign_all(array('contextid' => $child->id));
5550 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5553 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5554 $data->unenrolled = array();
5555 if (!empty($data->unenrol_users)) {
5556 $plugins = enrol_get_plugins(true);
5557 $instances = enrol_get_instances($data->courseid, true);
5558 foreach ($instances as $key => $instance) {
5559 if (!isset($plugins[$instance->enrol])) {
5560 unset($instances[$key]);
5561 continue;
5565 $usersroles = enrol_get_course_users_roles($data->courseid);
5566 foreach ($data->unenrol_users as $withroleid) {
5567 if ($withroleid) {
5568 $sql = "SELECT ue.*
5569 FROM {user_enrolments} ue
5570 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5571 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5572 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5573 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5575 } else {
5576 // Without any role assigned at course context.
5577 $sql = "SELECT ue.*
5578 FROM {user_enrolments} ue
5579 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5580 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5581 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5582 WHERE ra.id IS null";
5583 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5586 $rs = $DB->get_recordset_sql($sql, $params);
5587 foreach ($rs as $ue) {
5588 if (!isset($instances[$ue->enrolid])) {
5589 continue;
5591 $instance = $instances[$ue->enrolid];
5592 $plugin = $plugins[$instance->enrol];
5593 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5594 continue;
5597 if ($withroleid && count($usersroles[$ue->userid]) > 1) {
5598 // If we don't remove all roles and user has more than one role, just remove this role.
5599 role_unassign($withroleid, $ue->userid, $context->id);
5601 unset($usersroles[$ue->userid][$withroleid]);
5602 } else {
5603 // If we remove all roles or user has only one role, unenrol user from course.
5604 $plugin->unenrol_user($instance, $ue->userid);
5606 $data->unenrolled[$ue->userid] = $ue->userid;
5608 $rs->close();
5611 if (!empty($data->unenrolled)) {
5612 $status[] = array(
5613 'component' => $componentstr,
5614 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5615 'error' => false
5619 $componentstr = get_string('groups');
5621 // Remove all group members.
5622 if (!empty($data->reset_groups_members)) {
5623 groups_delete_group_members($data->courseid);
5624 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5627 // Remove all groups.
5628 if (!empty($data->reset_groups_remove)) {
5629 groups_delete_groups($data->courseid, false);
5630 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5633 // Remove all grouping members.
5634 if (!empty($data->reset_groupings_members)) {
5635 groups_delete_groupings_groups($data->courseid, false);
5636 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5639 // Remove all groupings.
5640 if (!empty($data->reset_groupings_remove)) {
5641 groups_delete_groupings($data->courseid, false);
5642 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5645 // Look in every instance of every module for data to delete.
5646 $unsupportedmods = array();
5647 if ($allmods = $DB->get_records('modules') ) {
5648 foreach ($allmods as $mod) {
5649 $modname = $mod->name;
5650 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5651 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5652 if (file_exists($modfile)) {
5653 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5654 continue; // Skip mods with no instances.
5656 include_once($modfile);
5657 if (function_exists($moddeleteuserdata)) {
5658 $modstatus = $moddeleteuserdata($data);
5659 if (is_array($modstatus)) {
5660 $status = array_merge($status, $modstatus);
5661 } else {
5662 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5664 } else {
5665 $unsupportedmods[] = $mod;
5667 } else {
5668 debugging('Missing lib.php in '.$modname.' module!');
5670 // Update calendar events for all modules.
5671 course_module_bulk_update_calendar_events($modname, $data->courseid);
5675 // Mention unsupported mods.
5676 if (!empty($unsupportedmods)) {
5677 foreach ($unsupportedmods as $mod) {
5678 $status[] = array(
5679 'component' => get_string('modulenameplural', $mod->name),
5680 'item' => '',
5681 'error' => get_string('resetnotimplemented')
5686 $componentstr = get_string('gradebook', 'grades');
5687 // Reset gradebook,.
5688 if (!empty($data->reset_gradebook_items)) {
5689 remove_course_grades($data->courseid, false);
5690 grade_grab_course_grades($data->courseid);
5691 grade_regrade_final_grades($data->courseid);
5692 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5694 } else if (!empty($data->reset_gradebook_grades)) {
5695 grade_course_reset($data->courseid);
5696 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5698 // Reset comments.
5699 if (!empty($data->reset_comments)) {
5700 require_once($CFG->dirroot.'/comment/lib.php');
5701 comment::reset_course_page_comments($context);
5704 $event = \core\event\course_reset_ended::create($eventparams);
5705 $event->trigger();
5707 return $status;
5711 * Generate an email processing address.
5713 * @param int $modid
5714 * @param string $modargs
5715 * @return string Returns email processing address
5717 function generate_email_processing_address($modid, $modargs) {
5718 global $CFG;
5720 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5721 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5727 * @todo Finish documenting this function
5729 * @param string $modargs
5730 * @param string $body Currently unused
5732 function moodle_process_email($modargs, $body) {
5733 global $DB;
5735 // The first char should be an unencoded letter. We'll take this as an action.
5736 switch ($modargs{0}) {
5737 case 'B': { // Bounce.
5738 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5739 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5740 // Check the half md5 of their email.
5741 $md5check = substr(md5($user->email), 0, 16);
5742 if ($md5check == substr($modargs, -16)) {
5743 set_bounce_count($user);
5745 // Else maybe they've already changed it?
5748 break;
5749 // Maybe more later?
5753 // CORRESPONDENCE.
5756 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5758 * @param string $action 'get', 'buffer', 'close' or 'flush'
5759 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5761 function get_mailer($action='get') {
5762 global $CFG;
5764 /** @var moodle_phpmailer $mailer */
5765 static $mailer = null;
5766 static $counter = 0;
5768 if (!isset($CFG->smtpmaxbulk)) {
5769 $CFG->smtpmaxbulk = 1;
5772 if ($action == 'get') {
5773 $prevkeepalive = false;
5775 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5776 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5777 $counter++;
5778 // Reset the mailer.
5779 $mailer->Priority = 3;
5780 $mailer->CharSet = 'UTF-8'; // Our default.
5781 $mailer->ContentType = "text/plain";
5782 $mailer->Encoding = "8bit";
5783 $mailer->From = "root@localhost";
5784 $mailer->FromName = "Root User";
5785 $mailer->Sender = "";
5786 $mailer->Subject = "";
5787 $mailer->Body = "";
5788 $mailer->AltBody = "";
5789 $mailer->ConfirmReadingTo = "";
5791 $mailer->clearAllRecipients();
5792 $mailer->clearReplyTos();
5793 $mailer->clearAttachments();
5794 $mailer->clearCustomHeaders();
5795 return $mailer;
5798 $prevkeepalive = $mailer->SMTPKeepAlive;
5799 get_mailer('flush');
5802 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5803 $mailer = new moodle_phpmailer();
5805 $counter = 1;
5807 if ($CFG->smtphosts == 'qmail') {
5808 // Use Qmail system.
5809 $mailer->isQmail();
5811 } else if (empty($CFG->smtphosts)) {
5812 // Use PHP mail() = sendmail.
5813 $mailer->isMail();
5815 } else {
5816 // Use SMTP directly.
5817 $mailer->isSMTP();
5818 if (!empty($CFG->debugsmtp) && (!empty($CFG->debugdeveloper))) {
5819 $mailer->SMTPDebug = 3;
5821 // Specify main and backup servers.
5822 $mailer->Host = $CFG->smtphosts;
5823 // Specify secure connection protocol.
5824 $mailer->SMTPSecure = $CFG->smtpsecure;
5825 // Use previous keepalive.
5826 $mailer->SMTPKeepAlive = $prevkeepalive;
5828 if ($CFG->smtpuser) {
5829 // Use SMTP authentication.
5830 $mailer->SMTPAuth = true;
5831 $mailer->Username = $CFG->smtpuser;
5832 $mailer->Password = $CFG->smtppass;
5836 return $mailer;
5839 $nothing = null;
5841 // Keep smtp session open after sending.
5842 if ($action == 'buffer') {
5843 if (!empty($CFG->smtpmaxbulk)) {
5844 get_mailer('flush');
5845 $m = get_mailer();
5846 if ($m->Mailer == 'smtp') {
5847 $m->SMTPKeepAlive = true;
5850 return $nothing;
5853 // Close smtp session, but continue buffering.
5854 if ($action == 'flush') {
5855 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5856 if (!empty($mailer->SMTPDebug)) {
5857 echo '<pre>'."\n";
5859 $mailer->SmtpClose();
5860 if (!empty($mailer->SMTPDebug)) {
5861 echo '</pre>';
5864 return $nothing;
5867 // Close smtp session, do not buffer anymore.
5868 if ($action == 'close') {
5869 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5870 get_mailer('flush');
5871 $mailer->SMTPKeepAlive = false;
5873 $mailer = null; // Better force new instance.
5874 return $nothing;
5879 * A helper function to test for email diversion
5881 * @param string $email
5882 * @return bool Returns true if the email should be diverted
5884 function email_should_be_diverted($email) {
5885 global $CFG;
5887 if (empty($CFG->divertallemailsto)) {
5888 return false;
5891 if (empty($CFG->divertallemailsexcept)) {
5892 return true;
5895 $patterns = array_map('trim', explode(',', $CFG->divertallemailsexcept));
5896 foreach ($patterns as $pattern) {
5897 if (preg_match("/$pattern/", $email)) {
5898 return false;
5902 return true;
5906 * Generate a unique email Message-ID using the moodle domain and install path
5908 * @param string $localpart An optional unique message id prefix.
5909 * @return string The formatted ID ready for appending to the email headers.
5911 function generate_email_messageid($localpart = null) {
5912 global $CFG;
5914 $urlinfo = parse_url($CFG->wwwroot);
5915 $base = '@' . $urlinfo['host'];
5917 // If multiple moodles are on the same domain we want to tell them
5918 // apart so we add the install path to the local part. This means
5919 // that the id local part should never contain a / character so
5920 // we can correctly parse the id to reassemble the wwwroot.
5921 if (isset($urlinfo['path'])) {
5922 $base = $urlinfo['path'] . $base;
5925 if (empty($localpart)) {
5926 $localpart = uniqid('', true);
5929 // Because we may have an option /installpath suffix to the local part
5930 // of the id we need to escape any / chars which are in the $localpart.
5931 $localpart = str_replace('/', '%2F', $localpart);
5933 return '<' . $localpart . $base . '>';
5937 * Send an email to a specified user
5939 * @param stdClass $user A {@link $USER} object
5940 * @param stdClass $from A {@link $USER} object
5941 * @param string $subject plain text subject line of the email
5942 * @param string $messagetext plain text version of the message
5943 * @param string $messagehtml complete html version of the message (optional)
5944 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5945 * @param string $attachname the name of the file (extension indicates MIME)
5946 * @param bool $usetrueaddress determines whether $from email address should
5947 * be sent out. Will be overruled by user profile setting for maildisplay
5948 * @param string $replyto Email address to reply to
5949 * @param string $replytoname Name of reply to recipient
5950 * @param int $wordwrapwidth custom word wrap width, default 79
5951 * @return bool Returns true if mail was sent OK and false if there was an error.
5953 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5954 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5956 global $CFG, $PAGE, $SITE;
5958 if (empty($user) or empty($user->id)) {
5959 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5960 return false;
5963 if (empty($user->email)) {
5964 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5965 return false;
5968 if (!empty($user->deleted)) {
5969 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5970 return false;
5973 if (defined('BEHAT_SITE_RUNNING')) {
5974 // Fake email sending in behat.
5975 return true;
5978 if (!empty($CFG->noemailever)) {
5979 // Hidden setting for development sites, set in config.php if needed.
5980 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5981 return true;
5984 if (email_should_be_diverted($user->email)) {
5985 $subject = "[DIVERTED {$user->email}] $subject";
5986 $user = clone($user);
5987 $user->email = $CFG->divertallemailsto;
5990 // Skip mail to suspended users.
5991 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5992 return true;
5995 if (!validate_email($user->email)) {
5996 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5997 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5998 return false;
6001 if (over_bounce_threshold($user)) {
6002 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
6003 return false;
6006 // TLD .invalid is specifically reserved for invalid domain names.
6007 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
6008 if (substr($user->email, -8) == '.invalid') {
6009 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
6010 return true; // This is not an error.
6013 // If the user is a remote mnet user, parse the email text for URL to the
6014 // wwwroot and modify the url to direct the user's browser to login at their
6015 // home site (identity provider - idp) before hitting the link itself.
6016 if (is_mnet_remote_user($user)) {
6017 require_once($CFG->dirroot.'/mnet/lib.php');
6019 $jumpurl = mnet_get_idp_jump_url($user);
6020 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
6022 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
6023 $callback,
6024 $messagetext);
6025 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
6026 $callback,
6027 $messagehtml);
6029 $mail = get_mailer();
6031 if (!empty($mail->SMTPDebug)) {
6032 echo '<pre>' . "\n";
6035 $temprecipients = array();
6036 $tempreplyto = array();
6038 // Make sure that we fall back onto some reasonable no-reply address.
6039 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
6040 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
6042 if (!validate_email($noreplyaddress)) {
6043 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
6044 $noreplyaddress = $noreplyaddressdefault;
6047 // Make up an email address for handling bounces.
6048 if (!empty($CFG->handlebounces)) {
6049 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
6050 $mail->Sender = generate_email_processing_address(0, $modargs);
6051 } else {
6052 $mail->Sender = $noreplyaddress;
6055 // Make sure that the explicit replyto is valid, fall back to the implicit one.
6056 if (!empty($replyto) && !validate_email($replyto)) {
6057 debugging('email_to_user: Invalid replyto-email '.s($replyto));
6058 $replyto = $noreplyaddress;
6061 if (is_string($from)) { // So we can pass whatever we want if there is need.
6062 $mail->From = $noreplyaddress;
6063 $mail->FromName = $from;
6064 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
6065 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6066 // in a course with the sender.
6067 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
6068 if (!validate_email($from->email)) {
6069 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
6070 // Better not to use $noreplyaddress in this case.
6071 return false;
6073 $mail->From = $from->email;
6074 $fromdetails = new stdClass();
6075 $fromdetails->name = fullname($from);
6076 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6077 $fromdetails->siteshortname = format_string($SITE->shortname);
6078 $fromstring = $fromdetails->name;
6079 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
6080 $fromstring = get_string('emailvia', 'core', $fromdetails);
6082 $mail->FromName = $fromstring;
6083 if (empty($replyto)) {
6084 $tempreplyto[] = array($from->email, fullname($from));
6086 } else {
6087 $mail->From = $noreplyaddress;
6088 $fromdetails = new stdClass();
6089 $fromdetails->name = fullname($from);
6090 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6091 $fromdetails->siteshortname = format_string($SITE->shortname);
6092 $fromstring = $fromdetails->name;
6093 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
6094 $fromstring = get_string('emailvia', 'core', $fromdetails);
6096 $mail->FromName = $fromstring;
6097 if (empty($replyto)) {
6098 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
6102 if (!empty($replyto)) {
6103 $tempreplyto[] = array($replyto, $replytoname);
6106 $temprecipients[] = array($user->email, fullname($user));
6108 // Set word wrap.
6109 $mail->WordWrap = $wordwrapwidth;
6111 if (!empty($from->customheaders)) {
6112 // Add custom headers.
6113 if (is_array($from->customheaders)) {
6114 foreach ($from->customheaders as $customheader) {
6115 $mail->addCustomHeader($customheader);
6117 } else {
6118 $mail->addCustomHeader($from->customheaders);
6122 // If the X-PHP-Originating-Script email header is on then also add an additional
6123 // header with details of where exactly in moodle the email was triggered from,
6124 // either a call to message_send() or to email_to_user().
6125 if (ini_get('mail.add_x_header')) {
6127 $stack = debug_backtrace(false);
6128 $origin = $stack[0];
6130 foreach ($stack as $depth => $call) {
6131 if ($call['function'] == 'message_send') {
6132 $origin = $call;
6136 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
6137 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
6138 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
6141 if (!empty($from->priority)) {
6142 $mail->Priority = $from->priority;
6145 $renderer = $PAGE->get_renderer('core');
6146 $context = array(
6147 'sitefullname' => $SITE->fullname,
6148 'siteshortname' => $SITE->shortname,
6149 'sitewwwroot' => $CFG->wwwroot,
6150 'subject' => $subject,
6151 'prefix' => $CFG->emailsubjectprefix,
6152 'to' => $user->email,
6153 'toname' => fullname($user),
6154 'from' => $mail->From,
6155 'fromname' => $mail->FromName,
6157 if (!empty($tempreplyto[0])) {
6158 $context['replyto'] = $tempreplyto[0][0];
6159 $context['replytoname'] = $tempreplyto[0][1];
6161 if ($user->id > 0) {
6162 $context['touserid'] = $user->id;
6163 $context['tousername'] = $user->username;
6166 if (!empty($user->mailformat) && $user->mailformat == 1) {
6167 // Only process html templates if the user preferences allow html email.
6169 if (!$messagehtml) {
6170 // If no html has been given, BUT there is an html wrapping template then
6171 // auto convert the text to html and then wrap it.
6172 $messagehtml = trim(text_to_html($messagetext));
6174 $context['body'] = $messagehtml;
6175 $messagehtml = $renderer->render_from_template('core/email_html', $context);
6178 $context['body'] = html_to_text(nl2br($messagetext));
6179 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
6180 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
6181 $messagetext = $renderer->render_from_template('core/email_text', $context);
6183 // Autogenerate a MessageID if it's missing.
6184 if (empty($mail->MessageID)) {
6185 $mail->MessageID = generate_email_messageid();
6188 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6189 // Don't ever send HTML to users who don't want it.
6190 $mail->isHTML(true);
6191 $mail->Encoding = 'quoted-printable';
6192 $mail->Body = $messagehtml;
6193 $mail->AltBody = "\n$messagetext\n";
6194 } else {
6195 $mail->IsHTML(false);
6196 $mail->Body = "\n$messagetext\n";
6199 if ($attachment && $attachname) {
6200 if (preg_match( "~\\.\\.~" , $attachment )) {
6201 // Security check for ".." in dir path.
6202 $supportuser = core_user::get_support_user();
6203 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6204 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6205 } else {
6206 require_once($CFG->libdir.'/filelib.php');
6207 $mimetype = mimeinfo('type', $attachname);
6209 $attachmentpath = $attachment;
6211 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6212 $attachpath = str_replace('\\', '/', $attachmentpath);
6213 // Make sure both variables are normalised before comparing.
6214 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
6216 // If the attachment is a full path to a file in the tempdir, use it as is,
6217 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6218 if (strpos($attachpath, $temppath) !== 0) {
6219 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
6222 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
6226 // Check if the email should be sent in an other charset then the default UTF-8.
6227 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6229 // Use the defined site mail charset or eventually the one preferred by the recipient.
6230 $charset = $CFG->sitemailcharset;
6231 if (!empty($CFG->allowusermailcharset)) {
6232 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6233 $charset = $useremailcharset;
6237 // Convert all the necessary strings if the charset is supported.
6238 $charsets = get_list_of_charsets();
6239 unset($charsets['UTF-8']);
6240 if (in_array($charset, $charsets)) {
6241 $mail->CharSet = $charset;
6242 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6243 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6244 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6245 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6247 foreach ($temprecipients as $key => $values) {
6248 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6250 foreach ($tempreplyto as $key => $values) {
6251 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6256 foreach ($temprecipients as $values) {
6257 $mail->addAddress($values[0], $values[1]);
6259 foreach ($tempreplyto as $values) {
6260 $mail->addReplyTo($values[0], $values[1]);
6263 if ($mail->send()) {
6264 set_send_count($user);
6265 if (!empty($mail->SMTPDebug)) {
6266 echo '</pre>';
6268 return true;
6269 } else {
6270 // Trigger event for failing to send email.
6271 $event = \core\event\email_failed::create(array(
6272 'context' => context_system::instance(),
6273 'userid' => $from->id,
6274 'relateduserid' => $user->id,
6275 'other' => array(
6276 'subject' => $subject,
6277 'message' => $messagetext,
6278 'errorinfo' => $mail->ErrorInfo
6281 $event->trigger();
6282 if (CLI_SCRIPT) {
6283 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6285 if (!empty($mail->SMTPDebug)) {
6286 echo '</pre>';
6288 return false;
6293 * Check to see if a user's real email address should be used for the "From" field.
6295 * @param object $from The user object for the user we are sending the email from.
6296 * @param object $user The user object that we are sending the email to.
6297 * @param array $unused No longer used.
6298 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6300 function can_send_from_real_email_address($from, $user, $unused = null) {
6301 global $CFG;
6302 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6303 return false;
6305 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6306 // Email is in the list of allowed domains for sending email,
6307 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6308 // in a course with the sender.
6309 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6310 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6311 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6312 && enrol_get_shared_courses($user, $from, false, true)))) {
6313 return true;
6315 return false;
6319 * Generate a signoff for emails based on support settings
6321 * @return string
6323 function generate_email_signoff() {
6324 global $CFG;
6326 $signoff = "\n";
6327 if (!empty($CFG->supportname)) {
6328 $signoff .= $CFG->supportname."\n";
6330 if (!empty($CFG->supportemail)) {
6331 $signoff .= $CFG->supportemail."\n";
6333 if (!empty($CFG->supportpage)) {
6334 $signoff .= $CFG->supportpage."\n";
6336 return $signoff;
6340 * Sets specified user's password and send the new password to the user via email.
6342 * @param stdClass $user A {@link $USER} object
6343 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6344 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6346 function setnew_password_and_mail($user, $fasthash = false) {
6347 global $CFG, $DB;
6349 // We try to send the mail in language the user understands,
6350 // unfortunately the filter_string() does not support alternative langs yet
6351 // so multilang will not work properly for site->fullname.
6352 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6354 $site = get_site();
6356 $supportuser = core_user::get_support_user();
6358 $newpassword = generate_password();
6360 update_internal_user_password($user, $newpassword, $fasthash);
6362 $a = new stdClass();
6363 $a->firstname = fullname($user, true);
6364 $a->sitename = format_string($site->fullname);
6365 $a->username = $user->username;
6366 $a->newpassword = $newpassword;
6367 $a->link = $CFG->wwwroot .'/login/?lang='.$lang;
6368 $a->signoff = generate_email_signoff();
6370 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6372 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6374 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6375 return email_to_user($user, $supportuser, $subject, $message);
6380 * Resets specified user's password and send the new password to the user via email.
6382 * @param stdClass $user A {@link $USER} object
6383 * @return bool Returns true if mail was sent OK and false if there was an error.
6385 function reset_password_and_mail($user) {
6386 global $CFG;
6388 $site = get_site();
6389 $supportuser = core_user::get_support_user();
6391 $userauth = get_auth_plugin($user->auth);
6392 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6393 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6394 return false;
6397 $newpassword = generate_password();
6399 if (!$userauth->user_update_password($user, $newpassword)) {
6400 print_error("cannotsetpassword");
6403 $a = new stdClass();
6404 $a->firstname = $user->firstname;
6405 $a->lastname = $user->lastname;
6406 $a->sitename = format_string($site->fullname);
6407 $a->username = $user->username;
6408 $a->newpassword = $newpassword;
6409 $a->link = $CFG->wwwroot .'/login/change_password.php';
6410 $a->signoff = generate_email_signoff();
6412 $message = get_string('newpasswordtext', '', $a);
6414 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6416 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6418 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6419 return email_to_user($user, $supportuser, $subject, $message);
6423 * Send email to specified user with confirmation text and activation link.
6425 * @param stdClass $user A {@link $USER} object
6426 * @param string $confirmationurl user confirmation URL
6427 * @return bool Returns true if mail was sent OK and false if there was an error.
6429 function send_confirmation_email($user, $confirmationurl = null) {
6430 global $CFG;
6432 $site = get_site();
6433 $supportuser = core_user::get_support_user();
6435 $data = new stdClass();
6436 $data->firstname = fullname($user);
6437 $data->sitename = format_string($site->fullname);
6438 $data->admin = generate_email_signoff();
6440 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6442 if (empty($confirmationurl)) {
6443 $confirmationurl = '/login/confirm.php';
6446 $confirmationurl = new moodle_url($confirmationurl);
6447 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6448 $confirmationurl->remove_params('data');
6449 $confirmationpath = $confirmationurl->out(false);
6451 // We need to custom encode the username to include trailing dots in the link.
6452 // Because of this custom encoding we can't use moodle_url directly.
6453 // Determine if a query string is present in the confirmation url.
6454 $hasquerystring = strpos($confirmationpath, '?') !== false;
6455 // Perform normal url encoding of the username first.
6456 $username = urlencode($user->username);
6457 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6458 $username = str_replace('.', '%2E', $username);
6460 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6462 $message = get_string('emailconfirmation', '', $data);
6463 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6465 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6466 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6470 * Sends a password change confirmation email.
6472 * @param stdClass $user A {@link $USER} object
6473 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6474 * @return bool Returns true if mail was sent OK and false if there was an error.
6476 function send_password_change_confirmation_email($user, $resetrecord) {
6477 global $CFG;
6479 $site = get_site();
6480 $supportuser = core_user::get_support_user();
6481 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6483 $data = new stdClass();
6484 $data->firstname = $user->firstname;
6485 $data->lastname = $user->lastname;
6486 $data->username = $user->username;
6487 $data->sitename = format_string($site->fullname);
6488 $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6489 $data->admin = generate_email_signoff();
6490 $data->resetminutes = $pwresetmins;
6492 $message = get_string('emailresetconfirmation', '', $data);
6493 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6495 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6496 return email_to_user($user, $supportuser, $subject, $message);
6501 * Sends an email containing information on how to change your password.
6503 * @param stdClass $user A {@link $USER} object
6504 * @return bool Returns true if mail was sent OK and false if there was an error.
6506 function send_password_change_info($user) {
6507 $site = get_site();
6508 $supportuser = core_user::get_support_user();
6510 $data = new stdClass();
6511 $data->firstname = $user->firstname;
6512 $data->lastname = $user->lastname;
6513 $data->username = $user->username;
6514 $data->sitename = format_string($site->fullname);
6515 $data->admin = generate_email_signoff();
6517 if (!is_enabled_auth($user->auth)) {
6518 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6519 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6520 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6521 return email_to_user($user, $supportuser, $subject, $message);
6524 $userauth = get_auth_plugin($user->auth);
6525 ['subject' => $subject, 'message' => $message] = $userauth->get_password_change_info($user);
6527 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6528 return email_to_user($user, $supportuser, $subject, $message);
6532 * Check that an email is allowed. It returns an error message if there was a problem.
6534 * @param string $email Content of email
6535 * @return string|false
6537 function email_is_not_allowed($email) {
6538 global $CFG;
6540 // Comparing lowercase domains.
6541 $email = strtolower($email);
6542 if (!empty($CFG->allowemailaddresses)) {
6543 $allowed = explode(' ', strtolower($CFG->allowemailaddresses));
6544 foreach ($allowed as $allowedpattern) {
6545 $allowedpattern = trim($allowedpattern);
6546 if (!$allowedpattern) {
6547 continue;
6549 if (strpos($allowedpattern, '.') === 0) {
6550 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6551 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6552 return false;
6555 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6556 return false;
6559 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6561 } else if (!empty($CFG->denyemailaddresses)) {
6562 $denied = explode(' ', strtolower($CFG->denyemailaddresses));
6563 foreach ($denied as $deniedpattern) {
6564 $deniedpattern = trim($deniedpattern);
6565 if (!$deniedpattern) {
6566 continue;
6568 if (strpos($deniedpattern, '.') === 0) {
6569 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6570 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6571 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6574 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6575 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6580 return false;
6583 // FILE HANDLING.
6586 * Returns local file storage instance
6588 * @return file_storage
6590 function get_file_storage($reset = false) {
6591 global $CFG;
6593 static $fs = null;
6595 if ($reset) {
6596 $fs = null;
6597 return;
6600 if ($fs) {
6601 return $fs;
6604 require_once("$CFG->libdir/filelib.php");
6606 $fs = new file_storage();
6608 return $fs;
6612 * Returns local file storage instance
6614 * @return file_browser
6616 function get_file_browser() {
6617 global $CFG;
6619 static $fb = null;
6621 if ($fb) {
6622 return $fb;
6625 require_once("$CFG->libdir/filelib.php");
6627 $fb = new file_browser();
6629 return $fb;
6633 * Returns file packer
6635 * @param string $mimetype default application/zip
6636 * @return file_packer
6638 function get_file_packer($mimetype='application/zip') {
6639 global $CFG;
6641 static $fp = array();
6643 if (isset($fp[$mimetype])) {
6644 return $fp[$mimetype];
6647 switch ($mimetype) {
6648 case 'application/zip':
6649 case 'application/vnd.moodle.profiling':
6650 $classname = 'zip_packer';
6651 break;
6653 case 'application/x-gzip' :
6654 $classname = 'tgz_packer';
6655 break;
6657 case 'application/vnd.moodle.backup':
6658 $classname = 'mbz_packer';
6659 break;
6661 default:
6662 return false;
6665 require_once("$CFG->libdir/filestorage/$classname.php");
6666 $fp[$mimetype] = new $classname();
6668 return $fp[$mimetype];
6672 * Returns current name of file on disk if it exists.
6674 * @param string $newfile File to be verified
6675 * @return string Current name of file on disk if true
6677 function valid_uploaded_file($newfile) {
6678 if (empty($newfile)) {
6679 return '';
6681 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6682 return $newfile['tmp_name'];
6683 } else {
6684 return '';
6689 * Returns the maximum size for uploading files.
6691 * There are seven possible upload limits:
6692 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6693 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6694 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6695 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6696 * 5. by the Moodle admin in $CFG->maxbytes
6697 * 6. by the teacher in the current course $course->maxbytes
6698 * 7. by the teacher for the current module, eg $assignment->maxbytes
6700 * These last two are passed to this function as arguments (in bytes).
6701 * Anything defined as 0 is ignored.
6702 * The smallest of all the non-zero numbers is returned.
6704 * @todo Finish documenting this function
6706 * @param int $sitebytes Set maximum size
6707 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6708 * @param int $modulebytes Current module ->maxbytes (in bytes)
6709 * @param bool $unused This parameter has been deprecated and is not used any more.
6710 * @return int The maximum size for uploading files.
6712 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6714 if (! $filesize = ini_get('upload_max_filesize')) {
6715 $filesize = '5M';
6717 $minimumsize = get_real_size($filesize);
6719 if ($postsize = ini_get('post_max_size')) {
6720 $postsize = get_real_size($postsize);
6721 if ($postsize < $minimumsize) {
6722 $minimumsize = $postsize;
6726 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6727 $minimumsize = $sitebytes;
6730 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6731 $minimumsize = $coursebytes;
6734 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6735 $minimumsize = $modulebytes;
6738 return $minimumsize;
6742 * Returns the maximum size for uploading files for the current user
6744 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6746 * @param context $context The context in which to check user capabilities
6747 * @param int $sitebytes Set maximum size
6748 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6749 * @param int $modulebytes Current module ->maxbytes (in bytes)
6750 * @param stdClass $user The user
6751 * @param bool $unused This parameter has been deprecated and is not used any more.
6752 * @return int The maximum size for uploading files.
6754 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6755 $unused = false) {
6756 global $USER;
6758 if (empty($user)) {
6759 $user = $USER;
6762 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6763 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6766 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6770 * Returns an array of possible sizes in local language
6772 * Related to {@link get_max_upload_file_size()} - this function returns an
6773 * array of possible sizes in an array, translated to the
6774 * local language.
6776 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6778 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6779 * with the value set to 0. This option will be the first in the list.
6781 * @uses SORT_NUMERIC
6782 * @param int $sitebytes Set maximum size
6783 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6784 * @param int $modulebytes Current module ->maxbytes (in bytes)
6785 * @param int|array $custombytes custom upload size/s which will be added to list,
6786 * Only value/s smaller then maxsize will be added to list.
6787 * @return array
6789 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6790 global $CFG;
6792 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6793 return array();
6796 if ($sitebytes == 0) {
6797 // Will get the minimum of upload_max_filesize or post_max_size.
6798 $sitebytes = get_max_upload_file_size();
6801 $filesize = array();
6802 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6803 5242880, 10485760, 20971520, 52428800, 104857600,
6804 262144000, 524288000, 786432000, 1073741824,
6805 2147483648, 4294967296, 8589934592);
6807 // If custombytes is given and is valid then add it to the list.
6808 if (is_number($custombytes) and $custombytes > 0) {
6809 $custombytes = (int)$custombytes;
6810 if (!in_array($custombytes, $sizelist)) {
6811 $sizelist[] = $custombytes;
6813 } else if (is_array($custombytes)) {
6814 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6817 // Allow maxbytes to be selected if it falls outside the above boundaries.
6818 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6819 // Note: get_real_size() is used in order to prevent problems with invalid values.
6820 $sizelist[] = get_real_size($CFG->maxbytes);
6823 foreach ($sizelist as $sizebytes) {
6824 if ($sizebytes < $maxsize && $sizebytes > 0) {
6825 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6829 $limitlevel = '';
6830 $displaysize = '';
6831 if ($modulebytes &&
6832 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6833 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6834 $limitlevel = get_string('activity', 'core');
6835 $displaysize = display_size($modulebytes);
6836 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6838 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6839 $limitlevel = get_string('course', 'core');
6840 $displaysize = display_size($coursebytes);
6841 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6843 } else if ($sitebytes) {
6844 $limitlevel = get_string('site', 'core');
6845 $displaysize = display_size($sitebytes);
6846 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6849 krsort($filesize, SORT_NUMERIC);
6850 if ($limitlevel) {
6851 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6852 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6855 return $filesize;
6859 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6861 * If excludefiles is defined, then that file/directory is ignored
6862 * If getdirs is true, then (sub)directories are included in the output
6863 * If getfiles is true, then files are included in the output
6864 * (at least one of these must be true!)
6866 * @todo Finish documenting this function. Add examples of $excludefile usage.
6868 * @param string $rootdir A given root directory to start from
6869 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6870 * @param bool $descend If true then subdirectories are recursed as well
6871 * @param bool $getdirs If true then (sub)directories are included in the output
6872 * @param bool $getfiles If true then files are included in the output
6873 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6875 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6877 $dirs = array();
6879 if (!$getdirs and !$getfiles) { // Nothing to show.
6880 return $dirs;
6883 if (!is_dir($rootdir)) { // Must be a directory.
6884 return $dirs;
6887 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6888 return $dirs;
6891 if (!is_array($excludefiles)) {
6892 $excludefiles = array($excludefiles);
6895 while (false !== ($file = readdir($dir))) {
6896 $firstchar = substr($file, 0, 1);
6897 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6898 continue;
6900 $fullfile = $rootdir .'/'. $file;
6901 if (filetype($fullfile) == 'dir') {
6902 if ($getdirs) {
6903 $dirs[] = $file;
6905 if ($descend) {
6906 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6907 foreach ($subdirs as $subdir) {
6908 $dirs[] = $file .'/'. $subdir;
6911 } else if ($getfiles) {
6912 $dirs[] = $file;
6915 closedir($dir);
6917 asort($dirs);
6919 return $dirs;
6924 * Adds up all the files in a directory and works out the size.
6926 * @param string $rootdir The directory to start from
6927 * @param string $excludefile A file to exclude when summing directory size
6928 * @return int The summed size of all files and subfiles within the root directory
6930 function get_directory_size($rootdir, $excludefile='') {
6931 global $CFG;
6933 // Do it this way if we can, it's much faster.
6934 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6935 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6936 $output = null;
6937 $return = null;
6938 exec($command, $output, $return);
6939 if (is_array($output)) {
6940 // We told it to return k.
6941 return get_real_size(intval($output[0]).'k');
6945 if (!is_dir($rootdir)) {
6946 // Must be a directory.
6947 return 0;
6950 if (!$dir = @opendir($rootdir)) {
6951 // Can't open it for some reason.
6952 return 0;
6955 $size = 0;
6957 while (false !== ($file = readdir($dir))) {
6958 $firstchar = substr($file, 0, 1);
6959 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6960 continue;
6962 $fullfile = $rootdir .'/'. $file;
6963 if (filetype($fullfile) == 'dir') {
6964 $size += get_directory_size($fullfile, $excludefile);
6965 } else {
6966 $size += filesize($fullfile);
6969 closedir($dir);
6971 return $size;
6975 * Converts bytes into display form
6977 * @static string $gb Localized string for size in gigabytes
6978 * @static string $mb Localized string for size in megabytes
6979 * @static string $kb Localized string for size in kilobytes
6980 * @static string $b Localized string for size in bytes
6981 * @param int $size The size to convert to human readable form
6982 * @return string
6984 function display_size($size) {
6986 static $gb, $mb, $kb, $b;
6988 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6989 return get_string('unlimited');
6992 if (empty($gb)) {
6993 $gb = get_string('sizegb');
6994 $mb = get_string('sizemb');
6995 $kb = get_string('sizekb');
6996 $b = get_string('sizeb');
6999 if ($size >= 1073741824) {
7000 $size = round($size / 1073741824 * 10) / 10 . $gb;
7001 } else if ($size >= 1048576) {
7002 $size = round($size / 1048576 * 10) / 10 . $mb;
7003 } else if ($size >= 1024) {
7004 $size = round($size / 1024 * 10) / 10 . $kb;
7005 } else {
7006 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
7008 return $size;
7012 * Cleans a given filename by removing suspicious or troublesome characters
7014 * @see clean_param()
7015 * @param string $string file name
7016 * @return string cleaned file name
7018 function clean_filename($string) {
7019 return clean_param($string, PARAM_FILE);
7022 // STRING TRANSLATION.
7025 * Returns the code for the current language
7027 * @category string
7028 * @return string
7030 function current_language() {
7031 global $CFG, $USER, $SESSION, $COURSE;
7033 if (!empty($SESSION->forcelang)) {
7034 // Allows overriding course-forced language (useful for admins to check
7035 // issues in courses whose language they don't understand).
7036 // Also used by some code to temporarily get language-related information in a
7037 // specific language (see force_current_language()).
7038 $return = $SESSION->forcelang;
7040 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
7041 // Course language can override all other settings for this page.
7042 $return = $COURSE->lang;
7044 } else if (!empty($SESSION->lang)) {
7045 // Session language can override other settings.
7046 $return = $SESSION->lang;
7048 } else if (!empty($USER->lang)) {
7049 $return = $USER->lang;
7051 } else if (isset($CFG->lang)) {
7052 $return = $CFG->lang;
7054 } else {
7055 $return = 'en';
7058 // Just in case this slipped in from somewhere by accident.
7059 $return = str_replace('_utf8', '', $return);
7061 return $return;
7065 * Returns parent language of current active language if defined
7067 * @category string
7068 * @param string $lang null means current language
7069 * @return string
7071 function get_parent_language($lang=null) {
7073 $parentlang = get_string_manager()->get_string('parentlanguage', 'langconfig', null, $lang);
7075 if ($parentlang === 'en') {
7076 $parentlang = '';
7079 return $parentlang;
7083 * Force the current language to get strings and dates localised in the given language.
7085 * After calling this function, all strings will be provided in the given language
7086 * until this function is called again, or equivalent code is run.
7088 * @param string $language
7089 * @return string previous $SESSION->forcelang value
7091 function force_current_language($language) {
7092 global $SESSION;
7093 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
7094 if ($language !== $sessionforcelang) {
7095 // Seting forcelang to null or an empty string disables it's effect.
7096 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
7097 $SESSION->forcelang = $language;
7098 moodle_setlocale();
7101 return $sessionforcelang;
7105 * Returns current string_manager instance.
7107 * The param $forcereload is needed for CLI installer only where the string_manager instance
7108 * must be replaced during the install.php script life time.
7110 * @category string
7111 * @param bool $forcereload shall the singleton be released and new instance created instead?
7112 * @return core_string_manager
7114 function get_string_manager($forcereload=false) {
7115 global $CFG;
7117 static $singleton = null;
7119 if ($forcereload) {
7120 $singleton = null;
7122 if ($singleton === null) {
7123 if (empty($CFG->early_install_lang)) {
7125 $transaliases = array();
7126 if (empty($CFG->langlist)) {
7127 $translist = array();
7128 } else {
7129 $translist = explode(',', $CFG->langlist);
7130 $translist = array_map('trim', $translist);
7131 // Each language in the $CFG->langlist can has an "alias" that would substitute the default language name.
7132 foreach ($translist as $i => $value) {
7133 $parts = preg_split('/\s*\|\s*/', $value, 2);
7134 if (count($parts) == 2) {
7135 $transaliases[$parts[0]] = $parts[1];
7136 $translist[$i] = $parts[0];
7141 if (!empty($CFG->config_php_settings['customstringmanager'])) {
7142 $classname = $CFG->config_php_settings['customstringmanager'];
7144 if (class_exists($classname)) {
7145 $implements = class_implements($classname);
7147 if (isset($implements['core_string_manager'])) {
7148 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7149 return $singleton;
7151 } else {
7152 debugging('Unable to instantiate custom string manager: class '.$classname.
7153 ' does not implement the core_string_manager interface.');
7156 } else {
7157 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7161 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7163 } else {
7164 $singleton = new core_string_manager_install();
7168 return $singleton;
7172 * Returns a localized string.
7174 * Returns the translated string specified by $identifier as
7175 * for $module. Uses the same format files as STphp.
7176 * $a is an object, string or number that can be used
7177 * within translation strings
7179 * eg 'hello {$a->firstname} {$a->lastname}'
7180 * or 'hello {$a}'
7182 * If you would like to directly echo the localized string use
7183 * the function {@link print_string()}
7185 * Example usage of this function involves finding the string you would
7186 * like a local equivalent of and using its identifier and module information
7187 * to retrieve it.<br/>
7188 * If you open moodle/lang/en/moodle.php and look near line 278
7189 * you will find a string to prompt a user for their word for 'course'
7190 * <code>
7191 * $string['course'] = 'Course';
7192 * </code>
7193 * So if you want to display the string 'Course'
7194 * in any language that supports it on your site
7195 * you just need to use the identifier 'course'
7196 * <code>
7197 * $mystring = '<strong>'. get_string('course') .'</strong>';
7198 * or
7199 * </code>
7200 * If the string you want is in another file you'd take a slightly
7201 * different approach. Looking in moodle/lang/en/calendar.php you find
7202 * around line 75:
7203 * <code>
7204 * $string['typecourse'] = 'Course event';
7205 * </code>
7206 * If you want to display the string "Course event" in any language
7207 * supported you would use the identifier 'typecourse' and the module 'calendar'
7208 * (because it is in the file calendar.php):
7209 * <code>
7210 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7211 * </code>
7213 * As a last resort, should the identifier fail to map to a string
7214 * the returned string will be [[ $identifier ]]
7216 * In Moodle 2.3 there is a new argument to this function $lazyload.
7217 * Setting $lazyload to true causes get_string to return a lang_string object
7218 * rather than the string itself. The fetching of the string is then put off until
7219 * the string object is first used. The object can be used by calling it's out
7220 * method or by casting the object to a string, either directly e.g.
7221 * (string)$stringobject
7222 * or indirectly by using the string within another string or echoing it out e.g.
7223 * echo $stringobject
7224 * return "<p>{$stringobject}</p>";
7225 * It is worth noting that using $lazyload and attempting to use the string as an
7226 * array key will cause a fatal error as objects cannot be used as array keys.
7227 * But you should never do that anyway!
7228 * For more information {@link lang_string}
7230 * @category string
7231 * @param string $identifier The key identifier for the localized string
7232 * @param string $component The module where the key identifier is stored,
7233 * usually expressed as the filename in the language pack without the
7234 * .php on the end but can also be written as mod/forum or grade/export/xls.
7235 * If none is specified then moodle.php is used.
7236 * @param string|object|array $a An object, string or number that can be used
7237 * within translation strings
7238 * @param bool $lazyload If set to true a string object is returned instead of
7239 * the string itself. The string then isn't calculated until it is first used.
7240 * @return string The localized string.
7241 * @throws coding_exception
7243 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7244 global $CFG;
7246 // If the lazy load argument has been supplied return a lang_string object
7247 // instead.
7248 // We need to make sure it is true (and a bool) as you will see below there
7249 // used to be a forth argument at one point.
7250 if ($lazyload === true) {
7251 return new lang_string($identifier, $component, $a);
7254 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7255 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7258 // There is now a forth argument again, this time it is a boolean however so
7259 // we can still check for the old extralocations parameter.
7260 if (!is_bool($lazyload) && !empty($lazyload)) {
7261 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7264 if (strpos($component, '/') !== false) {
7265 debugging('The module name you passed to get_string is the deprecated format ' .
7266 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7267 $componentpath = explode('/', $component);
7269 switch ($componentpath[0]) {
7270 case 'mod':
7271 $component = $componentpath[1];
7272 break;
7273 case 'blocks':
7274 case 'block':
7275 $component = 'block_'.$componentpath[1];
7276 break;
7277 case 'enrol':
7278 $component = 'enrol_'.$componentpath[1];
7279 break;
7280 case 'format':
7281 $component = 'format_'.$componentpath[1];
7282 break;
7283 case 'grade':
7284 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7285 break;
7289 $result = get_string_manager()->get_string($identifier, $component, $a);
7291 // Debugging feature lets you display string identifier and component.
7292 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7293 $result .= ' {' . $identifier . '/' . $component . '}';
7295 return $result;
7299 * Converts an array of strings to their localized value.
7301 * @param array $array An array of strings
7302 * @param string $component The language module that these strings can be found in.
7303 * @return stdClass translated strings.
7305 function get_strings($array, $component = '') {
7306 $string = new stdClass;
7307 foreach ($array as $item) {
7308 $string->$item = get_string($item, $component);
7310 return $string;
7314 * Prints out a translated string.
7316 * Prints out a translated string using the return value from the {@link get_string()} function.
7318 * Example usage of this function when the string is in the moodle.php file:<br/>
7319 * <code>
7320 * echo '<strong>';
7321 * print_string('course');
7322 * echo '</strong>';
7323 * </code>
7325 * Example usage of this function when the string is not in the moodle.php file:<br/>
7326 * <code>
7327 * echo '<h1>';
7328 * print_string('typecourse', 'calendar');
7329 * echo '</h1>';
7330 * </code>
7332 * @category string
7333 * @param string $identifier The key identifier for the localized string
7334 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7335 * @param string|object|array $a An object, string or number that can be used within translation strings
7337 function print_string($identifier, $component = '', $a = null) {
7338 echo get_string($identifier, $component, $a);
7342 * Returns a list of charset codes
7344 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7345 * (checking that such charset is supported by the texlib library!)
7347 * @return array And associative array with contents in the form of charset => charset
7349 function get_list_of_charsets() {
7351 $charsets = array(
7352 'EUC-JP' => 'EUC-JP',
7353 'ISO-2022-JP'=> 'ISO-2022-JP',
7354 'ISO-8859-1' => 'ISO-8859-1',
7355 'SHIFT-JIS' => 'SHIFT-JIS',
7356 'GB2312' => 'GB2312',
7357 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7358 'UTF-8' => 'UTF-8');
7360 asort($charsets);
7362 return $charsets;
7366 * Returns a list of valid and compatible themes
7368 * @return array
7370 function get_list_of_themes() {
7371 global $CFG;
7373 $themes = array();
7375 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7376 $themelist = explode(',', $CFG->themelist);
7377 } else {
7378 $themelist = array_keys(core_component::get_plugin_list("theme"));
7381 foreach ($themelist as $key => $themename) {
7382 $theme = theme_config::load($themename);
7383 $themes[$themename] = $theme;
7386 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7388 return $themes;
7392 * Factory function for emoticon_manager
7394 * @return emoticon_manager singleton
7396 function get_emoticon_manager() {
7397 static $singleton = null;
7399 if (is_null($singleton)) {
7400 $singleton = new emoticon_manager();
7403 return $singleton;
7407 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7409 * Whenever this manager mentiones 'emoticon object', the following data
7410 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7411 * altidentifier and altcomponent
7413 * @see admin_setting_emoticons
7415 * @copyright 2010 David Mudrak
7416 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7418 class emoticon_manager {
7421 * Returns the currently enabled emoticons
7423 * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
7424 * @return array of emoticon objects
7426 public function get_emoticons($selectable = false) {
7427 global $CFG;
7428 $notselectable = ['martin', 'egg'];
7430 if (empty($CFG->emoticons)) {
7431 return array();
7434 $emoticons = $this->decode_stored_config($CFG->emoticons);
7436 if (!is_array($emoticons)) {
7437 // Something is wrong with the format of stored setting.
7438 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7439 return array();
7441 if ($selectable) {
7442 foreach ($emoticons as $index => $emote) {
7443 if (in_array($emote->altidentifier, $notselectable)) {
7444 // Skip this one.
7445 unset($emoticons[$index]);
7450 return $emoticons;
7454 * Converts emoticon object into renderable pix_emoticon object
7456 * @param stdClass $emoticon emoticon object
7457 * @param array $attributes explicit HTML attributes to set
7458 * @return pix_emoticon
7460 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7461 $stringmanager = get_string_manager();
7462 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7463 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7464 } else {
7465 $alt = s($emoticon->text);
7467 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7471 * Encodes the array of emoticon objects into a string storable in config table
7473 * @see self::decode_stored_config()
7474 * @param array $emoticons array of emtocion objects
7475 * @return string
7477 public function encode_stored_config(array $emoticons) {
7478 return json_encode($emoticons);
7482 * Decodes the string into an array of emoticon objects
7484 * @see self::encode_stored_config()
7485 * @param string $encoded
7486 * @return string|null
7488 public function decode_stored_config($encoded) {
7489 $decoded = json_decode($encoded);
7490 if (!is_array($decoded)) {
7491 return null;
7493 return $decoded;
7497 * Returns default set of emoticons supported by Moodle
7499 * @return array of sdtClasses
7501 public function default_emoticons() {
7502 return array(
7503 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7504 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7505 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7506 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7507 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7508 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7509 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7510 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7511 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7512 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7513 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7514 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7515 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7516 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7517 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7518 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7519 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7520 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7521 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7522 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7523 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7524 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7525 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7526 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7527 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7528 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7529 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7530 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7531 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7532 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7537 * Helper method preparing the stdClass with the emoticon properties
7539 * @param string|array $text or array of strings
7540 * @param string $imagename to be used by {@link pix_emoticon}
7541 * @param string $altidentifier alternative string identifier, null for no alt
7542 * @param string $altcomponent where the alternative string is defined
7543 * @param string $imagecomponent to be used by {@link pix_emoticon}
7544 * @return stdClass
7546 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7547 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7548 return (object)array(
7549 'text' => $text,
7550 'imagename' => $imagename,
7551 'imagecomponent' => $imagecomponent,
7552 'altidentifier' => $altidentifier,
7553 'altcomponent' => $altcomponent,
7558 // ENCRYPTION.
7561 * rc4encrypt
7563 * @param string $data Data to encrypt.
7564 * @return string The now encrypted data.
7566 function rc4encrypt($data) {
7567 return endecrypt(get_site_identifier(), $data, '');
7571 * rc4decrypt
7573 * @param string $data Data to decrypt.
7574 * @return string The now decrypted data.
7576 function rc4decrypt($data) {
7577 return endecrypt(get_site_identifier(), $data, 'de');
7581 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7583 * @todo Finish documenting this function
7585 * @param string $pwd The password to use when encrypting or decrypting
7586 * @param string $data The data to be decrypted/encrypted
7587 * @param string $case Either 'de' for decrypt or '' for encrypt
7588 * @return string
7590 function endecrypt ($pwd, $data, $case) {
7592 if ($case == 'de') {
7593 $data = urldecode($data);
7596 $key[] = '';
7597 $box[] = '';
7598 $pwdlength = strlen($pwd);
7600 for ($i = 0; $i <= 255; $i++) {
7601 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7602 $box[$i] = $i;
7605 $x = 0;
7607 for ($i = 0; $i <= 255; $i++) {
7608 $x = ($x + $box[$i] + $key[$i]) % 256;
7609 $tempswap = $box[$i];
7610 $box[$i] = $box[$x];
7611 $box[$x] = $tempswap;
7614 $cipher = '';
7616 $a = 0;
7617 $j = 0;
7619 for ($i = 0; $i < strlen($data); $i++) {
7620 $a = ($a + 1) % 256;
7621 $j = ($j + $box[$a]) % 256;
7622 $temp = $box[$a];
7623 $box[$a] = $box[$j];
7624 $box[$j] = $temp;
7625 $k = $box[(($box[$a] + $box[$j]) % 256)];
7626 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7627 $cipher .= chr($cipherby);
7630 if ($case == 'de') {
7631 $cipher = urldecode(urlencode($cipher));
7632 } else {
7633 $cipher = urlencode($cipher);
7636 return $cipher;
7639 // ENVIRONMENT CHECKING.
7642 * This method validates a plug name. It is much faster than calling clean_param.
7644 * @param string $name a string that might be a plugin name.
7645 * @return bool if this string is a valid plugin name.
7647 function is_valid_plugin_name($name) {
7648 // This does not work for 'mod', bad luck, use any other type.
7649 return core_component::is_valid_plugin_name('tool', $name);
7653 * Get a list of all the plugins of a given type that define a certain API function
7654 * in a certain file. The plugin component names and function names are returned.
7656 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7657 * @param string $function the part of the name of the function after the
7658 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7659 * names like report_courselist_hook.
7660 * @param string $file the name of file within the plugin that defines the
7661 * function. Defaults to lib.php.
7662 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7663 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7665 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7666 global $CFG;
7668 // We don't include here as all plugin types files would be included.
7669 $plugins = get_plugins_with_function($function, $file, false);
7671 if (empty($plugins[$plugintype])) {
7672 return array();
7675 $allplugins = core_component::get_plugin_list($plugintype);
7677 // Reformat the array and include the files.
7678 $pluginfunctions = array();
7679 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7681 // Check that it has not been removed and the file is still available.
7682 if (!empty($allplugins[$pluginname])) {
7684 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7685 if (file_exists($filepath)) {
7686 include_once($filepath);
7687 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7692 return $pluginfunctions;
7696 * Get a list of all the plugins that define a certain API function in a certain file.
7698 * @param string $function the part of the name of the function after the
7699 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7700 * names like report_courselist_hook.
7701 * @param string $file the name of file within the plugin that defines the
7702 * function. Defaults to lib.php.
7703 * @param bool $include Whether to include the files that contain the functions or not.
7704 * @return array with [plugintype][plugin] = functionname
7706 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7707 global $CFG;
7709 if (during_initial_install() || isset($CFG->upgraderunning)) {
7710 // API functions _must not_ be called during an installation or upgrade.
7711 return [];
7714 $cache = \cache::make('core', 'plugin_functions');
7716 // Including both although I doubt that we will find two functions definitions with the same name.
7717 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7718 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7719 $pluginfunctions = $cache->get($key);
7721 // Use the plugin manager to check that plugins are currently installed.
7722 $pluginmanager = \core_plugin_manager::instance();
7724 if ($pluginfunctions !== false) {
7726 // Checking that the files are still available.
7727 foreach ($pluginfunctions as $plugintype => $plugins) {
7729 $allplugins = \core_component::get_plugin_list($plugintype);
7730 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7731 foreach ($plugins as $plugin => $function) {
7732 if (!isset($installedplugins[$plugin])) {
7733 // Plugin code is still present on disk but it is not installed.
7734 unset($pluginfunctions[$plugintype][$plugin]);
7735 continue;
7738 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7739 if (empty($allplugins[$plugin])) {
7740 unset($pluginfunctions[$plugintype][$plugin]);
7741 continue;
7744 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7745 if ($include && $fileexists) {
7746 // Include the files if it was requested.
7747 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7748 } else if (!$fileexists) {
7749 // If the file is not available any more it should not be returned.
7750 unset($pluginfunctions[$plugintype][$plugin]);
7754 return $pluginfunctions;
7757 $pluginfunctions = array();
7759 // To fill the cached. Also, everything should continue working with cache disabled.
7760 $plugintypes = \core_component::get_plugin_types();
7761 foreach ($plugintypes as $plugintype => $unused) {
7763 // We need to include files here.
7764 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7765 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7766 foreach ($pluginswithfile as $plugin => $notused) {
7768 if (!isset($installedplugins[$plugin])) {
7769 continue;
7772 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7774 $pluginfunction = false;
7775 if (function_exists($fullfunction)) {
7776 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7777 $pluginfunction = $fullfunction;
7779 } else if ($plugintype === 'mod') {
7780 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7781 $shortfunction = $plugin . '_' . $function;
7782 if (function_exists($shortfunction)) {
7783 $pluginfunction = $shortfunction;
7787 if ($pluginfunction) {
7788 if (empty($pluginfunctions[$plugintype])) {
7789 $pluginfunctions[$plugintype] = array();
7791 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7796 $cache->set($key, $pluginfunctions);
7798 return $pluginfunctions;
7803 * Lists plugin-like directories within specified directory
7805 * This function was originally used for standard Moodle plugins, please use
7806 * new core_component::get_plugin_list() now.
7808 * This function is used for general directory listing and backwards compatility.
7810 * @param string $directory relative directory from root
7811 * @param string $exclude dir name to exclude from the list (defaults to none)
7812 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7813 * @return array Sorted array of directory names found under the requested parameters
7815 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7816 global $CFG;
7818 $plugins = array();
7820 if (empty($basedir)) {
7821 $basedir = $CFG->dirroot .'/'. $directory;
7823 } else {
7824 $basedir = $basedir .'/'. $directory;
7827 if ($CFG->debugdeveloper and empty($exclude)) {
7828 // Make sure devs do not use this to list normal plugins,
7829 // this is intended for general directories that are not plugins!
7831 $subtypes = core_component::get_plugin_types();
7832 if (in_array($basedir, $subtypes)) {
7833 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7835 unset($subtypes);
7838 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7839 if (!$dirhandle = opendir($basedir)) {
7840 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7841 return array();
7843 while (false !== ($dir = readdir($dirhandle))) {
7844 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7845 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7846 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7847 continue;
7849 if (filetype($basedir .'/'. $dir) != 'dir') {
7850 continue;
7852 $plugins[] = $dir;
7854 closedir($dirhandle);
7856 if ($plugins) {
7857 asort($plugins);
7859 return $plugins;
7863 * Invoke plugin's callback functions
7865 * @param string $type plugin type e.g. 'mod'
7866 * @param string $name plugin name
7867 * @param string $feature feature name
7868 * @param string $action feature's action
7869 * @param array $params parameters of callback function, should be an array
7870 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7871 * @return mixed
7873 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7875 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7876 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7880 * Invoke component's callback functions
7882 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7883 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7884 * @param array $params parameters of callback function
7885 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7886 * @return mixed
7888 function component_callback($component, $function, array $params = array(), $default = null) {
7890 $functionname = component_callback_exists($component, $function);
7892 if ($functionname) {
7893 // Function exists, so just return function result.
7894 $ret = call_user_func_array($functionname, $params);
7895 if (is_null($ret)) {
7896 return $default;
7897 } else {
7898 return $ret;
7901 return $default;
7905 * Determine if a component callback exists and return the function name to call. Note that this
7906 * function will include the required library files so that the functioname returned can be
7907 * called directly.
7909 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7910 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7911 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7912 * @throws coding_exception if invalid component specfied
7914 function component_callback_exists($component, $function) {
7915 global $CFG; // This is needed for the inclusions.
7917 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7918 if (empty($cleancomponent)) {
7919 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7921 $component = $cleancomponent;
7923 list($type, $name) = core_component::normalize_component($component);
7924 $component = $type . '_' . $name;
7926 $oldfunction = $name.'_'.$function;
7927 $function = $component.'_'.$function;
7929 $dir = core_component::get_component_directory($component);
7930 if (empty($dir)) {
7931 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7934 // Load library and look for function.
7935 if (file_exists($dir.'/lib.php')) {
7936 require_once($dir.'/lib.php');
7939 if (!function_exists($function) and function_exists($oldfunction)) {
7940 if ($type !== 'mod' and $type !== 'core') {
7941 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7943 $function = $oldfunction;
7946 if (function_exists($function)) {
7947 return $function;
7949 return false;
7953 * Call the specified callback method on the provided class.
7955 * If the callback returns null, then the default value is returned instead.
7956 * If the class does not exist, then the default value is returned.
7958 * @param string $classname The name of the class to call upon.
7959 * @param string $methodname The name of the staticically defined method on the class.
7960 * @param array $params The arguments to pass into the method.
7961 * @param mixed $default The default value.
7962 * @return mixed The return value.
7964 function component_class_callback($classname, $methodname, array $params, $default = null) {
7965 if (!class_exists($classname)) {
7966 return $default;
7969 if (!method_exists($classname, $methodname)) {
7970 return $default;
7973 $fullfunction = $classname . '::' . $methodname;
7974 $result = call_user_func_array($fullfunction, $params);
7976 if (null === $result) {
7977 return $default;
7978 } else {
7979 return $result;
7984 * Checks whether a plugin supports a specified feature.
7986 * @param string $type Plugin type e.g. 'mod'
7987 * @param string $name Plugin name e.g. 'forum'
7988 * @param string $feature Feature code (FEATURE_xx constant)
7989 * @param mixed $default default value if feature support unknown
7990 * @return mixed Feature result (false if not supported, null if feature is unknown,
7991 * otherwise usually true but may have other feature-specific value such as array)
7992 * @throws coding_exception
7994 function plugin_supports($type, $name, $feature, $default = null) {
7995 global $CFG;
7997 if ($type === 'mod' and $name === 'NEWMODULE') {
7998 // Somebody forgot to rename the module template.
7999 return false;
8002 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
8003 if (empty($component)) {
8004 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8007 $function = null;
8009 if ($type === 'mod') {
8010 // We need this special case because we support subplugins in modules,
8011 // otherwise it would end up in infinite loop.
8012 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8013 include_once("$CFG->dirroot/mod/$name/lib.php");
8014 $function = $component.'_supports';
8015 if (!function_exists($function)) {
8016 // Legacy non-frankenstyle function name.
8017 $function = $name.'_supports';
8021 } else {
8022 if (!$path = core_component::get_plugin_directory($type, $name)) {
8023 // Non existent plugin type.
8024 return false;
8026 if (file_exists("$path/lib.php")) {
8027 include_once("$path/lib.php");
8028 $function = $component.'_supports';
8032 if ($function and function_exists($function)) {
8033 $supports = $function($feature);
8034 if (is_null($supports)) {
8035 // Plugin does not know - use default.
8036 return $default;
8037 } else {
8038 return $supports;
8042 // Plugin does not care, so use default.
8043 return $default;
8047 * Returns true if the current version of PHP is greater that the specified one.
8049 * @todo Check PHP version being required here is it too low?
8051 * @param string $version The version of php being tested.
8052 * @return bool
8054 function check_php_version($version='5.2.4') {
8055 return (version_compare(phpversion(), $version) >= 0);
8059 * Determine if moodle installation requires update.
8061 * Checks version numbers of main code and all plugins to see
8062 * if there are any mismatches.
8064 * @return bool
8066 function moodle_needs_upgrading() {
8067 global $CFG;
8069 if (empty($CFG->version)) {
8070 return true;
8073 // There is no need to purge plugininfo caches here because
8074 // these caches are not used during upgrade and they are purged after
8075 // every upgrade.
8077 if (empty($CFG->allversionshash)) {
8078 return true;
8081 $hash = core_component::get_all_versions_hash();
8083 return ($hash !== $CFG->allversionshash);
8087 * Returns the major version of this site
8089 * Moodle version numbers consist of three numbers separated by a dot, for
8090 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
8091 * called major version. This function extracts the major version from either
8092 * $CFG->release (default) or eventually from the $release variable defined in
8093 * the main version.php.
8095 * @param bool $fromdisk should the version if source code files be used
8096 * @return string|false the major version like '2.3', false if could not be determined
8098 function moodle_major_version($fromdisk = false) {
8099 global $CFG;
8101 if ($fromdisk) {
8102 $release = null;
8103 require($CFG->dirroot.'/version.php');
8104 if (empty($release)) {
8105 return false;
8108 } else {
8109 if (empty($CFG->release)) {
8110 return false;
8112 $release = $CFG->release;
8115 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8116 return $matches[0];
8117 } else {
8118 return false;
8122 // MISCELLANEOUS.
8125 * Gets the system locale
8127 * @return string Retuns the current locale.
8129 function moodle_getlocale() {
8130 global $CFG;
8132 // Fetch the correct locale based on ostype.
8133 if ($CFG->ostype == 'WINDOWS') {
8134 $stringtofetch = 'localewin';
8135 } else {
8136 $stringtofetch = 'locale';
8139 if (!empty($CFG->locale)) { // Override locale for all language packs.
8140 return $CFG->locale;
8143 return get_string($stringtofetch, 'langconfig');
8147 * Sets the system locale
8149 * @category string
8150 * @param string $locale Can be used to force a locale
8152 function moodle_setlocale($locale='') {
8153 global $CFG;
8155 static $currentlocale = ''; // Last locale caching.
8157 $oldlocale = $currentlocale;
8159 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8160 if (!empty($locale)) {
8161 $currentlocale = $locale;
8162 } else {
8163 $currentlocale = moodle_getlocale();
8166 // Do nothing if locale already set up.
8167 if ($oldlocale == $currentlocale) {
8168 return;
8171 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8172 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8173 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8175 // Get current values.
8176 $monetary= setlocale (LC_MONETARY, 0);
8177 $numeric = setlocale (LC_NUMERIC, 0);
8178 $ctype = setlocale (LC_CTYPE, 0);
8179 if ($CFG->ostype != 'WINDOWS') {
8180 $messages= setlocale (LC_MESSAGES, 0);
8182 // Set locale to all.
8183 $result = setlocale (LC_ALL, $currentlocale);
8184 // If setting of locale fails try the other utf8 or utf-8 variant,
8185 // some operating systems support both (Debian), others just one (OSX).
8186 if ($result === false) {
8187 if (stripos($currentlocale, '.UTF-8') !== false) {
8188 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8189 setlocale (LC_ALL, $newlocale);
8190 } else if (stripos($currentlocale, '.UTF8') !== false) {
8191 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8192 setlocale (LC_ALL, $newlocale);
8195 // Set old values.
8196 setlocale (LC_MONETARY, $monetary);
8197 setlocale (LC_NUMERIC, $numeric);
8198 if ($CFG->ostype != 'WINDOWS') {
8199 setlocale (LC_MESSAGES, $messages);
8201 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8202 // To workaround a well-known PHP problem with Turkish letter Ii.
8203 setlocale (LC_CTYPE, $ctype);
8208 * Count words in a string.
8210 * Words are defined as things between whitespace.
8212 * @category string
8213 * @param string $string The text to be searched for words.
8214 * @return int The count of words in the specified string
8216 function count_words($string) {
8217 $string = strip_tags($string);
8218 // Decode HTML entities.
8219 $string = html_entity_decode($string);
8220 // Replace underscores (which are classed as word characters) with spaces.
8221 $string = preg_replace('/_/u', ' ', $string);
8222 // Remove any characters that shouldn't be treated as word boundaries.
8223 $string = preg_replace('/[\'"’-]/u', '', $string);
8224 // Remove dots and commas from within numbers only.
8225 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
8227 return count(preg_split('/\w\b/u', $string)) - 1;
8231 * Count letters in a string.
8233 * Letters are defined as chars not in tags and different from whitespace.
8235 * @category string
8236 * @param string $string The text to be searched for letters.
8237 * @return int The count of letters in the specified text.
8239 function count_letters($string) {
8240 $string = strip_tags($string); // Tags are out now.
8241 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8243 return core_text::strlen($string);
8247 * Generate and return a random string of the specified length.
8249 * @param int $length The length of the string to be created.
8250 * @return string
8252 function random_string($length=15) {
8253 $randombytes = random_bytes_emulate($length);
8254 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8255 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8256 $pool .= '0123456789';
8257 $poollen = strlen($pool);
8258 $string = '';
8259 for ($i = 0; $i < $length; $i++) {
8260 $rand = ord($randombytes[$i]);
8261 $string .= substr($pool, ($rand%($poollen)), 1);
8263 return $string;
8267 * Generate a complex random string (useful for md5 salts)
8269 * This function is based on the above {@link random_string()} however it uses a
8270 * larger pool of characters and generates a string between 24 and 32 characters
8272 * @param int $length Optional if set generates a string to exactly this length
8273 * @return string
8275 function complex_random_string($length=null) {
8276 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8277 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8278 $poollen = strlen($pool);
8279 if ($length===null) {
8280 $length = floor(rand(24, 32));
8282 $randombytes = random_bytes_emulate($length);
8283 $string = '';
8284 for ($i = 0; $i < $length; $i++) {
8285 $rand = ord($randombytes[$i]);
8286 $string .= $pool[($rand%$poollen)];
8288 return $string;
8292 * Try to generates cryptographically secure pseudo-random bytes.
8294 * Note this is achieved by fallbacking between:
8295 * - PHP 7 random_bytes().
8296 * - OpenSSL openssl_random_pseudo_bytes().
8297 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8299 * @param int $length requested length in bytes
8300 * @return string binary data
8302 function random_bytes_emulate($length) {
8303 global $CFG;
8304 if ($length <= 0) {
8305 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8306 return '';
8308 if (function_exists('random_bytes')) {
8309 // Use PHP 7 goodness.
8310 $hash = @random_bytes($length);
8311 if ($hash !== false) {
8312 return $hash;
8315 if (function_exists('openssl_random_pseudo_bytes')) {
8316 // If you have the openssl extension enabled.
8317 $hash = openssl_random_pseudo_bytes($length);
8318 if ($hash !== false) {
8319 return $hash;
8323 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8324 $staticdata = serialize($CFG) . serialize($_SERVER);
8325 $hash = '';
8326 do {
8327 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8328 } while (strlen($hash) < $length);
8330 return substr($hash, 0, $length);
8334 * Given some text (which may contain HTML) and an ideal length,
8335 * this function truncates the text neatly on a word boundary if possible
8337 * @category string
8338 * @param string $text text to be shortened
8339 * @param int $ideal ideal string length
8340 * @param boolean $exact if false, $text will not be cut mid-word
8341 * @param string $ending The string to append if the passed string is truncated
8342 * @return string $truncate shortened string
8344 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8345 // If the plain text is shorter than the maximum length, return the whole text.
8346 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8347 return $text;
8350 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8351 // and only tag in its 'line'.
8352 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8354 $totallength = core_text::strlen($ending);
8355 $truncate = '';
8357 // This array stores information about open and close tags and their position
8358 // in the truncated string. Each item in the array is an object with fields
8359 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8360 // (byte position in truncated text).
8361 $tagdetails = array();
8363 foreach ($lines as $linematchings) {
8364 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8365 if (!empty($linematchings[1])) {
8366 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8367 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8368 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8369 // Record closing tag.
8370 $tagdetails[] = (object) array(
8371 'open' => false,
8372 'tag' => core_text::strtolower($tagmatchings[1]),
8373 'pos' => core_text::strlen($truncate),
8376 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8377 // Record opening tag.
8378 $tagdetails[] = (object) array(
8379 'open' => true,
8380 'tag' => core_text::strtolower($tagmatchings[1]),
8381 'pos' => core_text::strlen($truncate),
8383 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8384 $tagdetails[] = (object) array(
8385 'open' => true,
8386 'tag' => core_text::strtolower('if'),
8387 'pos' => core_text::strlen($truncate),
8389 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8390 $tagdetails[] = (object) array(
8391 'open' => false,
8392 'tag' => core_text::strtolower('if'),
8393 'pos' => core_text::strlen($truncate),
8397 // Add html-tag to $truncate'd text.
8398 $truncate .= $linematchings[1];
8401 // Calculate the length of the plain text part of the line; handle entities as one character.
8402 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8403 if ($totallength + $contentlength > $ideal) {
8404 // The number of characters which are left.
8405 $left = $ideal - $totallength;
8406 $entitieslength = 0;
8407 // Search for html entities.
8408 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)) {
8409 // Calculate the real length of all entities in the legal range.
8410 foreach ($entities[0] as $entity) {
8411 if ($entity[1]+1-$entitieslength <= $left) {
8412 $left--;
8413 $entitieslength += core_text::strlen($entity[0]);
8414 } else {
8415 // No more characters left.
8416 break;
8420 $breakpos = $left + $entitieslength;
8422 // If the words shouldn't be cut in the middle...
8423 if (!$exact) {
8424 // Search the last occurence of a space.
8425 for (; $breakpos > 0; $breakpos--) {
8426 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8427 if ($char === '.' or $char === ' ') {
8428 $breakpos += 1;
8429 break;
8430 } else if (strlen($char) > 2) {
8431 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8432 $breakpos += 1;
8433 break;
8438 if ($breakpos == 0) {
8439 // This deals with the test_shorten_text_no_spaces case.
8440 $breakpos = $left + $entitieslength;
8441 } else if ($breakpos > $left + $entitieslength) {
8442 // This deals with the previous for loop breaking on the first char.
8443 $breakpos = $left + $entitieslength;
8446 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8447 // Maximum length is reached, so get off the loop.
8448 break;
8449 } else {
8450 $truncate .= $linematchings[2];
8451 $totallength += $contentlength;
8454 // If the maximum length is reached, get off the loop.
8455 if ($totallength >= $ideal) {
8456 break;
8460 // Add the defined ending to the text.
8461 $truncate .= $ending;
8463 // Now calculate the list of open html tags based on the truncate position.
8464 $opentags = array();
8465 foreach ($tagdetails as $taginfo) {
8466 if ($taginfo->open) {
8467 // Add tag to the beginning of $opentags list.
8468 array_unshift($opentags, $taginfo->tag);
8469 } else {
8470 // Can have multiple exact same open tags, close the last one.
8471 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8472 if ($pos !== false) {
8473 unset($opentags[$pos]);
8478 // Close all unclosed html-tags.
8479 foreach ($opentags as $tag) {
8480 if ($tag === 'if') {
8481 $truncate .= '<!--<![endif]-->';
8482 } else {
8483 $truncate .= '</' . $tag . '>';
8487 return $truncate;
8491 * Shortens a given filename by removing characters positioned after the ideal string length.
8492 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8493 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8495 * @param string $filename file name
8496 * @param int $length ideal string length
8497 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8498 * @return string $shortened shortened file name
8500 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8501 $shortened = $filename;
8502 // Extract a part of the filename if it's char size exceeds the ideal string length.
8503 if (core_text::strlen($filename) > $length) {
8504 // Exclude extension if present in filename.
8505 $mimetypes = get_mimetypes_array();
8506 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8507 if ($extension && !empty($mimetypes[$extension])) {
8508 $basename = pathinfo($filename, PATHINFO_FILENAME);
8509 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8510 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8511 $shortened .= '.' . $extension;
8512 } else {
8513 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8514 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8517 return $shortened;
8521 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8523 * @param array $path The paths to reduce the length.
8524 * @param int $length Ideal string length
8525 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8526 * @return array $result Shortened paths in array.
8528 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8529 $result = null;
8531 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8532 $carry[] = shorten_filename($singlepath, $length, $includehash);
8533 return $carry;
8534 }, []);
8536 return $result;
8540 * Given dates in seconds, how many weeks is the date from startdate
8541 * The first week is 1, the second 2 etc ...
8543 * @param int $startdate Timestamp for the start date
8544 * @param int $thedate Timestamp for the end date
8545 * @return string
8547 function getweek ($startdate, $thedate) {
8548 if ($thedate < $startdate) {
8549 return 0;
8552 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8556 * Returns a randomly generated password of length $maxlen. inspired by
8558 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8559 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8561 * @param int $maxlen The maximum size of the password being generated.
8562 * @return string
8564 function generate_password($maxlen=10) {
8565 global $CFG;
8567 if (empty($CFG->passwordpolicy)) {
8568 $fillers = PASSWORD_DIGITS;
8569 $wordlist = file($CFG->wordlist);
8570 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8571 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8572 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8573 $password = $word1 . $filler1 . $word2;
8574 } else {
8575 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8576 $digits = $CFG->minpassworddigits;
8577 $lower = $CFG->minpasswordlower;
8578 $upper = $CFG->minpasswordupper;
8579 $nonalphanum = $CFG->minpasswordnonalphanum;
8580 $total = $lower + $upper + $digits + $nonalphanum;
8581 // Var minlength should be the greater one of the two ( $minlen and $total ).
8582 $minlen = $minlen < $total ? $total : $minlen;
8583 // Var maxlen can never be smaller than minlen.
8584 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8585 $additional = $maxlen - $total;
8587 // Make sure we have enough characters to fulfill
8588 // complexity requirements.
8589 $passworddigits = PASSWORD_DIGITS;
8590 while ($digits > strlen($passworddigits)) {
8591 $passworddigits .= PASSWORD_DIGITS;
8593 $passwordlower = PASSWORD_LOWER;
8594 while ($lower > strlen($passwordlower)) {
8595 $passwordlower .= PASSWORD_LOWER;
8597 $passwordupper = PASSWORD_UPPER;
8598 while ($upper > strlen($passwordupper)) {
8599 $passwordupper .= PASSWORD_UPPER;
8601 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8602 while ($nonalphanum > strlen($passwordnonalphanum)) {
8603 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8606 // Now mix and shuffle it all.
8607 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8608 substr(str_shuffle ($passwordupper), 0, $upper) .
8609 substr(str_shuffle ($passworddigits), 0, $digits) .
8610 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8611 substr(str_shuffle ($passwordlower .
8612 $passwordupper .
8613 $passworddigits .
8614 $passwordnonalphanum), 0 , $additional));
8617 return substr ($password, 0, $maxlen);
8621 * Given a float, prints it nicely.
8622 * Localized floats must not be used in calculations!
8624 * The stripzeros feature is intended for making numbers look nicer in small
8625 * areas where it is not necessary to indicate the degree of accuracy by showing
8626 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8627 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8629 * @param float $float The float to print
8630 * @param int $decimalpoints The number of decimal places to print.
8631 * @param bool $localized use localized decimal separator
8632 * @param bool $stripzeros If true, removes final zeros after decimal point
8633 * @return string locale float
8635 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8636 if (is_null($float)) {
8637 return '';
8639 if ($localized) {
8640 $separator = get_string('decsep', 'langconfig');
8641 } else {
8642 $separator = '.';
8644 $result = number_format($float, $decimalpoints, $separator, '');
8645 if ($stripzeros) {
8646 // Remove zeros and final dot if not needed.
8647 $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
8649 return $result;
8653 * Converts locale specific floating point/comma number back to standard PHP float value
8654 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8656 * @param string $localefloat locale aware float representation
8657 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8658 * @return mixed float|bool - false or the parsed float.
8660 function unformat_float($localefloat, $strict = false) {
8661 $localefloat = trim($localefloat);
8663 if ($localefloat == '') {
8664 return null;
8667 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8668 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8670 if ($strict && !is_numeric($localefloat)) {
8671 return false;
8674 return (float)$localefloat;
8678 * Given a simple array, this shuffles it up just like shuffle()
8679 * Unlike PHP's shuffle() this function works on any machine.
8681 * @param array $array The array to be rearranged
8682 * @return array
8684 function swapshuffle($array) {
8686 $last = count($array) - 1;
8687 for ($i = 0; $i <= $last; $i++) {
8688 $from = rand(0, $last);
8689 $curr = $array[$i];
8690 $array[$i] = $array[$from];
8691 $array[$from] = $curr;
8693 return $array;
8697 * Like {@link swapshuffle()}, but works on associative arrays
8699 * @param array $array The associative array to be rearranged
8700 * @return array
8702 function swapshuffle_assoc($array) {
8704 $newarray = array();
8705 $newkeys = swapshuffle(array_keys($array));
8707 foreach ($newkeys as $newkey) {
8708 $newarray[$newkey] = $array[$newkey];
8710 return $newarray;
8714 * Given an arbitrary array, and a number of draws,
8715 * this function returns an array with that amount
8716 * of items. The indexes are retained.
8718 * @todo Finish documenting this function
8720 * @param array $array
8721 * @param int $draws
8722 * @return array
8724 function draw_rand_array($array, $draws) {
8726 $return = array();
8728 $last = count($array);
8730 if ($draws > $last) {
8731 $draws = $last;
8734 while ($draws > 0) {
8735 $last--;
8737 $keys = array_keys($array);
8738 $rand = rand(0, $last);
8740 $return[$keys[$rand]] = $array[$keys[$rand]];
8741 unset($array[$keys[$rand]]);
8743 $draws--;
8746 return $return;
8750 * Calculate the difference between two microtimes
8752 * @param string $a The first Microtime
8753 * @param string $b The second Microtime
8754 * @return string
8756 function microtime_diff($a, $b) {
8757 list($adec, $asec) = explode(' ', $a);
8758 list($bdec, $bsec) = explode(' ', $b);
8759 return $bsec - $asec + $bdec - $adec;
8763 * Given a list (eg a,b,c,d,e) this function returns
8764 * an array of 1->a, 2->b, 3->c etc
8766 * @param string $list The string to explode into array bits
8767 * @param string $separator The separator used within the list string
8768 * @return array The now assembled array
8770 function make_menu_from_list($list, $separator=',') {
8772 $array = array_reverse(explode($separator, $list), true);
8773 foreach ($array as $key => $item) {
8774 $outarray[$key+1] = trim($item);
8776 return $outarray;
8780 * Creates an array that represents all the current grades that
8781 * can be chosen using the given grading type.
8783 * Negative numbers
8784 * are scales, zero is no grade, and positive numbers are maximum
8785 * grades.
8787 * @todo Finish documenting this function or better deprecated this completely!
8789 * @param int $gradingtype
8790 * @return array
8792 function make_grades_menu($gradingtype) {
8793 global $DB;
8795 $grades = array();
8796 if ($gradingtype < 0) {
8797 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8798 return make_menu_from_list($scale->scale);
8800 } else if ($gradingtype > 0) {
8801 for ($i=$gradingtype; $i>=0; $i--) {
8802 $grades[$i] = $i .' / '. $gradingtype;
8804 return $grades;
8806 return $grades;
8810 * make_unique_id_code
8812 * @todo Finish documenting this function
8814 * @uses $_SERVER
8815 * @param string $extra Extra string to append to the end of the code
8816 * @return string
8818 function make_unique_id_code($extra = '') {
8820 $hostname = 'unknownhost';
8821 if (!empty($_SERVER['HTTP_HOST'])) {
8822 $hostname = $_SERVER['HTTP_HOST'];
8823 } else if (!empty($_ENV['HTTP_HOST'])) {
8824 $hostname = $_ENV['HTTP_HOST'];
8825 } else if (!empty($_SERVER['SERVER_NAME'])) {
8826 $hostname = $_SERVER['SERVER_NAME'];
8827 } else if (!empty($_ENV['SERVER_NAME'])) {
8828 $hostname = $_ENV['SERVER_NAME'];
8831 $date = gmdate("ymdHis");
8833 $random = random_string(6);
8835 if ($extra) {
8836 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8837 } else {
8838 return $hostname .'+'. $date .'+'. $random;
8844 * Function to check the passed address is within the passed subnet
8846 * The parameter is a comma separated string of subnet definitions.
8847 * Subnet strings can be in one of three formats:
8848 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8849 * 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)
8850 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8851 * Code for type 1 modified from user posted comments by mediator at
8852 * {@link http://au.php.net/manual/en/function.ip2long.php}
8854 * @param string $addr The address you are checking
8855 * @param string $subnetstr The string of subnet addresses
8856 * @return bool
8858 function address_in_subnet($addr, $subnetstr) {
8860 if ($addr == '0.0.0.0') {
8861 return false;
8863 $subnets = explode(',', $subnetstr);
8864 $found = false;
8865 $addr = trim($addr);
8866 $addr = cleanremoteaddr($addr, false); // Normalise.
8867 if ($addr === null) {
8868 return false;
8870 $addrparts = explode(':', $addr);
8872 $ipv6 = strpos($addr, ':');
8874 foreach ($subnets as $subnet) {
8875 $subnet = trim($subnet);
8876 if ($subnet === '') {
8877 continue;
8880 if (strpos($subnet, '/') !== false) {
8881 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8882 list($ip, $mask) = explode('/', $subnet);
8883 $mask = trim($mask);
8884 if (!is_number($mask)) {
8885 continue; // Incorect mask number, eh?
8887 $ip = cleanremoteaddr($ip, false); // Normalise.
8888 if ($ip === null) {
8889 continue;
8891 if (strpos($ip, ':') !== false) {
8892 // IPv6.
8893 if (!$ipv6) {
8894 continue;
8896 if ($mask > 128 or $mask < 0) {
8897 continue; // Nonsense.
8899 if ($mask == 0) {
8900 return true; // Any address.
8902 if ($mask == 128) {
8903 if ($ip === $addr) {
8904 return true;
8906 continue;
8908 $ipparts = explode(':', $ip);
8909 $modulo = $mask % 16;
8910 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8911 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8912 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8913 if ($modulo == 0) {
8914 return true;
8916 $pos = ($mask-$modulo)/16;
8917 $ipnet = hexdec($ipparts[$pos]);
8918 $addrnet = hexdec($addrparts[$pos]);
8919 $mask = 0xffff << (16 - $modulo);
8920 if (($addrnet & $mask) == ($ipnet & $mask)) {
8921 return true;
8925 } else {
8926 // IPv4.
8927 if ($ipv6) {
8928 continue;
8930 if ($mask > 32 or $mask < 0) {
8931 continue; // Nonsense.
8933 if ($mask == 0) {
8934 return true;
8936 if ($mask == 32) {
8937 if ($ip === $addr) {
8938 return true;
8940 continue;
8942 $mask = 0xffffffff << (32 - $mask);
8943 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8944 return true;
8948 } else if (strpos($subnet, '-') !== false) {
8949 // 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.
8950 $parts = explode('-', $subnet);
8951 if (count($parts) != 2) {
8952 continue;
8955 if (strpos($subnet, ':') !== false) {
8956 // IPv6.
8957 if (!$ipv6) {
8958 continue;
8960 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8961 if ($ipstart === null) {
8962 continue;
8964 $ipparts = explode(':', $ipstart);
8965 $start = hexdec(array_pop($ipparts));
8966 $ipparts[] = trim($parts[1]);
8967 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8968 if ($ipend === null) {
8969 continue;
8971 $ipparts[7] = '';
8972 $ipnet = implode(':', $ipparts);
8973 if (strpos($addr, $ipnet) !== 0) {
8974 continue;
8976 $ipparts = explode(':', $ipend);
8977 $end = hexdec($ipparts[7]);
8979 $addrend = hexdec($addrparts[7]);
8981 if (($addrend >= $start) and ($addrend <= $end)) {
8982 return true;
8985 } else {
8986 // IPv4.
8987 if ($ipv6) {
8988 continue;
8990 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8991 if ($ipstart === null) {
8992 continue;
8994 $ipparts = explode('.', $ipstart);
8995 $ipparts[3] = trim($parts[1]);
8996 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8997 if ($ipend === null) {
8998 continue;
9001 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9002 return true;
9006 } else {
9007 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9008 if (strpos($subnet, ':') !== false) {
9009 // IPv6.
9010 if (!$ipv6) {
9011 continue;
9013 $parts = explode(':', $subnet);
9014 $count = count($parts);
9015 if ($parts[$count-1] === '') {
9016 unset($parts[$count-1]); // Trim trailing :'s.
9017 $count--;
9018 $subnet = implode('.', $parts);
9020 $isip = cleanremoteaddr($subnet, false); // Normalise.
9021 if ($isip !== null) {
9022 if ($isip === $addr) {
9023 return true;
9025 continue;
9026 } else if ($count > 8) {
9027 continue;
9029 $zeros = array_fill(0, 8-$count, '0');
9030 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9031 if (address_in_subnet($addr, $subnet)) {
9032 return true;
9035 } else {
9036 // IPv4.
9037 if ($ipv6) {
9038 continue;
9040 $parts = explode('.', $subnet);
9041 $count = count($parts);
9042 if ($parts[$count-1] === '') {
9043 unset($parts[$count-1]); // Trim trailing .
9044 $count--;
9045 $subnet = implode('.', $parts);
9047 if ($count == 4) {
9048 $subnet = cleanremoteaddr($subnet, false); // Normalise.
9049 if ($subnet === $addr) {
9050 return true;
9052 continue;
9053 } else if ($count > 4) {
9054 continue;
9056 $zeros = array_fill(0, 4-$count, '0');
9057 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9058 if (address_in_subnet($addr, $subnet)) {
9059 return true;
9065 return false;
9069 * For outputting debugging info
9071 * @param string $string The string to write
9072 * @param string $eol The end of line char(s) to use
9073 * @param string $sleep Period to make the application sleep
9074 * This ensures any messages have time to display before redirect
9076 function mtrace($string, $eol="\n", $sleep=0) {
9077 global $CFG;
9079 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
9080 $fn = $CFG->mtrace_wrapper;
9081 $fn($string, $eol);
9082 return;
9083 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
9084 fwrite(STDOUT, $string.$eol);
9086 // We must explicitly call the add_line function here.
9087 // Uses of fwrite to STDOUT are not picked up by ob_start.
9088 \core\task\logmanager::add_line("{$string}{$eol}");
9089 } else {
9090 echo $string . $eol;
9093 // Flush again.
9094 flush();
9096 // Delay to keep message on user's screen in case of subsequent redirect.
9097 if ($sleep) {
9098 sleep($sleep);
9103 * Replace 1 or more slashes or backslashes to 1 slash
9105 * @param string $path The path to strip
9106 * @return string the path with double slashes removed
9108 function cleardoubleslashes ($path) {
9109 return preg_replace('/(\/|\\\){1,}/', '/', $path);
9113 * Is the current ip in a given list?
9115 * @param string $list
9116 * @return bool
9118 function remoteip_in_list($list) {
9119 $inlist = false;
9120 $clientip = getremoteaddr(null);
9122 if (!$clientip) {
9123 // Ensure access on cli.
9124 return true;
9127 $list = explode("\n", $list);
9128 foreach ($list as $line) {
9129 $tokens = explode('#', $line);
9130 $subnet = trim($tokens[0]);
9131 if (address_in_subnet($clientip, $subnet)) {
9132 $inlist = true;
9133 break;
9136 return $inlist;
9140 * Returns most reliable client address
9142 * @param string $default If an address can't be determined, then return this
9143 * @return string The remote IP address
9145 function getremoteaddr($default='0.0.0.0') {
9146 global $CFG;
9148 if (empty($CFG->getremoteaddrconf)) {
9149 // This will happen, for example, before just after the upgrade, as the
9150 // user is redirected to the admin screen.
9151 $variablestoskip = 0;
9152 } else {
9153 $variablestoskip = $CFG->getremoteaddrconf;
9155 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
9156 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9157 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9158 return $address ? $address : $default;
9161 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
9162 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9163 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9164 $address = $forwardedaddresses[0];
9166 if (substr_count($address, ":") > 1) {
9167 // Remove port and brackets from IPv6.
9168 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9169 $address = $matches[1];
9171 } else {
9172 // Remove port from IPv4.
9173 if (substr_count($address, ":") == 1) {
9174 $parts = explode(":", $address);
9175 $address = $parts[0];
9179 $address = cleanremoteaddr($address);
9180 return $address ? $address : $default;
9183 if (!empty($_SERVER['REMOTE_ADDR'])) {
9184 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9185 return $address ? $address : $default;
9186 } else {
9187 return $default;
9192 * Cleans an ip address. Internal addresses are now allowed.
9193 * (Originally local addresses were not allowed.)
9195 * @param string $addr IPv4 or IPv6 address
9196 * @param bool $compress use IPv6 address compression
9197 * @return string normalised ip address string, null if error
9199 function cleanremoteaddr($addr, $compress=false) {
9200 $addr = trim($addr);
9202 if (strpos($addr, ':') !== false) {
9203 // Can be only IPv6.
9204 $parts = explode(':', $addr);
9205 $count = count($parts);
9207 if (strpos($parts[$count-1], '.') !== false) {
9208 // Legacy ipv4 notation.
9209 $last = array_pop($parts);
9210 $ipv4 = cleanremoteaddr($last, true);
9211 if ($ipv4 === null) {
9212 return null;
9214 $bits = explode('.', $ipv4);
9215 $parts[] = dechex($bits[0]).dechex($bits[1]);
9216 $parts[] = dechex($bits[2]).dechex($bits[3]);
9217 $count = count($parts);
9218 $addr = implode(':', $parts);
9221 if ($count < 3 or $count > 8) {
9222 return null; // Severly malformed.
9225 if ($count != 8) {
9226 if (strpos($addr, '::') === false) {
9227 return null; // Malformed.
9229 // Uncompress.
9230 $insertat = array_search('', $parts, true);
9231 $missing = array_fill(0, 1 + 8 - $count, '0');
9232 array_splice($parts, $insertat, 1, $missing);
9233 foreach ($parts as $key => $part) {
9234 if ($part === '') {
9235 $parts[$key] = '0';
9240 $adr = implode(':', $parts);
9241 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9242 return null; // Incorrect format - sorry.
9245 // Normalise 0s and case.
9246 $parts = array_map('hexdec', $parts);
9247 $parts = array_map('dechex', $parts);
9249 $result = implode(':', $parts);
9251 if (!$compress) {
9252 return $result;
9255 if ($result === '0:0:0:0:0:0:0:0') {
9256 return '::'; // All addresses.
9259 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9260 if ($compressed !== $result) {
9261 return $compressed;
9264 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9265 if ($compressed !== $result) {
9266 return $compressed;
9269 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9270 if ($compressed !== $result) {
9271 return $compressed;
9274 return $result;
9277 // First get all things that look like IPv4 addresses.
9278 $parts = array();
9279 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9280 return null;
9282 unset($parts[0]);
9284 foreach ($parts as $key => $match) {
9285 if ($match > 255) {
9286 return null;
9288 $parts[$key] = (int)$match; // Normalise 0s.
9291 return implode('.', $parts);
9296 * Is IP address a public address?
9298 * @param string $ip The ip to check
9299 * @return bool true if the ip is public
9301 function ip_is_public($ip) {
9302 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9306 * This function will make a complete copy of anything it's given,
9307 * regardless of whether it's an object or not.
9309 * @param mixed $thing Something you want cloned
9310 * @return mixed What ever it is you passed it
9312 function fullclone($thing) {
9313 return unserialize(serialize($thing));
9317 * Used to make sure that $min <= $value <= $max
9319 * Make sure that value is between min, and max
9321 * @param int $min The minimum value
9322 * @param int $value The value to check
9323 * @param int $max The maximum value
9324 * @return int
9326 function bounded_number($min, $value, $max) {
9327 if ($value < $min) {
9328 return $min;
9330 if ($value > $max) {
9331 return $max;
9333 return $value;
9337 * Check if there is a nested array within the passed array
9339 * @param array $array
9340 * @return bool true if there is a nested array false otherwise
9342 function array_is_nested($array) {
9343 foreach ($array as $value) {
9344 if (is_array($value)) {
9345 return true;
9348 return false;
9352 * get_performance_info() pairs up with init_performance_info()
9353 * loaded in setup.php. Returns an array with 'html' and 'txt'
9354 * values ready for use, and each of the individual stats provided
9355 * separately as well.
9357 * @return array
9359 function get_performance_info() {
9360 global $CFG, $PERF, $DB, $PAGE;
9362 $info = array();
9363 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9365 $info['html'] = '';
9366 if (!empty($CFG->themedesignermode)) {
9367 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9368 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9370 $info['html'] .= '<ul class="list-unstyled ml-1 row">'; // Holds userfriendly HTML representation.
9372 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9374 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9375 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9377 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9378 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9380 if (function_exists('memory_get_usage')) {
9381 $info['memory_total'] = memory_get_usage();
9382 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9383 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9384 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9385 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9388 if (function_exists('memory_get_peak_usage')) {
9389 $info['memory_peak'] = memory_get_peak_usage();
9390 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9391 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9394 $info['html'] .= '</ul><ul class="list-unstyled ml-1 row">';
9395 $inc = get_included_files();
9396 $info['includecount'] = count($inc);
9397 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9398 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9400 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9401 // We can not track more performance before installation or before PAGE init, sorry.
9402 return $info;
9405 $filtermanager = filter_manager::instance();
9406 if (method_exists($filtermanager, 'get_performance_summary')) {
9407 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9408 $info = array_merge($filterinfo, $info);
9409 foreach ($filterinfo as $key => $value) {
9410 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9411 $info['txt'] .= "$key: $value ";
9415 $stringmanager = get_string_manager();
9416 if (method_exists($stringmanager, 'get_performance_summary')) {
9417 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9418 $info = array_merge($filterinfo, $info);
9419 foreach ($filterinfo as $key => $value) {
9420 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9421 $info['txt'] .= "$key: $value ";
9425 if (!empty($PERF->logwrites)) {
9426 $info['logwrites'] = $PERF->logwrites;
9427 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9428 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9431 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9432 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9433 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9435 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9436 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9437 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9439 if (function_exists('posix_times')) {
9440 $ptimes = posix_times();
9441 if (is_array($ptimes)) {
9442 foreach ($ptimes as $key => $val) {
9443 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9445 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9446 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9447 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9451 // Grab the load average for the last minute.
9452 // /proc will only work under some linux configurations
9453 // while uptime is there under MacOSX/Darwin and other unices.
9454 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9455 list($serverload) = explode(' ', $loadavg[0]);
9456 unset($loadavg);
9457 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9458 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9459 $serverload = $matches[1];
9460 } else {
9461 trigger_error('Could not parse uptime output!');
9464 if (!empty($serverload)) {
9465 $info['serverload'] = $serverload;
9466 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9467 $info['txt'] .= "serverload: {$info['serverload']} ";
9470 // Display size of session if session started.
9471 if ($si = \core\session\manager::get_performance_info()) {
9472 $info['sessionsize'] = $si['size'];
9473 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9474 $info['txt'] .= $si['txt'];
9477 $info['html'] .= '</ul>';
9478 if ($stats = cache_helper::get_stats()) {
9479 $html = '<ul class="cachesused list-unstyled ml-1 row">';
9480 $html .= '<li class="cache-stats-heading font-weight-bold">Caches used (hits/misses/sets)</li>';
9481 $html .= '</ul><ul class="cachesused list-unstyled ml-1">';
9482 $text = 'Caches used (hits/misses/sets): ';
9483 $hits = 0;
9484 $misses = 0;
9485 $sets = 0;
9486 foreach ($stats as $definition => $details) {
9487 switch ($details['mode']) {
9488 case cache_store::MODE_APPLICATION:
9489 $modeclass = 'application';
9490 $mode = ' <span title="application cache">[a]</span>';
9491 break;
9492 case cache_store::MODE_SESSION:
9493 $modeclass = 'session';
9494 $mode = ' <span title="session cache">[s]</span>';
9495 break;
9496 case cache_store::MODE_REQUEST:
9497 $modeclass = 'request';
9498 $mode = ' <span title="request cache">[r]</span>';
9499 break;
9501 $html .= '<ul class="cache-definition-stats list-unstyled ml-1 mb-1 cache-mode-'.$modeclass.' card d-inline-block">';
9502 $html .= '<li class="cache-definition-stats-heading p-t-1 card-header bg-dark bg-inverse font-weight-bold">' .
9503 $definition . $mode.'</li>';
9504 $text .= "$definition {";
9505 foreach ($details['stores'] as $store => $data) {
9506 $hits += $data['hits'];
9507 $misses += $data['misses'];
9508 $sets += $data['sets'];
9509 if ($data['hits'] == 0 and $data['misses'] > 0) {
9510 $cachestoreclass = 'nohits text-danger';
9511 } else if ($data['hits'] < $data['misses']) {
9512 $cachestoreclass = 'lowhits text-warning';
9513 } else {
9514 $cachestoreclass = 'hihits text-success';
9516 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9517 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">" .
9518 "$store: $data[hits] / $data[misses] / $data[sets]</li>";
9519 // This makes boxes of same sizes.
9520 if (count($details['stores']) == 1) {
9521 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">&nbsp;</li>";
9524 $html .= '</ul>';
9525 $text .= '} ';
9527 $html .= '</ul> ';
9528 $html .= "<div class='cache-total-stats row'>Total: $hits / $misses / $sets</div>";
9529 $info['cachesused'] = "$hits / $misses / $sets";
9530 $info['html'] .= $html;
9531 $info['txt'] .= $text.'. ';
9532 } else {
9533 $info['cachesused'] = '0 / 0 / 0';
9534 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9535 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9538 $info['html'] = '<div class="performanceinfo siteinfo container-fluid">'.$info['html'].'</div>';
9539 return $info;
9543 * Delete directory or only its content
9545 * @param string $dir directory path
9546 * @param bool $contentonly
9547 * @return bool success, true also if dir does not exist
9549 function remove_dir($dir, $contentonly=false) {
9550 if (!file_exists($dir)) {
9551 // Nothing to do.
9552 return true;
9554 if (!$handle = opendir($dir)) {
9555 return false;
9557 $result = true;
9558 while (false!==($item = readdir($handle))) {
9559 if ($item != '.' && $item != '..') {
9560 if (is_dir($dir.'/'.$item)) {
9561 $result = remove_dir($dir.'/'.$item) && $result;
9562 } else {
9563 $result = unlink($dir.'/'.$item) && $result;
9567 closedir($handle);
9568 if ($contentonly) {
9569 clearstatcache(); // Make sure file stat cache is properly invalidated.
9570 return $result;
9572 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9573 clearstatcache(); // Make sure file stat cache is properly invalidated.
9574 return $result;
9578 * Detect if an object or a class contains a given property
9579 * will take an actual object or the name of a class
9581 * @param mix $obj Name of class or real object to test
9582 * @param string $property name of property to find
9583 * @return bool true if property exists
9585 function object_property_exists( $obj, $property ) {
9586 if (is_string( $obj )) {
9587 $properties = get_class_vars( $obj );
9588 } else {
9589 $properties = get_object_vars( $obj );
9591 return array_key_exists( $property, $properties );
9595 * Converts an object into an associative array
9597 * This function converts an object into an associative array by iterating
9598 * over its public properties. Because this function uses the foreach
9599 * construct, Iterators are respected. It works recursively on arrays of objects.
9600 * Arrays and simple values are returned as is.
9602 * If class has magic properties, it can implement IteratorAggregate
9603 * and return all available properties in getIterator()
9605 * @param mixed $var
9606 * @return array
9608 function convert_to_array($var) {
9609 $result = array();
9611 // Loop over elements/properties.
9612 foreach ($var as $key => $value) {
9613 // Recursively convert objects.
9614 if (is_object($value) || is_array($value)) {
9615 $result[$key] = convert_to_array($value);
9616 } else {
9617 // Simple values are untouched.
9618 $result[$key] = $value;
9621 return $result;
9625 * Detect a custom script replacement in the data directory that will
9626 * replace an existing moodle script
9628 * @return string|bool full path name if a custom script exists, false if no custom script exists
9630 function custom_script_path() {
9631 global $CFG, $SCRIPT;
9633 if ($SCRIPT === null) {
9634 // Probably some weird external script.
9635 return false;
9638 $scriptpath = $CFG->customscripts . $SCRIPT;
9640 // Check the custom script exists.
9641 if (file_exists($scriptpath) and is_file($scriptpath)) {
9642 return $scriptpath;
9643 } else {
9644 return false;
9649 * Returns whether or not the user object is a remote MNET user. This function
9650 * is in moodlelib because it does not rely on loading any of the MNET code.
9652 * @param object $user A valid user object
9653 * @return bool True if the user is from a remote Moodle.
9655 function is_mnet_remote_user($user) {
9656 global $CFG;
9658 if (!isset($CFG->mnet_localhost_id)) {
9659 include_once($CFG->dirroot . '/mnet/lib.php');
9660 $env = new mnet_environment();
9661 $env->init();
9662 unset($env);
9665 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9669 * This function will search for browser prefereed languages, setting Moodle
9670 * to use the best one available if $SESSION->lang is undefined
9672 function setup_lang_from_browser() {
9673 global $CFG, $SESSION, $USER;
9675 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9676 // Lang is defined in session or user profile, nothing to do.
9677 return;
9680 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9681 return;
9684 // Extract and clean langs from headers.
9685 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9686 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9687 $rawlangs = explode(',', $rawlangs); // Convert to array.
9688 $langs = array();
9690 $order = 1.0;
9691 foreach ($rawlangs as $lang) {
9692 if (strpos($lang, ';') === false) {
9693 $langs[(string)$order] = $lang;
9694 $order = $order-0.01;
9695 } else {
9696 $parts = explode(';', $lang);
9697 $pos = strpos($parts[1], '=');
9698 $langs[substr($parts[1], $pos+1)] = $parts[0];
9701 krsort($langs, SORT_NUMERIC);
9703 // Look for such langs under standard locations.
9704 foreach ($langs as $lang) {
9705 // Clean it properly for include.
9706 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9707 if (get_string_manager()->translation_exists($lang, false)) {
9708 // Lang exists, set it in session.
9709 $SESSION->lang = $lang;
9710 // We have finished. Go out.
9711 break;
9714 return;
9718 * Check if $url matches anything in proxybypass list
9720 * Any errors just result in the proxy being used (least bad)
9722 * @param string $url url to check
9723 * @return boolean true if we should bypass the proxy
9725 function is_proxybypass( $url ) {
9726 global $CFG;
9728 // Sanity check.
9729 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9730 return false;
9733 // Get the host part out of the url.
9734 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9735 return false;
9738 // Get the possible bypass hosts into an array.
9739 $matches = explode( ',', $CFG->proxybypass );
9741 // Check for a match.
9742 // (IPs need to match the left hand side and hosts the right of the url,
9743 // but we can recklessly check both as there can't be a false +ve).
9744 foreach ($matches as $match) {
9745 $match = trim($match);
9747 // Try for IP match (Left side).
9748 $lhs = substr($host, 0, strlen($match));
9749 if (strcasecmp($match, $lhs)==0) {
9750 return true;
9753 // Try for host match (Right side).
9754 $rhs = substr($host, -strlen($match));
9755 if (strcasecmp($match, $rhs)==0) {
9756 return true;
9760 // Nothing matched.
9761 return false;
9765 * Check if the passed navigation is of the new style
9767 * @param mixed $navigation
9768 * @return bool true for yes false for no
9770 function is_newnav($navigation) {
9771 if (is_array($navigation) && !empty($navigation['newnav'])) {
9772 return true;
9773 } else {
9774 return false;
9779 * Checks whether the given variable name is defined as a variable within the given object.
9781 * This will NOT work with stdClass objects, which have no class variables.
9783 * @param string $var The variable name
9784 * @param object $object The object to check
9785 * @return boolean
9787 function in_object_vars($var, $object) {
9788 $classvars = get_class_vars(get_class($object));
9789 $classvars = array_keys($classvars);
9790 return in_array($var, $classvars);
9794 * Returns an array without repeated objects.
9795 * This function is similar to array_unique, but for arrays that have objects as values
9797 * @param array $array
9798 * @param bool $keepkeyassoc
9799 * @return array
9801 function object_array_unique($array, $keepkeyassoc = true) {
9802 $duplicatekeys = array();
9803 $tmp = array();
9805 foreach ($array as $key => $val) {
9806 // Convert objects to arrays, in_array() does not support objects.
9807 if (is_object($val)) {
9808 $val = (array)$val;
9811 if (!in_array($val, $tmp)) {
9812 $tmp[] = $val;
9813 } else {
9814 $duplicatekeys[] = $key;
9818 foreach ($duplicatekeys as $key) {
9819 unset($array[$key]);
9822 return $keepkeyassoc ? $array : array_values($array);
9826 * Is a userid the primary administrator?
9828 * @param int $userid int id of user to check
9829 * @return boolean
9831 function is_primary_admin($userid) {
9832 $primaryadmin = get_admin();
9834 if ($userid == $primaryadmin->id) {
9835 return true;
9836 } else {
9837 return false;
9842 * Returns the site identifier
9844 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9846 function get_site_identifier() {
9847 global $CFG;
9848 // Check to see if it is missing. If so, initialise it.
9849 if (empty($CFG->siteidentifier)) {
9850 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9852 // Return it.
9853 return $CFG->siteidentifier;
9857 * Check whether the given password has no more than the specified
9858 * number of consecutive identical characters.
9860 * @param string $password password to be checked against the password policy
9861 * @param integer $maxchars maximum number of consecutive identical characters
9862 * @return bool
9864 function check_consecutive_identical_characters($password, $maxchars) {
9866 if ($maxchars < 1) {
9867 return true; // Zero 0 is to disable this check.
9869 if (strlen($password) <= $maxchars) {
9870 return true; // Too short to fail this test.
9873 $previouschar = '';
9874 $consecutivecount = 1;
9875 foreach (str_split($password) as $char) {
9876 if ($char != $previouschar) {
9877 $consecutivecount = 1;
9878 } else {
9879 $consecutivecount++;
9880 if ($consecutivecount > $maxchars) {
9881 return false; // Check failed already.
9885 $previouschar = $char;
9888 return true;
9892 * Helper function to do partial function binding.
9893 * so we can use it for preg_replace_callback, for example
9894 * this works with php functions, user functions, static methods and class methods
9895 * it returns you a callback that you can pass on like so:
9897 * $callback = partial('somefunction', $arg1, $arg2);
9898 * or
9899 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9900 * or even
9901 * $obj = new someclass();
9902 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9904 * and then the arguments that are passed through at calltime are appended to the argument list.
9906 * @param mixed $function a php callback
9907 * @param mixed $arg1,... $argv arguments to partially bind with
9908 * @return array Array callback
9910 function partial() {
9911 if (!class_exists('partial')) {
9913 * Used to manage function binding.
9914 * @copyright 2009 Penny Leach
9915 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9917 class partial{
9918 /** @var array */
9919 public $values = array();
9920 /** @var string The function to call as a callback. */
9921 public $func;
9923 * Constructor
9924 * @param string $func
9925 * @param array $args
9927 public function __construct($func, $args) {
9928 $this->values = $args;
9929 $this->func = $func;
9932 * Calls the callback function.
9933 * @return mixed
9935 public function method() {
9936 $args = func_get_args();
9937 return call_user_func_array($this->func, array_merge($this->values, $args));
9941 $args = func_get_args();
9942 $func = array_shift($args);
9943 $p = new partial($func, $args);
9944 return array($p, 'method');
9948 * helper function to load up and initialise the mnet environment
9949 * this must be called before you use mnet functions.
9951 * @return mnet_environment the equivalent of old $MNET global
9953 function get_mnet_environment() {
9954 global $CFG;
9955 require_once($CFG->dirroot . '/mnet/lib.php');
9956 static $instance = null;
9957 if (empty($instance)) {
9958 $instance = new mnet_environment();
9959 $instance->init();
9961 return $instance;
9965 * during xmlrpc server code execution, any code wishing to access
9966 * information about the remote peer must use this to get it.
9968 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9970 function get_mnet_remote_client() {
9971 if (!defined('MNET_SERVER')) {
9972 debugging(get_string('notinxmlrpcserver', 'mnet'));
9973 return false;
9975 global $MNET_REMOTE_CLIENT;
9976 if (isset($MNET_REMOTE_CLIENT)) {
9977 return $MNET_REMOTE_CLIENT;
9979 return false;
9983 * during the xmlrpc server code execution, this will be called
9984 * to setup the object returned by {@link get_mnet_remote_client}
9986 * @param mnet_remote_client $client the client to set up
9987 * @throws moodle_exception
9989 function set_mnet_remote_client($client) {
9990 if (!defined('MNET_SERVER')) {
9991 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9993 global $MNET_REMOTE_CLIENT;
9994 $MNET_REMOTE_CLIENT = $client;
9998 * return the jump url for a given remote user
9999 * this is used for rewriting forum post links in emails, etc
10001 * @param stdclass $user the user to get the idp url for
10003 function mnet_get_idp_jump_url($user) {
10004 global $CFG;
10006 static $mnetjumps = array();
10007 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
10008 $idp = mnet_get_peer_host($user->mnethostid);
10009 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
10010 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
10012 return $mnetjumps[$user->mnethostid];
10016 * Gets the homepage to use for the current user
10018 * @return int One of HOMEPAGE_*
10020 function get_home_page() {
10021 global $CFG;
10023 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
10024 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
10025 return HOMEPAGE_MY;
10026 } else {
10027 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
10030 return HOMEPAGE_SITE;
10034 * Gets the name of a course to be displayed when showing a list of courses.
10035 * By default this is just $course->fullname but user can configure it. The
10036 * result of this function should be passed through print_string.
10037 * @param stdClass|core_course_list_element $course Moodle course object
10038 * @return string Display name of course (either fullname or short + fullname)
10040 function get_course_display_name_for_list($course) {
10041 global $CFG;
10042 if (!empty($CFG->courselistshortnames)) {
10043 if (!($course instanceof stdClass)) {
10044 $course = (object)convert_to_array($course);
10046 return get_string('courseextendednamedisplay', '', $course);
10047 } else {
10048 return $course->fullname;
10053 * Safe analogue of unserialize() that can only parse arrays
10055 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
10056 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
10057 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
10059 * @param string $expression
10060 * @return array|bool either parsed array or false if parsing was impossible.
10062 function unserialize_array($expression) {
10063 $subs = [];
10064 // Find nested arrays, parse them and store in $subs , substitute with special string.
10065 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
10066 $key = '--SUB' . count($subs) . '--';
10067 $subs[$key] = unserialize_array($matches[2]);
10068 if ($subs[$key] === false) {
10069 return false;
10071 $expression = str_replace($matches[2], $key . ';', $expression);
10074 // Check the expression is an array.
10075 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
10076 return false;
10078 // Get the size and elements of an array (key;value;key;value;....).
10079 $parts = explode(';', $matches1[2]);
10080 $size = intval($matches1[1]);
10081 if (count($parts) < $size * 2 + 1) {
10082 return false;
10084 // Analyze each part and make sure it is an integer or string or a substitute.
10085 $value = [];
10086 for ($i = 0; $i < $size * 2; $i++) {
10087 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
10088 $parts[$i] = (int)$matches2[1];
10089 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
10090 $parts[$i] = $matches3[2];
10091 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
10092 $parts[$i] = $subs[$parts[$i]];
10093 } else {
10094 return false;
10097 // Combine keys and values.
10098 for ($i = 0; $i < $size * 2; $i += 2) {
10099 $value[$parts[$i]] = $parts[$i+1];
10101 return $value;
10105 * The lang_string class
10107 * This special class is used to create an object representation of a string request.
10108 * It is special because processing doesn't occur until the object is first used.
10109 * The class was created especially to aid performance in areas where strings were
10110 * required to be generated but were not necessarily used.
10111 * As an example the admin tree when generated uses over 1500 strings, of which
10112 * normally only 1/3 are ever actually printed at any time.
10113 * The performance advantage is achieved by not actually processing strings that
10114 * arn't being used, as such reducing the processing required for the page.
10116 * How to use the lang_string class?
10117 * There are two methods of using the lang_string class, first through the
10118 * forth argument of the get_string function, and secondly directly.
10119 * The following are examples of both.
10120 * 1. Through get_string calls e.g.
10121 * $string = get_string($identifier, $component, $a, true);
10122 * $string = get_string('yes', 'moodle', null, true);
10123 * 2. Direct instantiation
10124 * $string = new lang_string($identifier, $component, $a, $lang);
10125 * $string = new lang_string('yes');
10127 * How do I use a lang_string object?
10128 * The lang_string object makes use of a magic __toString method so that you
10129 * are able to use the object exactly as you would use a string in most cases.
10130 * This means you are able to collect it into a variable and then directly
10131 * echo it, or concatenate it into another string, or similar.
10132 * The other thing you can do is manually get the string by calling the
10133 * lang_strings out method e.g.
10134 * $string = new lang_string('yes');
10135 * $string->out();
10136 * Also worth noting is that the out method can take one argument, $lang which
10137 * allows the developer to change the language on the fly.
10139 * When should I use a lang_string object?
10140 * The lang_string object is designed to be used in any situation where a
10141 * string may not be needed, but needs to be generated.
10142 * The admin tree is a good example of where lang_string objects should be
10143 * used.
10144 * A more practical example would be any class that requries strings that may
10145 * not be printed (after all classes get renderer by renderers and who knows
10146 * what they will do ;))
10148 * When should I not use a lang_string object?
10149 * Don't use lang_strings when you are going to use a string immediately.
10150 * There is no need as it will be processed immediately and there will be no
10151 * advantage, and in fact perhaps a negative hit as a class has to be
10152 * instantiated for a lang_string object, however get_string won't require
10153 * that.
10155 * Limitations:
10156 * 1. You cannot use a lang_string object as an array offset. Doing so will
10157 * result in PHP throwing an error. (You can use it as an object property!)
10159 * @package core
10160 * @category string
10161 * @copyright 2011 Sam Hemelryk
10162 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10164 class lang_string {
10166 /** @var string The strings identifier */
10167 protected $identifier;
10168 /** @var string The strings component. Default '' */
10169 protected $component = '';
10170 /** @var array|stdClass Any arguments required for the string. Default null */
10171 protected $a = null;
10172 /** @var string The language to use when processing the string. Default null */
10173 protected $lang = null;
10175 /** @var string The processed string (once processed) */
10176 protected $string = null;
10179 * A special boolean. If set to true then the object has been woken up and
10180 * cannot be regenerated. If this is set then $this->string MUST be used.
10181 * @var bool
10183 protected $forcedstring = false;
10186 * Constructs a lang_string object
10188 * This function should do as little processing as possible to ensure the best
10189 * performance for strings that won't be used.
10191 * @param string $identifier The strings identifier
10192 * @param string $component The strings component
10193 * @param stdClass|array $a Any arguments the string requires
10194 * @param string $lang The language to use when processing the string.
10195 * @throws coding_exception
10197 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10198 if (empty($component)) {
10199 $component = 'moodle';
10202 $this->identifier = $identifier;
10203 $this->component = $component;
10204 $this->lang = $lang;
10206 // We MUST duplicate $a to ensure that it if it changes by reference those
10207 // changes are not carried across.
10208 // To do this we always ensure $a or its properties/values are strings
10209 // and that any properties/values that arn't convertable are forgotten.
10210 if (!empty($a)) {
10211 if (is_scalar($a)) {
10212 $this->a = $a;
10213 } else if ($a instanceof lang_string) {
10214 $this->a = $a->out();
10215 } else if (is_object($a) or is_array($a)) {
10216 $a = (array)$a;
10217 $this->a = array();
10218 foreach ($a as $key => $value) {
10219 // Make sure conversion errors don't get displayed (results in '').
10220 if (is_array($value)) {
10221 $this->a[$key] = '';
10222 } else if (is_object($value)) {
10223 if (method_exists($value, '__toString')) {
10224 $this->a[$key] = $value->__toString();
10225 } else {
10226 $this->a[$key] = '';
10228 } else {
10229 $this->a[$key] = (string)$value;
10235 if (debugging(false, DEBUG_DEVELOPER)) {
10236 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10237 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10239 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10240 throw new coding_exception('Invalid string compontent. Please check your string definition');
10242 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10243 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10249 * Processes the string.
10251 * This function actually processes the string, stores it in the string property
10252 * and then returns it.
10253 * You will notice that this function is VERY similar to the get_string method.
10254 * That is because it is pretty much doing the same thing.
10255 * However as this function is an upgrade it isn't as tolerant to backwards
10256 * compatibility.
10258 * @return string
10259 * @throws coding_exception
10261 protected function get_string() {
10262 global $CFG;
10264 // Check if we need to process the string.
10265 if ($this->string === null) {
10266 // Check the quality of the identifier.
10267 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10268 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);
10271 // Process the string.
10272 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10273 // Debugging feature lets you display string identifier and component.
10274 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10275 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10278 // Return the string.
10279 return $this->string;
10283 * Returns the string
10285 * @param string $lang The langauge to use when processing the string
10286 * @return string
10288 public function out($lang = null) {
10289 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10290 if ($this->forcedstring) {
10291 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10292 return $this->get_string();
10294 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10295 return $translatedstring->out();
10297 return $this->get_string();
10301 * Magic __toString method for printing a string
10303 * @return string
10305 public function __toString() {
10306 return $this->get_string();
10310 * Magic __set_state method used for var_export
10312 * @return string
10314 public function __set_state() {
10315 return $this->get_string();
10319 * Prepares the lang_string for sleep and stores only the forcedstring and
10320 * string properties... the string cannot be regenerated so we need to ensure
10321 * it is generated for this.
10323 * @return string
10325 public function __sleep() {
10326 $this->get_string();
10327 $this->forcedstring = true;
10328 return array('forcedstring', 'string', 'lang');
10332 * Returns the identifier.
10334 * @return string
10336 public function get_identifier() {
10337 return $this->identifier;
10341 * Returns the component.
10343 * @return string
10345 public function get_component() {
10346 return $this->component;
10351 * Get human readable name describing the given callable.
10353 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10354 * It does not check if the callable actually exists.
10356 * @param callable|string|array $callable
10357 * @return string|bool Human readable name of callable, or false if not a valid callable.
10359 function get_callable_name($callable) {
10361 if (!is_callable($callable, true, $name)) {
10362 return false;
10364 } else {
10365 return $name;
10370 * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10371 * Never put your faith on this function and rely on its accuracy as there might be false positives.
10372 * It just performs some simple checks, and mainly is used for places where we want to hide some options
10373 * such as site registration when $CFG->wwwroot is not publicly accessible.
10374 * Good thing is there is no false negative.
10376 * @return bool
10378 function site_is_public() {
10379 global $CFG;
10381 $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
10383 if ($host === 'localhost' || preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10384 $ispublic = false;
10385 } else if (\core\ip_utils::is_ip_address($host) && !ip_is_public($host)) {
10386 $ispublic = false;
10387 } else {
10388 $ispublic = true;
10391 return $ispublic;