Moodle release 3.5.17
[moodle.git] / lib / moodlelib.php
blob895058f75f519855dcd836aa2b045f26a6e5f0cb
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 * Instead, do something like
141 * $rawvalue = required_param('name', PARAM_RAW);
142 * // ... other code including require_login, which sets current lang ...
143 * $realvalue = unformat_float($rawvalue);
144 * // ... then use $realvalue
146 define('PARAM_FLOAT', 'float');
149 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
151 define('PARAM_HOST', 'host');
154 * PARAM_INT - integers only, use when expecting only numbers.
156 define('PARAM_INT', 'int');
159 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
161 define('PARAM_LANG', 'lang');
164 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
165 * others! Implies PARAM_URL!)
167 define('PARAM_LOCALURL', 'localurl');
170 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
172 define('PARAM_NOTAGS', 'notags');
175 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
176 * traversals note: the leading slash is not removed, window drive letter is not allowed
178 define('PARAM_PATH', 'path');
181 * PARAM_PEM - Privacy Enhanced Mail format
183 define('PARAM_PEM', 'pem');
186 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
188 define('PARAM_PERMISSION', 'permission');
191 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
193 define('PARAM_RAW', 'raw');
196 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
198 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
201 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
203 define('PARAM_SAFEDIR', 'safedir');
206 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
208 define('PARAM_SAFEPATH', 'safepath');
211 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
213 define('PARAM_SEQUENCE', 'sequence');
216 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
218 define('PARAM_TAG', 'tag');
221 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
223 define('PARAM_TAGLIST', 'taglist');
226 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
228 define('PARAM_TEXT', 'text');
231 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
233 define('PARAM_THEME', 'theme');
236 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
237 * http://localhost.localdomain/ is ok.
239 define('PARAM_URL', 'url');
242 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
243 * accounts, do NOT use when syncing with external systems!!
245 define('PARAM_USERNAME', 'username');
248 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
250 define('PARAM_STRINGID', 'stringid');
252 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
254 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
255 * It was one of the first types, that is why it is abused so much ;-)
256 * @deprecated since 2.0
258 define('PARAM_CLEAN', 'clean');
261 * PARAM_INTEGER - deprecated alias for PARAM_INT
262 * @deprecated since 2.0
264 define('PARAM_INTEGER', 'int');
267 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
268 * @deprecated since 2.0
270 define('PARAM_NUMBER', 'float');
273 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
274 * NOTE: originally alias for PARAM_APLHA
275 * @deprecated since 2.0
277 define('PARAM_ACTION', 'alphanumext');
280 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
281 * NOTE: originally alias for PARAM_APLHA
282 * @deprecated since 2.0
284 define('PARAM_FORMAT', 'alphanumext');
287 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
288 * @deprecated since 2.0
290 define('PARAM_MULTILANG', 'text');
293 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
294 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
295 * America/Port-au-Prince)
297 define('PARAM_TIMEZONE', 'timezone');
300 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
302 define('PARAM_CLEANFILE', 'file');
305 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
306 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
307 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308 * NOTE: numbers and underscores are strongly discouraged in plugin names!
310 define('PARAM_COMPONENT', 'component');
313 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
314 * It is usually used together with context id and component.
315 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
317 define('PARAM_AREA', 'area');
320 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
321 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
324 define('PARAM_PLUGIN', 'plugin');
327 // Web Services.
330 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
332 define('VALUE_REQUIRED', 1);
335 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
337 define('VALUE_OPTIONAL', 2);
340 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
342 define('VALUE_DEFAULT', 0);
345 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
347 define('NULL_NOT_ALLOWED', false);
350 * NULL_ALLOWED - the parameter can be set to null in the database
352 define('NULL_ALLOWED', true);
354 // Page types.
357 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
359 define('PAGE_COURSE_VIEW', 'course-view');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363 /** Get remote addr constant */
364 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
366 * GETREMOTEADDR_SKIP_DEFAULT defines the default behavior remote IP address validation.
368 define('GETREMOTEADDR_SKIP_DEFAULT', GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR|GETREMOTEADDR_SKIP_HTTP_CLIENT_IP);
370 // Blog access level constant declaration.
371 define ('BLOG_USER_LEVEL', 1);
372 define ('BLOG_GROUP_LEVEL', 2);
373 define ('BLOG_COURSE_LEVEL', 3);
374 define ('BLOG_SITE_LEVEL', 4);
375 define ('BLOG_GLOBAL_LEVEL', 5);
378 // Tag constants.
380 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
381 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
382 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
384 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
386 define('TAG_MAX_LENGTH', 50);
388 // Password policy constants.
389 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
390 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
391 define ('PASSWORD_DIGITS', '0123456789');
392 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
394 // Feature constants.
395 // Used for plugin_supports() to report features that are, or are not, supported by a module.
397 /** True if module can provide a grade */
398 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
399 /** True if module supports outcomes */
400 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
401 /** True if module supports advanced grading methods */
402 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
403 /** True if module controls the grade visibility over the gradebook */
404 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
405 /** True if module supports plagiarism plugins */
406 define('FEATURE_PLAGIARISM', 'plagiarism');
408 /** True if module has code to track whether somebody viewed it */
409 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
410 /** True if module has custom completion rules */
411 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
413 /** True if module has no 'view' page (like label) */
414 define('FEATURE_NO_VIEW_LINK', 'viewlink');
415 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
416 define('FEATURE_IDNUMBER', 'idnumber');
417 /** True if module supports groups */
418 define('FEATURE_GROUPS', 'groups');
419 /** True if module supports groupings */
420 define('FEATURE_GROUPINGS', 'groupings');
422 * True if module supports groupmembersonly (which no longer exists)
423 * @deprecated Since Moodle 2.8
425 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
427 /** Type of module */
428 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
429 /** True if module supports intro editor */
430 define('FEATURE_MOD_INTRO', 'mod_intro');
431 /** True if module has default completion */
432 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
434 define('FEATURE_COMMENT', 'comment');
436 define('FEATURE_RATE', 'rate');
437 /** True if module supports backup/restore of moodle2 format */
438 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
440 /** True if module can show description on course main page */
441 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
443 /** True if module uses the question bank */
444 define('FEATURE_USES_QUESTIONS', 'usesquestions');
447 * Maximum filename char size
449 define('MAX_FILENAME_SIZE', 100);
451 /** Unspecified module archetype */
452 define('MOD_ARCHETYPE_OTHER', 0);
453 /** Resource-like type module */
454 define('MOD_ARCHETYPE_RESOURCE', 1);
455 /** Assignment module archetype */
456 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
457 /** System (not user-addable) module archetype */
458 define('MOD_ARCHETYPE_SYSTEM', 3);
461 * Return this from modname_get_types callback to use default display in activity chooser.
462 * Deprecated, will be removed in 3.5, TODO MDL-53697.
463 * @deprecated since Moodle 3.1
465 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
468 * Security token used for allowing access
469 * from external application such as web services.
470 * Scripts do not use any session, performance is relatively
471 * low because we need to load access info in each request.
472 * Scripts are executed in parallel.
474 define('EXTERNAL_TOKEN_PERMANENT', 0);
477 * Security token used for allowing access
478 * of embedded applications, the code is executed in the
479 * active user session. Token is invalidated after user logs out.
480 * Scripts are executed serially - normal session locking is used.
482 define('EXTERNAL_TOKEN_EMBEDDED', 1);
485 * The home page should be the site home
487 define('HOMEPAGE_SITE', 0);
489 * The home page should be the users my page
491 define('HOMEPAGE_MY', 1);
493 * The home page can be chosen by the user
495 define('HOMEPAGE_USER', 2);
498 * Hub directory url (should be moodle.org)
500 define('HUB_HUBDIRECTORYURL', "https://hubdirectory.moodle.org");
504 * Moodle.net url (should be moodle.net)
506 define('HUB_MOODLEORGHUBURL', "https://moodle.net");
507 define('HUB_OLDMOODLEORGHUBURL', "http://hub.moodle.org");
510 * Moodle mobile app service name
512 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
515 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
517 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
520 * Course display settings: display all sections on one page.
522 define('COURSE_DISPLAY_SINGLEPAGE', 0);
524 * Course display settings: split pages into a page per section.
526 define('COURSE_DISPLAY_MULTIPAGE', 1);
529 * Authentication constant: String used in password field when password is not stored.
531 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
534 * Email from header to never include via information.
536 define('EMAIL_VIA_NEVER', 0);
539 * Email from header to always include via information.
541 define('EMAIL_VIA_ALWAYS', 1);
544 * Email from header to only include via information if the address is no-reply.
546 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
548 // PARAMETER HANDLING.
551 * Returns a particular value for the named variable, taken from
552 * POST or GET. If the parameter doesn't exist then an error is
553 * thrown because we require this variable.
555 * This function should be used to initialise all required values
556 * in a script that are based on parameters. Usually it will be
557 * used like this:
558 * $id = required_param('id', PARAM_INT);
560 * Please note the $type parameter is now required and the value can not be array.
562 * @param string $parname the name of the page parameter we want
563 * @param string $type expected type of parameter
564 * @return mixed
565 * @throws coding_exception
567 function required_param($parname, $type) {
568 if (func_num_args() != 2 or empty($parname) or empty($type)) {
569 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
571 // POST has precedence.
572 if (isset($_POST[$parname])) {
573 $param = $_POST[$parname];
574 } else if (isset($_GET[$parname])) {
575 $param = $_GET[$parname];
576 } else {
577 print_error('missingparam', '', '', $parname);
580 if (is_array($param)) {
581 debugging('Invalid array parameter detected in required_param(): '.$parname);
582 // TODO: switch to fatal error in Moodle 2.3.
583 return required_param_array($parname, $type);
586 return clean_param($param, $type);
590 * Returns a particular array value for the named variable, taken from
591 * POST or GET. If the parameter doesn't exist then an error is
592 * thrown because we require this variable.
594 * This function should be used to initialise all required values
595 * in a script that are based on parameters. Usually it will be
596 * used like this:
597 * $ids = required_param_array('ids', PARAM_INT);
599 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
601 * @param string $parname the name of the page parameter we want
602 * @param string $type expected type of parameter
603 * @return array
604 * @throws coding_exception
606 function required_param_array($parname, $type) {
607 if (func_num_args() != 2 or empty($parname) or empty($type)) {
608 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
610 // POST has precedence.
611 if (isset($_POST[$parname])) {
612 $param = $_POST[$parname];
613 } else if (isset($_GET[$parname])) {
614 $param = $_GET[$parname];
615 } else {
616 print_error('missingparam', '', '', $parname);
618 if (!is_array($param)) {
619 print_error('missingparam', '', '', $parname);
622 $result = array();
623 foreach ($param as $key => $value) {
624 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
625 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
626 continue;
628 $result[$key] = clean_param($value, $type);
631 return $result;
635 * Returns a particular value for the named variable, taken from
636 * POST or GET, otherwise returning a given default.
638 * This function should be used to initialise all optional values
639 * in a script that are based on parameters. Usually it will be
640 * used like this:
641 * $name = optional_param('name', 'Fred', PARAM_TEXT);
643 * Please note the $type parameter is now required and the value can not be array.
645 * @param string $parname the name of the page parameter we want
646 * @param mixed $default the default value to return if nothing is found
647 * @param string $type expected type of parameter
648 * @return mixed
649 * @throws coding_exception
651 function optional_param($parname, $default, $type) {
652 if (func_num_args() != 3 or empty($parname) or empty($type)) {
653 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
656 // POST has precedence.
657 if (isset($_POST[$parname])) {
658 $param = $_POST[$parname];
659 } else if (isset($_GET[$parname])) {
660 $param = $_GET[$parname];
661 } else {
662 return $default;
665 if (is_array($param)) {
666 debugging('Invalid array parameter detected in required_param(): '.$parname);
667 // TODO: switch to $default in Moodle 2.3.
668 return optional_param_array($parname, $default, $type);
671 return clean_param($param, $type);
675 * Returns a particular array value for the named variable, taken from
676 * POST or GET, otherwise returning a given default.
678 * This function should be used to initialise all optional values
679 * in a script that are based on parameters. Usually it will be
680 * used like this:
681 * $ids = optional_param('id', array(), PARAM_INT);
683 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
685 * @param string $parname the name of the page parameter we want
686 * @param mixed $default the default value to return if nothing is found
687 * @param string $type expected type of parameter
688 * @return array
689 * @throws coding_exception
691 function optional_param_array($parname, $default, $type) {
692 if (func_num_args() != 3 or empty($parname) or empty($type)) {
693 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
696 // POST has precedence.
697 if (isset($_POST[$parname])) {
698 $param = $_POST[$parname];
699 } else if (isset($_GET[$parname])) {
700 $param = $_GET[$parname];
701 } else {
702 return $default;
704 if (!is_array($param)) {
705 debugging('optional_param_array() expects array parameters only: '.$parname);
706 return $default;
709 $result = array();
710 foreach ($param as $key => $value) {
711 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
712 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
713 continue;
715 $result[$key] = clean_param($value, $type);
718 return $result;
722 * Strict validation of parameter values, the values are only converted
723 * to requested PHP type. Internally it is using clean_param, the values
724 * before and after cleaning must be equal - otherwise
725 * an invalid_parameter_exception is thrown.
726 * Objects and classes are not accepted.
728 * @param mixed $param
729 * @param string $type PARAM_ constant
730 * @param bool $allownull are nulls valid value?
731 * @param string $debuginfo optional debug information
732 * @return mixed the $param value converted to PHP type
733 * @throws invalid_parameter_exception if $param is not of given type
735 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
736 if (is_null($param)) {
737 if ($allownull == NULL_ALLOWED) {
738 return null;
739 } else {
740 throw new invalid_parameter_exception($debuginfo);
743 if (is_array($param) or is_object($param)) {
744 throw new invalid_parameter_exception($debuginfo);
747 $cleaned = clean_param($param, $type);
749 if ($type == PARAM_FLOAT) {
750 // Do not detect precision loss here.
751 if (is_float($param) or is_int($param)) {
752 // These always fit.
753 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
754 throw new invalid_parameter_exception($debuginfo);
756 } else if ((string)$param !== (string)$cleaned) {
757 // Conversion to string is usually lossless.
758 throw new invalid_parameter_exception($debuginfo);
761 return $cleaned;
765 * Makes sure array contains only the allowed types, this function does not validate array key names!
767 * <code>
768 * $options = clean_param($options, PARAM_INT);
769 * </code>
771 * @param array $param the variable array we are cleaning
772 * @param string $type expected format of param after cleaning.
773 * @param bool $recursive clean recursive arrays
774 * @return array
775 * @throws coding_exception
777 function clean_param_array(array $param = null, $type, $recursive = false) {
778 // Convert null to empty array.
779 $param = (array)$param;
780 foreach ($param as $key => $value) {
781 if (is_array($value)) {
782 if ($recursive) {
783 $param[$key] = clean_param_array($value, $type, true);
784 } else {
785 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
787 } else {
788 $param[$key] = clean_param($value, $type);
791 return $param;
795 * Used by {@link optional_param()} and {@link required_param()} to
796 * clean the variables and/or cast to specific types, based on
797 * an options field.
798 * <code>
799 * $course->format = clean_param($course->format, PARAM_ALPHA);
800 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
801 * </code>
803 * @param mixed $param the variable we are cleaning
804 * @param string $type expected format of param after cleaning.
805 * @return mixed
806 * @throws coding_exception
808 function clean_param($param, $type) {
809 global $CFG;
811 if (is_array($param)) {
812 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
813 } else if (is_object($param)) {
814 if (method_exists($param, '__toString')) {
815 $param = $param->__toString();
816 } else {
817 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
821 switch ($type) {
822 case PARAM_RAW:
823 // No cleaning at all.
824 $param = fix_utf8($param);
825 return $param;
827 case PARAM_RAW_TRIMMED:
828 // No cleaning, but strip leading and trailing whitespace.
829 $param = fix_utf8($param);
830 return trim($param);
832 case PARAM_CLEAN:
833 // General HTML cleaning, try to use more specific type if possible this is deprecated!
834 // Please use more specific type instead.
835 if (is_numeric($param)) {
836 return $param;
838 $param = fix_utf8($param);
839 // Sweep for scripts, etc.
840 return clean_text($param);
842 case PARAM_CLEANHTML:
843 // Clean html fragment.
844 $param = fix_utf8($param);
845 // Sweep for scripts, etc.
846 $param = clean_text($param, FORMAT_HTML);
847 return trim($param);
849 case PARAM_INT:
850 // Convert to integer.
851 return (int)$param;
853 case PARAM_FLOAT:
854 // Convert to float.
855 return (float)$param;
857 case PARAM_ALPHA:
858 // Remove everything not `a-z`.
859 return preg_replace('/[^a-zA-Z]/i', '', $param);
861 case PARAM_ALPHAEXT:
862 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
863 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
865 case PARAM_ALPHANUM:
866 // Remove everything not `a-zA-Z0-9`.
867 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
869 case PARAM_ALPHANUMEXT:
870 // Remove everything not `a-zA-Z0-9_-`.
871 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
873 case PARAM_SEQUENCE:
874 // Remove everything not `0-9,`.
875 return preg_replace('/[^0-9,]/i', '', $param);
877 case PARAM_BOOL:
878 // Convert to 1 or 0.
879 $tempstr = strtolower($param);
880 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
881 $param = 1;
882 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
883 $param = 0;
884 } else {
885 $param = empty($param) ? 0 : 1;
887 return $param;
889 case PARAM_NOTAGS:
890 // Strip all tags.
891 $param = fix_utf8($param);
892 return strip_tags($param);
894 case PARAM_TEXT:
895 // Leave only tags needed for multilang.
896 $param = fix_utf8($param);
897 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
898 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
899 do {
900 if (strpos($param, '</lang>') !== false) {
901 // Old and future mutilang syntax.
902 $param = strip_tags($param, '<lang>');
903 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
904 break;
906 $open = false;
907 foreach ($matches[0] as $match) {
908 if ($match === '</lang>') {
909 if ($open) {
910 $open = false;
911 continue;
912 } else {
913 break 2;
916 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
917 break 2;
918 } else {
919 $open = true;
922 if ($open) {
923 break;
925 return $param;
927 } else if (strpos($param, '</span>') !== false) {
928 // Current problematic multilang syntax.
929 $param = strip_tags($param, '<span>');
930 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
931 break;
933 $open = false;
934 foreach ($matches[0] as $match) {
935 if ($match === '</span>') {
936 if ($open) {
937 $open = false;
938 continue;
939 } else {
940 break 2;
943 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
944 break 2;
945 } else {
946 $open = true;
949 if ($open) {
950 break;
952 return $param;
954 } while (false);
955 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
956 return strip_tags($param);
958 case PARAM_COMPONENT:
959 // We do not want any guessing here, either the name is correct or not
960 // please note only normalised component names are accepted.
961 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
962 return '';
964 if (strpos($param, '__') !== false) {
965 return '';
967 if (strpos($param, 'mod_') === 0) {
968 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
969 if (substr_count($param, '_') != 1) {
970 return '';
973 return $param;
975 case PARAM_PLUGIN:
976 case PARAM_AREA:
977 // We do not want any guessing here, either the name is correct or not.
978 if (!is_valid_plugin_name($param)) {
979 return '';
981 return $param;
983 case PARAM_SAFEDIR:
984 // Remove everything not a-zA-Z0-9_- .
985 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
987 case PARAM_SAFEPATH:
988 // Remove everything not a-zA-Z0-9/_- .
989 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
991 case PARAM_FILE:
992 // Strip all suspicious characters from filename.
993 $param = fix_utf8($param);
994 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
995 if ($param === '.' || $param === '..') {
996 $param = '';
998 return $param;
1000 case PARAM_PATH:
1001 // Strip all suspicious characters from file path.
1002 $param = fix_utf8($param);
1003 $param = str_replace('\\', '/', $param);
1005 // Explode the path and clean each element using the PARAM_FILE rules.
1006 $breadcrumb = explode('/', $param);
1007 foreach ($breadcrumb as $key => $crumb) {
1008 if ($crumb === '.' && $key === 0) {
1009 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1010 } else {
1011 $crumb = clean_param($crumb, PARAM_FILE);
1013 $breadcrumb[$key] = $crumb;
1015 $param = implode('/', $breadcrumb);
1017 // Remove multiple current path (./././) and multiple slashes (///).
1018 $param = preg_replace('~//+~', '/', $param);
1019 $param = preg_replace('~/(\./)+~', '/', $param);
1020 return $param;
1022 case PARAM_HOST:
1023 // Allow FQDN or IPv4 dotted quad.
1024 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1025 // Match ipv4 dotted quad.
1026 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1027 // Confirm values are ok.
1028 if ( $match[0] > 255
1029 || $match[1] > 255
1030 || $match[3] > 255
1031 || $match[4] > 255 ) {
1032 // Hmmm, what kind of dotted quad is this?
1033 $param = '';
1035 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1036 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1037 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1039 // All is ok - $param is respected.
1040 } else {
1041 // All is not ok...
1042 $param='';
1044 return $param;
1046 case PARAM_URL:
1047 // Allow safe urls.
1048 $param = fix_utf8($param);
1049 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1050 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1051 // All is ok, param is respected.
1052 } else {
1053 // Not really ok.
1054 $param ='';
1056 return $param;
1058 case PARAM_LOCALURL:
1059 // Allow http absolute, root relative and relative URLs within wwwroot.
1060 $param = clean_param($param, PARAM_URL);
1061 if (!empty($param)) {
1063 if ($param === $CFG->wwwroot) {
1064 // Exact match;
1065 } else if (preg_match(':^/:', $param)) {
1066 // Root-relative, ok!
1067 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1068 // Absolute, and matches our wwwroot.
1069 } else {
1070 // Relative - let's make sure there are no tricks.
1071 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1072 // Looks ok.
1073 } else {
1074 $param = '';
1078 return $param;
1080 case PARAM_PEM:
1081 $param = trim($param);
1082 // PEM formatted strings may contain letters/numbers and the symbols:
1083 // forward slash: /
1084 // plus sign: +
1085 // equal sign: =
1086 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1087 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1088 list($wholething, $body) = $matches;
1089 unset($wholething, $matches);
1090 $b64 = clean_param($body, PARAM_BASE64);
1091 if (!empty($b64)) {
1092 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1093 } else {
1094 return '';
1097 return '';
1099 case PARAM_BASE64:
1100 if (!empty($param)) {
1101 // PEM formatted strings may contain letters/numbers and the symbols
1102 // forward slash: /
1103 // plus sign: +
1104 // equal sign: =.
1105 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1106 return '';
1108 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1109 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1110 // than (or equal to) 64 characters long.
1111 for ($i=0, $j=count($lines); $i < $j; $i++) {
1112 if ($i + 1 == $j) {
1113 if (64 < strlen($lines[$i])) {
1114 return '';
1116 continue;
1119 if (64 != strlen($lines[$i])) {
1120 return '';
1123 return implode("\n", $lines);
1124 } else {
1125 return '';
1128 case PARAM_TAG:
1129 $param = fix_utf8($param);
1130 // Please note it is not safe to use the tag name directly anywhere,
1131 // it must be processed with s(), urlencode() before embedding anywhere.
1132 // Remove some nasties.
1133 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1134 // Convert many whitespace chars into one.
1135 $param = preg_replace('/\s+/u', ' ', $param);
1136 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1137 return $param;
1139 case PARAM_TAGLIST:
1140 $param = fix_utf8($param);
1141 $tags = explode(',', $param);
1142 $result = array();
1143 foreach ($tags as $tag) {
1144 $res = clean_param($tag, PARAM_TAG);
1145 if ($res !== '') {
1146 $result[] = $res;
1149 if ($result) {
1150 return implode(',', $result);
1151 } else {
1152 return '';
1155 case PARAM_CAPABILITY:
1156 if (get_capability_info($param)) {
1157 return $param;
1158 } else {
1159 return '';
1162 case PARAM_PERMISSION:
1163 $param = (int)$param;
1164 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1165 return $param;
1166 } else {
1167 return CAP_INHERIT;
1170 case PARAM_AUTH:
1171 $param = clean_param($param, PARAM_PLUGIN);
1172 if (empty($param)) {
1173 return '';
1174 } else if (exists_auth_plugin($param)) {
1175 return $param;
1176 } else {
1177 return '';
1180 case PARAM_LANG:
1181 $param = clean_param($param, PARAM_SAFEDIR);
1182 if (get_string_manager()->translation_exists($param)) {
1183 return $param;
1184 } else {
1185 // Specified language is not installed or param malformed.
1186 return '';
1189 case PARAM_THEME:
1190 $param = clean_param($param, PARAM_PLUGIN);
1191 if (empty($param)) {
1192 return '';
1193 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1194 return $param;
1195 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1196 return $param;
1197 } else {
1198 // Specified theme is not installed.
1199 return '';
1202 case PARAM_USERNAME:
1203 $param = fix_utf8($param);
1204 $param = trim($param);
1205 // Convert uppercase to lowercase MDL-16919.
1206 $param = core_text::strtolower($param);
1207 if (empty($CFG->extendedusernamechars)) {
1208 $param = str_replace(" " , "", $param);
1209 // Regular expression, eliminate all chars EXCEPT:
1210 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1211 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1213 return $param;
1215 case PARAM_EMAIL:
1216 $param = fix_utf8($param);
1217 if (validate_email($param)) {
1218 return $param;
1219 } else {
1220 return '';
1223 case PARAM_STRINGID:
1224 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1225 return $param;
1226 } else {
1227 return '';
1230 case PARAM_TIMEZONE:
1231 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1232 $param = fix_utf8($param);
1233 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1234 if (preg_match($timezonepattern, $param)) {
1235 return $param;
1236 } else {
1237 return '';
1240 default:
1241 // Doh! throw error, switched parameters in optional_param or another serious problem.
1242 print_error("unknownparamtype", '', '', $type);
1247 * Whether the PARAM_* type is compatible in RTL.
1249 * Being compatible with RTL means that the data they contain can flow
1250 * from right-to-left or left-to-right without compromising the user experience.
1252 * Take URLs for example, they are not RTL compatible as they should always
1253 * flow from the left to the right. This also applies to numbers, email addresses,
1254 * configuration snippets, base64 strings, etc...
1256 * This function tries to best guess which parameters can contain localised strings.
1258 * @param string $paramtype Constant PARAM_*.
1259 * @return bool
1261 function is_rtl_compatible($paramtype) {
1262 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1266 * Makes sure the data is using valid utf8, invalid characters are discarded.
1268 * Note: this function is not intended for full objects with methods and private properties.
1270 * @param mixed $value
1271 * @return mixed with proper utf-8 encoding
1273 function fix_utf8($value) {
1274 if (is_null($value) or $value === '') {
1275 return $value;
1277 } else if (is_string($value)) {
1278 if ((string)(int)$value === $value) {
1279 // Shortcut.
1280 return $value;
1282 // No null bytes expected in our data, so let's remove it.
1283 $value = str_replace("\0", '', $value);
1285 // Note: this duplicates min_fix_utf8() intentionally.
1286 static $buggyiconv = null;
1287 if ($buggyiconv === null) {
1288 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1291 if ($buggyiconv) {
1292 if (function_exists('mb_convert_encoding')) {
1293 $subst = mb_substitute_character();
1294 mb_substitute_character('');
1295 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1296 mb_substitute_character($subst);
1298 } else {
1299 // Warn admins on admin/index.php page.
1300 $result = $value;
1303 } else {
1304 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1307 return $result;
1309 } else if (is_array($value)) {
1310 foreach ($value as $k => $v) {
1311 $value[$k] = fix_utf8($v);
1313 return $value;
1315 } else if (is_object($value)) {
1316 // Do not modify original.
1317 $value = clone($value);
1318 foreach ($value as $k => $v) {
1319 $value->$k = fix_utf8($v);
1321 return $value;
1323 } else {
1324 // This is some other type, no utf-8 here.
1325 return $value;
1330 * Return true if given value is integer or string with integer value
1332 * @param mixed $value String or Int
1333 * @return bool true if number, false if not
1335 function is_number($value) {
1336 if (is_int($value)) {
1337 return true;
1338 } else if (is_string($value)) {
1339 return ((string)(int)$value) === $value;
1340 } else {
1341 return false;
1346 * Returns host part from url.
1348 * @param string $url full url
1349 * @return string host, null if not found
1351 function get_host_from_url($url) {
1352 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1353 if ($matches) {
1354 return $matches[1];
1356 return null;
1360 * Tests whether anything was returned by text editor
1362 * This function is useful for testing whether something you got back from
1363 * the HTML editor actually contains anything. Sometimes the HTML editor
1364 * appear to be empty, but actually you get back a <br> tag or something.
1366 * @param string $string a string containing HTML.
1367 * @return boolean does the string contain any actual content - that is text,
1368 * images, objects, etc.
1370 function html_is_blank($string) {
1371 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1375 * Set a key in global configuration
1377 * Set a key/value pair in both this session's {@link $CFG} global variable
1378 * and in the 'config' database table for future sessions.
1380 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1381 * In that case it doesn't affect $CFG.
1383 * A NULL value will delete the entry.
1385 * NOTE: this function is called from lib/db/upgrade.php
1387 * @param string $name the key to set
1388 * @param string $value the value to set (without magic quotes)
1389 * @param string $plugin (optional) the plugin scope, default null
1390 * @return bool true or exception
1392 function set_config($name, $value, $plugin=null) {
1393 global $CFG, $DB;
1395 if (empty($plugin)) {
1396 if (!array_key_exists($name, $CFG->config_php_settings)) {
1397 // So it's defined for this invocation at least.
1398 if (is_null($value)) {
1399 unset($CFG->$name);
1400 } else {
1401 // Settings from db are always strings.
1402 $CFG->$name = (string)$value;
1406 if ($DB->get_field('config', 'name', array('name' => $name))) {
1407 if ($value === null) {
1408 $DB->delete_records('config', array('name' => $name));
1409 } else {
1410 $DB->set_field('config', 'value', $value, array('name' => $name));
1412 } else {
1413 if ($value !== null) {
1414 $config = new stdClass();
1415 $config->name = $name;
1416 $config->value = $value;
1417 $DB->insert_record('config', $config, false);
1420 if ($name === 'siteidentifier') {
1421 cache_helper::update_site_identifier($value);
1423 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1424 } else {
1425 // Plugin scope.
1426 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1427 if ($value===null) {
1428 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1429 } else {
1430 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1432 } else {
1433 if ($value !== null) {
1434 $config = new stdClass();
1435 $config->plugin = $plugin;
1436 $config->name = $name;
1437 $config->value = $value;
1438 $DB->insert_record('config_plugins', $config, false);
1441 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1444 return true;
1448 * Get configuration values from the global config table
1449 * or the config_plugins table.
1451 * If called with one parameter, it will load all the config
1452 * variables for one plugin, and return them as an object.
1454 * If called with 2 parameters it will return a string single
1455 * value or false if the value is not found.
1457 * NOTE: this function is called from lib/db/upgrade.php
1459 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1460 * that we need only fetch it once per request.
1461 * @param string $plugin full component name
1462 * @param string $name default null
1463 * @return mixed hash-like object or single value, return false no config found
1464 * @throws dml_exception
1466 function get_config($plugin, $name = null) {
1467 global $CFG, $DB;
1469 static $siteidentifier = null;
1471 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1472 $forced =& $CFG->config_php_settings;
1473 $iscore = true;
1474 $plugin = 'core';
1475 } else {
1476 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1477 $forced =& $CFG->forced_plugin_settings[$plugin];
1478 } else {
1479 $forced = array();
1481 $iscore = false;
1484 if ($siteidentifier === null) {
1485 try {
1486 // This may fail during installation.
1487 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1488 // install the database.
1489 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1490 } catch (dml_exception $ex) {
1491 // Set siteidentifier to false. We don't want to trip this continually.
1492 $siteidentifier = false;
1493 throw $ex;
1497 if (!empty($name)) {
1498 if (array_key_exists($name, $forced)) {
1499 return (string)$forced[$name];
1500 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1501 return $siteidentifier;
1505 $cache = cache::make('core', 'config');
1506 $result = $cache->get($plugin);
1507 if ($result === false) {
1508 // The user is after a recordset.
1509 if (!$iscore) {
1510 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1511 } else {
1512 // This part is not really used any more, but anyway...
1513 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1515 $cache->set($plugin, $result);
1518 if (!empty($name)) {
1519 if (array_key_exists($name, $result)) {
1520 return $result[$name];
1522 return false;
1525 if ($plugin === 'core') {
1526 $result['siteidentifier'] = $siteidentifier;
1529 foreach ($forced as $key => $value) {
1530 if (is_null($value) or is_array($value) or is_object($value)) {
1531 // We do not want any extra mess here, just real settings that could be saved in db.
1532 unset($result[$key]);
1533 } else {
1534 // Convert to string as if it went through the DB.
1535 $result[$key] = (string)$value;
1539 return (object)$result;
1543 * Removes a key from global configuration.
1545 * NOTE: this function is called from lib/db/upgrade.php
1547 * @param string $name the key to set
1548 * @param string $plugin (optional) the plugin scope
1549 * @return boolean whether the operation succeeded.
1551 function unset_config($name, $plugin=null) {
1552 global $CFG, $DB;
1554 if (empty($plugin)) {
1555 unset($CFG->$name);
1556 $DB->delete_records('config', array('name' => $name));
1557 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1558 } else {
1559 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1560 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1563 return true;
1567 * Remove all the config variables for a given plugin.
1569 * NOTE: this function is called from lib/db/upgrade.php
1571 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1572 * @return boolean whether the operation succeeded.
1574 function unset_all_config_for_plugin($plugin) {
1575 global $DB;
1576 // Delete from the obvious config_plugins first.
1577 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1578 // Next delete any suspect settings from config.
1579 $like = $DB->sql_like('name', '?', true, true, false, '|');
1580 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1581 $DB->delete_records_select('config', $like, $params);
1582 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1583 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1585 return true;
1589 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1591 * All users are verified if they still have the necessary capability.
1593 * @param string $value the value of the config setting.
1594 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1595 * @param bool $includeadmins include administrators.
1596 * @return array of user objects.
1598 function get_users_from_config($value, $capability, $includeadmins = true) {
1599 if (empty($value) or $value === '$@NONE@$') {
1600 return array();
1603 // We have to make sure that users still have the necessary capability,
1604 // it should be faster to fetch them all first and then test if they are present
1605 // instead of validating them one-by-one.
1606 $users = get_users_by_capability(context_system::instance(), $capability);
1607 if ($includeadmins) {
1608 $admins = get_admins();
1609 foreach ($admins as $admin) {
1610 $users[$admin->id] = $admin;
1614 if ($value === '$@ALL@$') {
1615 return $users;
1618 $result = array(); // Result in correct order.
1619 $allowed = explode(',', $value);
1620 foreach ($allowed as $uid) {
1621 if (isset($users[$uid])) {
1622 $user = $users[$uid];
1623 $result[$user->id] = $user;
1627 return $result;
1632 * Invalidates browser caches and cached data in temp.
1634 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1635 * {@link phpunit_util::reset_dataroot()}
1637 * @return void
1639 function purge_all_caches() {
1640 global $CFG, $DB;
1642 reset_text_filters_cache();
1643 js_reset_all_caches();
1644 theme_reset_all_caches();
1645 get_string_manager()->reset_caches();
1646 core_text::reset_caches();
1647 if (class_exists('core_plugin_manager')) {
1648 core_plugin_manager::reset_caches();
1651 // Bump up cacherev field for all courses.
1652 try {
1653 increment_revision_number('course', 'cacherev', '');
1654 } catch (moodle_exception $e) {
1655 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1658 $DB->reset_caches();
1659 cache_helper::purge_all();
1661 // Purge all other caches: rss, simplepie, etc.
1662 clearstatcache();
1663 remove_dir($CFG->cachedir.'', true);
1665 // Make sure cache dir is writable, throws exception if not.
1666 make_cache_directory('');
1668 // This is the only place where we purge local caches, we are only adding files there.
1669 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1670 remove_dir($CFG->localcachedir, true);
1671 set_config('localcachedirpurged', time());
1672 make_localcache_directory('', true);
1673 \core\task\manager::clear_static_caches();
1677 * Get volatile flags
1679 * @param string $type
1680 * @param int $changedsince default null
1681 * @return array records array
1683 function get_cache_flags($type, $changedsince = null) {
1684 global $DB;
1686 $params = array('type' => $type, 'expiry' => time());
1687 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1688 if ($changedsince !== null) {
1689 $params['changedsince'] = $changedsince;
1690 $sqlwhere .= " AND timemodified > :changedsince";
1692 $cf = array();
1693 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1694 foreach ($flags as $flag) {
1695 $cf[$flag->name] = $flag->value;
1698 return $cf;
1702 * Get volatile flags
1704 * @param string $type
1705 * @param string $name
1706 * @param int $changedsince default null
1707 * @return string|false The cache flag value or false
1709 function get_cache_flag($type, $name, $changedsince=null) {
1710 global $DB;
1712 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1714 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1715 if ($changedsince !== null) {
1716 $params['changedsince'] = $changedsince;
1717 $sqlwhere .= " AND timemodified > :changedsince";
1720 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1724 * Set a volatile flag
1726 * @param string $type the "type" namespace for the key
1727 * @param string $name the key to set
1728 * @param string $value the value to set (without magic quotes) - null will remove the flag
1729 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1730 * @return bool Always returns true
1732 function set_cache_flag($type, $name, $value, $expiry = null) {
1733 global $DB;
1735 $timemodified = time();
1736 if ($expiry === null || $expiry < $timemodified) {
1737 $expiry = $timemodified + 24 * 60 * 60;
1738 } else {
1739 $expiry = (int)$expiry;
1742 if ($value === null) {
1743 unset_cache_flag($type, $name);
1744 return true;
1747 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1748 // This is a potential problem in DEBUG_DEVELOPER.
1749 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1750 return true; // No need to update.
1752 $f->value = $value;
1753 $f->expiry = $expiry;
1754 $f->timemodified = $timemodified;
1755 $DB->update_record('cache_flags', $f);
1756 } else {
1757 $f = new stdClass();
1758 $f->flagtype = $type;
1759 $f->name = $name;
1760 $f->value = $value;
1761 $f->expiry = $expiry;
1762 $f->timemodified = $timemodified;
1763 $DB->insert_record('cache_flags', $f);
1765 return true;
1769 * Removes a single volatile flag
1771 * @param string $type the "type" namespace for the key
1772 * @param string $name the key to set
1773 * @return bool
1775 function unset_cache_flag($type, $name) {
1776 global $DB;
1777 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1778 return true;
1782 * Garbage-collect volatile flags
1784 * @return bool Always returns true
1786 function gc_cache_flags() {
1787 global $DB;
1788 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1789 return true;
1792 // USER PREFERENCE API.
1795 * Refresh user preference cache. This is used most often for $USER
1796 * object that is stored in session, but it also helps with performance in cron script.
1798 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1800 * @package core
1801 * @category preference
1802 * @access public
1803 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1804 * @param int $cachelifetime Cache life time on the current page (in seconds)
1805 * @throws coding_exception
1806 * @return null
1808 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1809 global $DB;
1810 // Static cache, we need to check on each page load, not only every 2 minutes.
1811 static $loadedusers = array();
1813 if (!isset($user->id)) {
1814 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1817 if (empty($user->id) or isguestuser($user->id)) {
1818 // No permanent storage for not-logged-in users and guest.
1819 if (!isset($user->preference)) {
1820 $user->preference = array();
1822 return;
1825 $timenow = time();
1827 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1828 // Already loaded at least once on this page. Are we up to date?
1829 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1830 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1831 return;
1833 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1834 // No change since the lastcheck on this page.
1835 $user->preference['_lastloaded'] = $timenow;
1836 return;
1840 // OK, so we have to reload all preferences.
1841 $loadedusers[$user->id] = true;
1842 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1843 $user->preference['_lastloaded'] = $timenow;
1847 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1849 * NOTE: internal function, do not call from other code.
1851 * @package core
1852 * @access private
1853 * @param integer $userid the user whose prefs were changed.
1855 function mark_user_preferences_changed($userid) {
1856 global $CFG;
1858 if (empty($userid) or isguestuser($userid)) {
1859 // No cache flags for guest and not-logged-in users.
1860 return;
1863 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1867 * Sets a preference for the specified user.
1869 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1871 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1873 * @package core
1874 * @category preference
1875 * @access public
1876 * @param string $name The key to set as preference for the specified user
1877 * @param string $value The value to set for the $name key in the specified user's
1878 * record, null means delete current value.
1879 * @param stdClass|int|null $user A moodle user object or id, null means current user
1880 * @throws coding_exception
1881 * @return bool Always true or exception
1883 function set_user_preference($name, $value, $user = null) {
1884 global $USER, $DB;
1886 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1887 throw new coding_exception('Invalid preference name in set_user_preference() call');
1890 if (is_null($value)) {
1891 // Null means delete current.
1892 return unset_user_preference($name, $user);
1893 } else if (is_object($value)) {
1894 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1895 } else if (is_array($value)) {
1896 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1898 // Value column maximum length is 1333 characters.
1899 $value = (string)$value;
1900 if (core_text::strlen($value) > 1333) {
1901 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1904 if (is_null($user)) {
1905 $user = $USER;
1906 } else if (isset($user->id)) {
1907 // It is a valid object.
1908 } else if (is_numeric($user)) {
1909 $user = (object)array('id' => (int)$user);
1910 } else {
1911 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1914 check_user_preferences_loaded($user);
1916 if (empty($user->id) or isguestuser($user->id)) {
1917 // No permanent storage for not-logged-in users and guest.
1918 $user->preference[$name] = $value;
1919 return true;
1922 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1923 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1924 // Preference already set to this value.
1925 return true;
1927 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1929 } else {
1930 $preference = new stdClass();
1931 $preference->userid = $user->id;
1932 $preference->name = $name;
1933 $preference->value = $value;
1934 $DB->insert_record('user_preferences', $preference);
1937 // Update value in cache.
1938 $user->preference[$name] = $value;
1939 // Update the $USER in case where we've not a direct reference to $USER.
1940 if ($user !== $USER && $user->id == $USER->id) {
1941 $USER->preference[$name] = $value;
1944 // Set reload flag for other sessions.
1945 mark_user_preferences_changed($user->id);
1947 return true;
1951 * Sets a whole array of preferences for the current user
1953 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1955 * @package core
1956 * @category preference
1957 * @access public
1958 * @param array $prefarray An array of key/value pairs to be set
1959 * @param stdClass|int|null $user A moodle user object or id, null means current user
1960 * @return bool Always true or exception
1962 function set_user_preferences(array $prefarray, $user = null) {
1963 foreach ($prefarray as $name => $value) {
1964 set_user_preference($name, $value, $user);
1966 return true;
1970 * Unsets a preference completely by deleting it from the database
1972 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1974 * @package core
1975 * @category preference
1976 * @access public
1977 * @param string $name The key to unset as preference for the specified user
1978 * @param stdClass|int|null $user A moodle user object or id, null means current user
1979 * @throws coding_exception
1980 * @return bool Always true or exception
1982 function unset_user_preference($name, $user = null) {
1983 global $USER, $DB;
1985 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1986 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1989 if (is_null($user)) {
1990 $user = $USER;
1991 } else if (isset($user->id)) {
1992 // It is a valid object.
1993 } else if (is_numeric($user)) {
1994 $user = (object)array('id' => (int)$user);
1995 } else {
1996 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1999 check_user_preferences_loaded($user);
2001 if (empty($user->id) or isguestuser($user->id)) {
2002 // No permanent storage for not-logged-in user and guest.
2003 unset($user->preference[$name]);
2004 return true;
2007 // Delete from DB.
2008 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2010 // Delete the preference from cache.
2011 unset($user->preference[$name]);
2012 // Update the $USER in case where we've not a direct reference to $USER.
2013 if ($user !== $USER && $user->id == $USER->id) {
2014 unset($USER->preference[$name]);
2017 // Set reload flag for other sessions.
2018 mark_user_preferences_changed($user->id);
2020 return true;
2024 * Used to fetch user preference(s)
2026 * If no arguments are supplied this function will return
2027 * all of the current user preferences as an array.
2029 * If a name is specified then this function
2030 * attempts to return that particular preference value. If
2031 * none is found, then the optional value $default is returned,
2032 * otherwise null.
2034 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2036 * @package core
2037 * @category preference
2038 * @access public
2039 * @param string $name Name of the key to use in finding a preference value
2040 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2041 * @param stdClass|int|null $user A moodle user object or id, null means current user
2042 * @throws coding_exception
2043 * @return string|mixed|null A string containing the value of a single preference. An
2044 * array with all of the preferences or null
2046 function get_user_preferences($name = null, $default = null, $user = null) {
2047 global $USER;
2049 if (is_null($name)) {
2050 // All prefs.
2051 } else if (is_numeric($name) or $name === '_lastloaded') {
2052 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2055 if (is_null($user)) {
2056 $user = $USER;
2057 } else if (isset($user->id)) {
2058 // Is a valid object.
2059 } else if (is_numeric($user)) {
2060 if ($USER->id == $user) {
2061 $user = $USER;
2062 } else {
2063 $user = (object)array('id' => (int)$user);
2065 } else {
2066 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2069 check_user_preferences_loaded($user);
2071 if (empty($name)) {
2072 // All values.
2073 return $user->preference;
2074 } else if (isset($user->preference[$name])) {
2075 // The single string value.
2076 return $user->preference[$name];
2077 } else {
2078 // Default value (null if not specified).
2079 return $default;
2083 // FUNCTIONS FOR HANDLING TIME.
2086 * Given Gregorian date parts in user time produce a GMT timestamp.
2088 * @package core
2089 * @category time
2090 * @param int $year The year part to create timestamp of
2091 * @param int $month The month part to create timestamp of
2092 * @param int $day The day part to create timestamp of
2093 * @param int $hour The hour part to create timestamp of
2094 * @param int $minute The minute part to create timestamp of
2095 * @param int $second The second part to create timestamp of
2096 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2097 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2098 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2099 * applied only if timezone is 99 or string.
2100 * @return int GMT timestamp
2102 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2103 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2104 $date->setDate((int)$year, (int)$month, (int)$day);
2105 $date->setTime((int)$hour, (int)$minute, (int)$second);
2107 $time = $date->getTimestamp();
2109 if ($time === false) {
2110 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2111 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2114 // Moodle BC DST stuff.
2115 if (!$applydst) {
2116 $time += dst_offset_on($time, $timezone);
2119 return $time;
2124 * Format a date/time (seconds) as weeks, days, hours etc as needed
2126 * Given an amount of time in seconds, returns string
2127 * formatted nicely as years, days, hours etc as needed
2129 * @package core
2130 * @category time
2131 * @uses MINSECS
2132 * @uses HOURSECS
2133 * @uses DAYSECS
2134 * @uses YEARSECS
2135 * @param int $totalsecs Time in seconds
2136 * @param stdClass $str Should be a time object
2137 * @return string A nicely formatted date/time string
2139 function format_time($totalsecs, $str = null) {
2141 $totalsecs = abs($totalsecs);
2143 if (!$str) {
2144 // Create the str structure the slow way.
2145 $str = new stdClass();
2146 $str->day = get_string('day');
2147 $str->days = get_string('days');
2148 $str->hour = get_string('hour');
2149 $str->hours = get_string('hours');
2150 $str->min = get_string('min');
2151 $str->mins = get_string('mins');
2152 $str->sec = get_string('sec');
2153 $str->secs = get_string('secs');
2154 $str->year = get_string('year');
2155 $str->years = get_string('years');
2158 $years = floor($totalsecs/YEARSECS);
2159 $remainder = $totalsecs - ($years*YEARSECS);
2160 $days = floor($remainder/DAYSECS);
2161 $remainder = $totalsecs - ($days*DAYSECS);
2162 $hours = floor($remainder/HOURSECS);
2163 $remainder = $remainder - ($hours*HOURSECS);
2164 $mins = floor($remainder/MINSECS);
2165 $secs = $remainder - ($mins*MINSECS);
2167 $ss = ($secs == 1) ? $str->sec : $str->secs;
2168 $sm = ($mins == 1) ? $str->min : $str->mins;
2169 $sh = ($hours == 1) ? $str->hour : $str->hours;
2170 $sd = ($days == 1) ? $str->day : $str->days;
2171 $sy = ($years == 1) ? $str->year : $str->years;
2173 $oyears = '';
2174 $odays = '';
2175 $ohours = '';
2176 $omins = '';
2177 $osecs = '';
2179 if ($years) {
2180 $oyears = $years .' '. $sy;
2182 if ($days) {
2183 $odays = $days .' '. $sd;
2185 if ($hours) {
2186 $ohours = $hours .' '. $sh;
2188 if ($mins) {
2189 $omins = $mins .' '. $sm;
2191 if ($secs) {
2192 $osecs = $secs .' '. $ss;
2195 if ($years) {
2196 return trim($oyears .' '. $odays);
2198 if ($days) {
2199 return trim($odays .' '. $ohours);
2201 if ($hours) {
2202 return trim($ohours .' '. $omins);
2204 if ($mins) {
2205 return trim($omins .' '. $osecs);
2207 if ($secs) {
2208 return $osecs;
2210 return get_string('now');
2214 * Returns a formatted string that represents a date in user time.
2216 * @package core
2217 * @category time
2218 * @param int $date the timestamp in UTC, as obtained from the database.
2219 * @param string $format strftime format. You should probably get this using
2220 * get_string('strftime...', 'langconfig');
2221 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2222 * not 99 then daylight saving will not be added.
2223 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2224 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2225 * If false then the leading zero is maintained.
2226 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2227 * @return string the formatted date/time.
2229 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2230 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2231 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2235 * Returns a formatted date ensuring it is UTF-8.
2237 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2238 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2240 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2241 * @param string $format strftime format.
2242 * @param int|float|string $tz the user timezone
2243 * @return string the formatted date/time.
2244 * @since Moodle 2.3.3
2246 function date_format_string($date, $format, $tz = 99) {
2247 global $CFG;
2249 $localewincharset = null;
2250 // Get the calendar type user is using.
2251 if ($CFG->ostype == 'WINDOWS') {
2252 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2253 $localewincharset = $calendartype->locale_win_charset();
2256 if ($localewincharset) {
2257 $format = core_text::convert($format, 'utf-8', $localewincharset);
2260 date_default_timezone_set(core_date::get_user_timezone($tz));
2261 $datestring = strftime($format, $date);
2262 core_date::set_default_server_timezone();
2264 if ($localewincharset) {
2265 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2268 return $datestring;
2272 * Given a $time timestamp in GMT (seconds since epoch),
2273 * returns an array that represents the Gregorian date in user time
2275 * @package core
2276 * @category time
2277 * @param int $time Timestamp in GMT
2278 * @param float|int|string $timezone user timezone
2279 * @return array An array that represents the date in user time
2281 function usergetdate($time, $timezone=99) {
2282 date_default_timezone_set(core_date::get_user_timezone($timezone));
2283 $result = getdate($time);
2284 core_date::set_default_server_timezone();
2286 return $result;
2290 * Given a GMT timestamp (seconds since epoch), offsets it by
2291 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2293 * NOTE: this function does not include DST properly,
2294 * you should use the PHP date stuff instead!
2296 * @package core
2297 * @category time
2298 * @param int $date Timestamp in GMT
2299 * @param float|int|string $timezone user timezone
2300 * @return int
2302 function usertime($date, $timezone=99) {
2303 $userdate = new DateTime('@' . $date);
2304 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2305 $dst = dst_offset_on($date, $timezone);
2307 return $date - $userdate->getOffset() + $dst;
2311 * Given a time, return the GMT timestamp of the most recent midnight
2312 * for the current user.
2314 * @package core
2315 * @category time
2316 * @param int $date Timestamp in GMT
2317 * @param float|int|string $timezone user timezone
2318 * @return int Returns a GMT timestamp
2320 function usergetmidnight($date, $timezone=99) {
2322 $userdate = usergetdate($date, $timezone);
2324 // Time of midnight of this user's day, in GMT.
2325 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2330 * Returns a string that prints the user's timezone
2332 * @package core
2333 * @category time
2334 * @param float|int|string $timezone user timezone
2335 * @return string
2337 function usertimezone($timezone=99) {
2338 $tz = core_date::get_user_timezone($timezone);
2339 return core_date::get_localised_timezone($tz);
2343 * Returns a float or a string which denotes the user's timezone
2344 * 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)
2345 * means that for this timezone there are also DST rules to be taken into account
2346 * Checks various settings and picks the most dominant of those which have a value
2348 * @package core
2349 * @category time
2350 * @param float|int|string $tz timezone to calculate GMT time offset before
2351 * calculating user timezone, 99 is default user timezone
2352 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2353 * @return float|string
2355 function get_user_timezone($tz = 99) {
2356 global $USER, $CFG;
2358 $timezones = array(
2359 $tz,
2360 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2361 isset($USER->timezone) ? $USER->timezone : 99,
2362 isset($CFG->timezone) ? $CFG->timezone : 99,
2365 $tz = 99;
2367 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2368 foreach ($timezones as $nextvalue) {
2369 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2370 $tz = $nextvalue;
2373 return is_numeric($tz) ? (float) $tz : $tz;
2377 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2378 * - Note: Daylight saving only works for string timezones and not for float.
2380 * @package core
2381 * @category time
2382 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2383 * @param int|float|string $strtimezone user timezone
2384 * @return int
2386 function dst_offset_on($time, $strtimezone = null) {
2387 $tz = core_date::get_user_timezone($strtimezone);
2388 $date = new DateTime('@' . $time);
2389 $date->setTimezone(new DateTimeZone($tz));
2390 if ($date->format('I') == '1') {
2391 if ($tz === 'Australia/Lord_Howe') {
2392 return 1800;
2394 return 3600;
2396 return 0;
2400 * Calculates when the day appears in specific month
2402 * @package core
2403 * @category time
2404 * @param int $startday starting day of the month
2405 * @param int $weekday The day when week starts (normally taken from user preferences)
2406 * @param int $month The month whose day is sought
2407 * @param int $year The year of the month whose day is sought
2408 * @return int
2410 function find_day_in_month($startday, $weekday, $month, $year) {
2411 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2413 $daysinmonth = days_in_month($month, $year);
2414 $daysinweek = count($calendartype->get_weekdays());
2416 if ($weekday == -1) {
2417 // Don't care about weekday, so return:
2418 // abs($startday) if $startday != -1
2419 // $daysinmonth otherwise.
2420 return ($startday == -1) ? $daysinmonth : abs($startday);
2423 // From now on we 're looking for a specific weekday.
2424 // Give "end of month" its actual value, since we know it.
2425 if ($startday == -1) {
2426 $startday = -1 * $daysinmonth;
2429 // Starting from day $startday, the sign is the direction.
2430 if ($startday < 1) {
2431 $startday = abs($startday);
2432 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2434 // This is the last such weekday of the month.
2435 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2436 if ($lastinmonth > $daysinmonth) {
2437 $lastinmonth -= $daysinweek;
2440 // Find the first such weekday <= $startday.
2441 while ($lastinmonth > $startday) {
2442 $lastinmonth -= $daysinweek;
2445 return $lastinmonth;
2446 } else {
2447 $indexweekday = dayofweek($startday, $month, $year);
2449 $diff = $weekday - $indexweekday;
2450 if ($diff < 0) {
2451 $diff += $daysinweek;
2454 // This is the first such weekday of the month equal to or after $startday.
2455 $firstfromindex = $startday + $diff;
2457 return $firstfromindex;
2462 * Calculate the number of days in a given month
2464 * @package core
2465 * @category time
2466 * @param int $month The month whose day count is sought
2467 * @param int $year The year of the month whose day count is sought
2468 * @return int
2470 function days_in_month($month, $year) {
2471 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2472 return $calendartype->get_num_days_in_month($year, $month);
2476 * Calculate the position in the week of a specific calendar day
2478 * @package core
2479 * @category time
2480 * @param int $day The day of the date whose position in the week is sought
2481 * @param int $month The month of the date whose position in the week is sought
2482 * @param int $year The year of the date whose position in the week is sought
2483 * @return int
2485 function dayofweek($day, $month, $year) {
2486 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2487 return $calendartype->get_weekday($year, $month, $day);
2490 // USER AUTHENTICATION AND LOGIN.
2493 * Returns full login url.
2495 * Any form submissions for authentication to this URL must include username,
2496 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2498 * @return string login url
2500 function get_login_url() {
2501 global $CFG;
2503 return "$CFG->wwwroot/login/index.php";
2507 * This function checks that the current user is logged in and has the
2508 * required privileges
2510 * This function checks that the current user is logged in, and optionally
2511 * whether they are allowed to be in a particular course and view a particular
2512 * course module.
2513 * If they are not logged in, then it redirects them to the site login unless
2514 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2515 * case they are automatically logged in as guests.
2516 * If $courseid is given and the user is not enrolled in that course then the
2517 * user is redirected to the course enrolment page.
2518 * If $cm is given and the course module is hidden and the user is not a teacher
2519 * in the course then the user is redirected to the course home page.
2521 * When $cm parameter specified, this function sets page layout to 'module'.
2522 * You need to change it manually later if some other layout needed.
2524 * @package core_access
2525 * @category access
2527 * @param mixed $courseorid id of the course or course object
2528 * @param bool $autologinguest default true
2529 * @param object $cm course module object
2530 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2531 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2532 * in order to keep redirects working properly. MDL-14495
2533 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2534 * @return mixed Void, exit, and die depending on path
2535 * @throws coding_exception
2536 * @throws require_login_exception
2537 * @throws moodle_exception
2539 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2540 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2542 // Must not redirect when byteserving already started.
2543 if (!empty($_SERVER['HTTP_RANGE'])) {
2544 $preventredirect = true;
2547 if (AJAX_SCRIPT) {
2548 // We cannot redirect for AJAX scripts either.
2549 $preventredirect = true;
2552 // Setup global $COURSE, themes, language and locale.
2553 if (!empty($courseorid)) {
2554 if (is_object($courseorid)) {
2555 $course = $courseorid;
2556 } else if ($courseorid == SITEID) {
2557 $course = clone($SITE);
2558 } else {
2559 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2561 if ($cm) {
2562 if ($cm->course != $course->id) {
2563 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2565 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2566 if (!($cm instanceof cm_info)) {
2567 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2568 // db queries so this is not really a performance concern, however it is obviously
2569 // better if you use get_fast_modinfo to get the cm before calling this.
2570 $modinfo = get_fast_modinfo($course);
2571 $cm = $modinfo->get_cm($cm->id);
2574 } else {
2575 // Do not touch global $COURSE via $PAGE->set_course(),
2576 // the reasons is we need to be able to call require_login() at any time!!
2577 $course = $SITE;
2578 if ($cm) {
2579 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2583 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2584 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2585 // risk leading the user back to the AJAX request URL.
2586 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2587 $setwantsurltome = false;
2590 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2591 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2592 if ($preventredirect) {
2593 throw new require_login_session_timeout_exception();
2594 } else {
2595 if ($setwantsurltome) {
2596 $SESSION->wantsurl = qualified_me();
2598 redirect(get_login_url());
2602 // If the user is not even logged in yet then make sure they are.
2603 if (!isloggedin()) {
2604 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2605 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2606 // Misconfigured site guest, just redirect to login page.
2607 redirect(get_login_url());
2608 exit; // Never reached.
2610 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2611 complete_user_login($guest);
2612 $USER->autologinguest = true;
2613 $SESSION->lang = $lang;
2614 } else {
2615 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2616 if ($preventredirect) {
2617 throw new require_login_exception('You are not logged in');
2620 if ($setwantsurltome) {
2621 $SESSION->wantsurl = qualified_me();
2624 $referer = get_local_referer(false);
2625 if (!empty($referer)) {
2626 $SESSION->fromurl = $referer;
2629 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2630 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2631 foreach($authsequence as $authname) {
2632 $authplugin = get_auth_plugin($authname);
2633 $authplugin->pre_loginpage_hook();
2634 if (isloggedin()) {
2635 if ($cm) {
2636 $modinfo = get_fast_modinfo($course);
2637 $cm = $modinfo->get_cm($cm->id);
2639 set_access_log_user();
2640 break;
2644 // If we're still not logged in then go to the login page
2645 if (!isloggedin()) {
2646 redirect(get_login_url());
2647 exit; // Never reached.
2652 // Loginas as redirection if needed.
2653 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2654 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2655 if ($USER->loginascontext->instanceid != $course->id) {
2656 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2661 // Check whether the user should be changing password (but only if it is REALLY them).
2662 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2663 $userauth = get_auth_plugin($USER->auth);
2664 if ($userauth->can_change_password() and !$preventredirect) {
2665 if ($setwantsurltome) {
2666 $SESSION->wantsurl = qualified_me();
2668 if ($changeurl = $userauth->change_password_url()) {
2669 // Use plugin custom url.
2670 redirect($changeurl);
2671 } else {
2672 // Use moodle internal method.
2673 redirect($CFG->wwwroot .'/login/change_password.php');
2675 } else if ($userauth->can_change_password()) {
2676 throw new moodle_exception('forcepasswordchangenotice');
2677 } else {
2678 throw new moodle_exception('nopasswordchangeforced', 'auth');
2682 // Check that the user account is properly set up. If we can't redirect to
2683 // edit their profile and this is not a WS request, perform just the lax check.
2684 // It will allow them to use filepicker on the profile edit page.
2686 if ($preventredirect && !WS_SERVER) {
2687 $usernotfullysetup = user_not_fully_set_up($USER, false);
2688 } else {
2689 $usernotfullysetup = user_not_fully_set_up($USER, true);
2692 if ($usernotfullysetup) {
2693 if ($preventredirect) {
2694 throw new moodle_exception('usernotfullysetup');
2696 if ($setwantsurltome) {
2697 $SESSION->wantsurl = qualified_me();
2699 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2702 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2703 sesskey();
2705 if (\core\session\manager::is_loggedinas()) {
2706 // During a "logged in as" session we should force all content to be cleaned because the
2707 // logged in user will be viewing potentially malicious user generated content.
2708 // See MDL-63786 for more details.
2709 $CFG->forceclean = true;
2712 // Do not bother admins with any formalities, except for activities pending deletion.
2713 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2714 // Set the global $COURSE.
2715 if ($cm) {
2716 $PAGE->set_cm($cm, $course);
2717 $PAGE->set_pagelayout('incourse');
2718 } else if (!empty($courseorid)) {
2719 $PAGE->set_course($course);
2721 // Set accesstime or the user will appear offline which messes up messaging.
2722 user_accesstime_log($course->id);
2723 return;
2726 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2727 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2728 if (!defined('NO_SITEPOLICY_CHECK')) {
2729 define('NO_SITEPOLICY_CHECK', false);
2732 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2733 // Do not test if the script explicitly asked for skipping the site policies check.
2734 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2735 $manager = new \core_privacy\local\sitepolicy\manager();
2736 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2737 if ($preventredirect) {
2738 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2740 if ($setwantsurltome) {
2741 $SESSION->wantsurl = qualified_me();
2743 redirect($policyurl);
2747 // Fetch the system context, the course context, and prefetch its child contexts.
2748 $sysctx = context_system::instance();
2749 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2750 if ($cm) {
2751 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2752 } else {
2753 $cmcontext = null;
2756 // If the site is currently under maintenance, then print a message.
2757 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2758 if ($preventredirect) {
2759 throw new require_login_exception('Maintenance in progress');
2761 $PAGE->set_context(null);
2762 print_maintenance_message();
2765 // Make sure the course itself is not hidden.
2766 if ($course->id == SITEID) {
2767 // Frontpage can not be hidden.
2768 } else {
2769 if (is_role_switched($course->id)) {
2770 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2771 } else {
2772 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2773 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2774 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2775 if ($preventredirect) {
2776 throw new require_login_exception('Course is hidden');
2778 $PAGE->set_context(null);
2779 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2780 // the navigation will mess up when trying to find it.
2781 navigation_node::override_active_url(new moodle_url('/'));
2782 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2787 // Is the user enrolled?
2788 if ($course->id == SITEID) {
2789 // Everybody is enrolled on the frontpage.
2790 } else {
2791 if (\core\session\manager::is_loggedinas()) {
2792 // Make sure the REAL person can access this course first.
2793 $realuser = \core\session\manager::get_realuser();
2794 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2795 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2796 if ($preventredirect) {
2797 throw new require_login_exception('Invalid course login-as access');
2799 $PAGE->set_context(null);
2800 echo $OUTPUT->header();
2801 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2805 $access = false;
2807 if (is_role_switched($course->id)) {
2808 // Ok, user had to be inside this course before the switch.
2809 $access = true;
2811 } else if (is_viewing($coursecontext, $USER)) {
2812 // Ok, no need to mess with enrol.
2813 $access = true;
2815 } else {
2816 if (isset($USER->enrol['enrolled'][$course->id])) {
2817 if ($USER->enrol['enrolled'][$course->id] > time()) {
2818 $access = true;
2819 if (isset($USER->enrol['tempguest'][$course->id])) {
2820 unset($USER->enrol['tempguest'][$course->id]);
2821 remove_temp_course_roles($coursecontext);
2823 } else {
2824 // Expired.
2825 unset($USER->enrol['enrolled'][$course->id]);
2828 if (isset($USER->enrol['tempguest'][$course->id])) {
2829 if ($USER->enrol['tempguest'][$course->id] == 0) {
2830 $access = true;
2831 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2832 $access = true;
2833 } else {
2834 // Expired.
2835 unset($USER->enrol['tempguest'][$course->id]);
2836 remove_temp_course_roles($coursecontext);
2840 if (!$access) {
2841 // Cache not ok.
2842 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2843 if ($until !== false) {
2844 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2845 if ($until == 0) {
2846 $until = ENROL_MAX_TIMESTAMP;
2848 $USER->enrol['enrolled'][$course->id] = $until;
2849 $access = true;
2851 } else {
2852 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2853 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2854 $enrols = enrol_get_plugins(true);
2855 // First ask all enabled enrol instances in course if they want to auto enrol user.
2856 foreach ($instances as $instance) {
2857 if (!isset($enrols[$instance->enrol])) {
2858 continue;
2860 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2861 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2862 if ($until !== false) {
2863 if ($until == 0) {
2864 $until = ENROL_MAX_TIMESTAMP;
2866 $USER->enrol['enrolled'][$course->id] = $until;
2867 $access = true;
2868 break;
2871 // If not enrolled yet try to gain temporary guest access.
2872 if (!$access) {
2873 foreach ($instances as $instance) {
2874 if (!isset($enrols[$instance->enrol])) {
2875 continue;
2877 // Get a duration for the guest access, a timestamp in the future or false.
2878 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2879 if ($until !== false and $until > time()) {
2880 $USER->enrol['tempguest'][$course->id] = $until;
2881 $access = true;
2882 break;
2890 if (!$access) {
2891 if ($preventredirect) {
2892 throw new require_login_exception('Not enrolled');
2894 if ($setwantsurltome) {
2895 $SESSION->wantsurl = qualified_me();
2897 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2901 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
2902 if ($cm && $cm->deletioninprogress) {
2903 if ($preventredirect) {
2904 throw new moodle_exception('activityisscheduledfordeletion');
2906 require_once($CFG->dirroot . '/course/lib.php');
2907 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
2910 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2911 if ($cm && !$cm->uservisible) {
2912 if ($preventredirect) {
2913 throw new require_login_exception('Activity is hidden');
2915 // Get the error message that activity is not available and why (if explanation can be shown to the user).
2916 $PAGE->set_course($course);
2917 $renderer = $PAGE->get_renderer('course');
2918 $message = $renderer->course_section_cm_unavailable_error_message($cm);
2919 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
2922 // Set the global $COURSE.
2923 if ($cm) {
2924 $PAGE->set_cm($cm, $course);
2925 $PAGE->set_pagelayout('incourse');
2926 } else if (!empty($courseorid)) {
2927 $PAGE->set_course($course);
2930 // Finally access granted, update lastaccess times.
2931 user_accesstime_log($course->id);
2936 * This function just makes sure a user is logged out.
2938 * @package core_access
2939 * @category access
2941 function require_logout() {
2942 global $USER, $DB;
2944 if (!isloggedin()) {
2945 // This should not happen often, no need for hooks or events here.
2946 \core\session\manager::terminate_current();
2947 return;
2950 // Execute hooks before action.
2951 $authplugins = array();
2952 $authsequence = get_enabled_auth_plugins();
2953 foreach ($authsequence as $authname) {
2954 $authplugins[$authname] = get_auth_plugin($authname);
2955 $authplugins[$authname]->prelogout_hook();
2958 // Store info that gets removed during logout.
2959 $sid = session_id();
2960 $event = \core\event\user_loggedout::create(
2961 array(
2962 'userid' => $USER->id,
2963 'objectid' => $USER->id,
2964 'other' => array('sessionid' => $sid),
2967 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2968 $event->add_record_snapshot('sessions', $session);
2971 // Clone of $USER object to be used by auth plugins.
2972 $user = fullclone($USER);
2974 // Delete session record and drop $_SESSION content.
2975 \core\session\manager::terminate_current();
2977 // Trigger event AFTER action.
2978 $event->trigger();
2980 // Hook to execute auth plugins redirection after event trigger.
2981 foreach ($authplugins as $authplugin) {
2982 $authplugin->postlogout_hook($user);
2987 * Weaker version of require_login()
2989 * This is a weaker version of {@link require_login()} which only requires login
2990 * when called from within a course rather than the site page, unless
2991 * the forcelogin option is turned on.
2992 * @see require_login()
2994 * @package core_access
2995 * @category access
2997 * @param mixed $courseorid The course object or id in question
2998 * @param bool $autologinguest Allow autologin guests if that is wanted
2999 * @param object $cm Course activity module if known
3000 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3001 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3002 * in order to keep redirects working properly. MDL-14495
3003 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3004 * @return void
3005 * @throws coding_exception
3007 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3008 global $CFG, $PAGE, $SITE;
3009 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3010 or (!is_object($courseorid) and $courseorid == SITEID));
3011 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3012 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3013 // db queries so this is not really a performance concern, however it is obviously
3014 // better if you use get_fast_modinfo to get the cm before calling this.
3015 if (is_object($courseorid)) {
3016 $course = $courseorid;
3017 } else {
3018 $course = clone($SITE);
3020 $modinfo = get_fast_modinfo($course);
3021 $cm = $modinfo->get_cm($cm->id);
3023 if (!empty($CFG->forcelogin)) {
3024 // Login required for both SITE and courses.
3025 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3027 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3028 // Always login for hidden activities.
3029 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3031 } else if (isloggedin() && !isguestuser()) {
3032 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3033 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3035 } else if ($issite) {
3036 // Login for SITE not required.
3037 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3038 if (!empty($courseorid)) {
3039 if (is_object($courseorid)) {
3040 $course = $courseorid;
3041 } else {
3042 $course = clone $SITE;
3044 if ($cm) {
3045 if ($cm->course != $course->id) {
3046 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3048 $PAGE->set_cm($cm, $course);
3049 $PAGE->set_pagelayout('incourse');
3050 } else {
3051 $PAGE->set_course($course);
3053 } else {
3054 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3055 $PAGE->set_course($PAGE->course);
3057 // Do not update access time for webservice or ajax requests.
3058 if (!WS_SERVER && !AJAX_SCRIPT) {
3059 user_accesstime_log(SITEID);
3061 return;
3063 } else {
3064 // Course login always required.
3065 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3070 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3072 * @param string $keyvalue the key value
3073 * @param string $script unique script identifier
3074 * @param int $instance instance id
3075 * @return stdClass the key entry in the user_private_key table
3076 * @since Moodle 3.2
3077 * @throws moodle_exception
3079 function validate_user_key($keyvalue, $script, $instance) {
3080 global $DB;
3082 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3083 print_error('invalidkey');
3086 if (!empty($key->validuntil) and $key->validuntil < time()) {
3087 print_error('expiredkey');
3090 if ($key->iprestriction) {
3091 $remoteaddr = getremoteaddr(null);
3092 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3093 print_error('ipmismatch');
3096 return $key;
3100 * Require key login. Function terminates with error if key not found or incorrect.
3102 * @uses NO_MOODLE_COOKIES
3103 * @uses PARAM_ALPHANUM
3104 * @param string $script unique script identifier
3105 * @param int $instance optional instance id
3106 * @return int Instance ID
3108 function require_user_key_login($script, $instance=null) {
3109 global $DB;
3111 if (!NO_MOODLE_COOKIES) {
3112 print_error('sessioncookiesdisable');
3115 // Extra safety.
3116 \core\session\manager::write_close();
3118 $keyvalue = required_param('key', PARAM_ALPHANUM);
3120 $key = validate_user_key($keyvalue, $script, $instance);
3122 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3123 print_error('invaliduserid');
3126 // Emulate normal session.
3127 enrol_check_plugins($user);
3128 \core\session\manager::set_user($user);
3130 // Note we are not using normal login.
3131 if (!defined('USER_KEY_LOGIN')) {
3132 define('USER_KEY_LOGIN', true);
3135 // Return instance id - it might be empty.
3136 return $key->instance;
3140 * Creates a new private user access key.
3142 * @param string $script unique target identifier
3143 * @param int $userid
3144 * @param int $instance optional instance id
3145 * @param string $iprestriction optional ip restricted access
3146 * @param int $validuntil key valid only until given data
3147 * @return string access key value
3149 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3150 global $DB;
3152 $key = new stdClass();
3153 $key->script = $script;
3154 $key->userid = $userid;
3155 $key->instance = $instance;
3156 $key->iprestriction = $iprestriction;
3157 $key->validuntil = $validuntil;
3158 $key->timecreated = time();
3160 // Something long and unique.
3161 $key->value = md5($userid.'_'.time().random_string(40));
3162 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3163 // Must be unique.
3164 $key->value = md5($userid.'_'.time().random_string(40));
3166 $DB->insert_record('user_private_key', $key);
3167 return $key->value;
3171 * Delete the user's new private user access keys for a particular script.
3173 * @param string $script unique target identifier
3174 * @param int $userid
3175 * @return void
3177 function delete_user_key($script, $userid) {
3178 global $DB;
3179 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3183 * Gets a private user access key (and creates one if one doesn't exist).
3185 * @param string $script unique target identifier
3186 * @param int $userid
3187 * @param int $instance optional instance id
3188 * @param string $iprestriction optional ip restricted access
3189 * @param int $validuntil key valid only until given date
3190 * @return string access key value
3192 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3193 global $DB;
3195 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3196 'instance' => $instance, 'iprestriction' => $iprestriction,
3197 'validuntil' => $validuntil))) {
3198 return $key->value;
3199 } else {
3200 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3206 * Modify the user table by setting the currently logged in user's last login to now.
3208 * @return bool Always returns true
3210 function update_user_login_times() {
3211 global $USER, $DB;
3213 if (isguestuser()) {
3214 // Do not update guest access times/ips for performance.
3215 return true;
3218 $now = time();
3220 $user = new stdClass();
3221 $user->id = $USER->id;
3223 // Make sure all users that logged in have some firstaccess.
3224 if ($USER->firstaccess == 0) {
3225 $USER->firstaccess = $user->firstaccess = $now;
3228 // Store the previous current as lastlogin.
3229 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3231 $USER->currentlogin = $user->currentlogin = $now;
3233 // Function user_accesstime_log() may not update immediately, better do it here.
3234 $USER->lastaccess = $user->lastaccess = $now;
3235 $USER->lastip = $user->lastip = getremoteaddr();
3237 // Note: do not call user_update_user() here because this is part of the login process,
3238 // the login event means that these fields were updated.
3239 $DB->update_record('user', $user);
3240 return true;
3244 * Determines if a user has completed setting up their account.
3246 * The lax mode (with $strict = false) has been introduced for special cases
3247 * only where we want to skip certain checks intentionally. This is valid in
3248 * certain mnet or ajax scenarios when the user cannot / should not be
3249 * redirected to edit their profile. In most cases, you should perform the
3250 * strict check.
3252 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3253 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3254 * @return bool
3256 function user_not_fully_set_up($user, $strict = true) {
3257 global $CFG;
3258 require_once($CFG->dirroot.'/user/profile/lib.php');
3260 if (isguestuser($user)) {
3261 return false;
3264 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3265 return true;
3268 if ($strict) {
3269 if (empty($user->id)) {
3270 // Strict mode can be used with existing accounts only.
3271 return true;
3273 if (!profile_has_required_custom_fields_set($user->id)) {
3274 return true;
3278 return false;
3282 * Check whether the user has exceeded the bounce threshold
3284 * @param stdClass $user A {@link $USER} object
3285 * @return bool true => User has exceeded bounce threshold
3287 function over_bounce_threshold($user) {
3288 global $CFG, $DB;
3290 if (empty($CFG->handlebounces)) {
3291 return false;
3294 if (empty($user->id)) {
3295 // No real (DB) user, nothing to do here.
3296 return false;
3299 // Set sensible defaults.
3300 if (empty($CFG->minbounces)) {
3301 $CFG->minbounces = 10;
3303 if (empty($CFG->bounceratio)) {
3304 $CFG->bounceratio = .20;
3306 $bouncecount = 0;
3307 $sendcount = 0;
3308 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3309 $bouncecount = $bounce->value;
3311 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3312 $sendcount = $send->value;
3314 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3318 * Used to increment or reset email sent count
3320 * @param stdClass $user object containing an id
3321 * @param bool $reset will reset the count to 0
3322 * @return void
3324 function set_send_count($user, $reset=false) {
3325 global $DB;
3327 if (empty($user->id)) {
3328 // No real (DB) user, nothing to do here.
3329 return;
3332 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3333 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3334 $DB->update_record('user_preferences', $pref);
3335 } else if (!empty($reset)) {
3336 // If it's not there and we're resetting, don't bother. Make a new one.
3337 $pref = new stdClass();
3338 $pref->name = 'email_send_count';
3339 $pref->value = 1;
3340 $pref->userid = $user->id;
3341 $DB->insert_record('user_preferences', $pref, false);
3346 * Increment or reset user's email bounce count
3348 * @param stdClass $user object containing an id
3349 * @param bool $reset will reset the count to 0
3351 function set_bounce_count($user, $reset=false) {
3352 global $DB;
3354 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3355 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3356 $DB->update_record('user_preferences', $pref);
3357 } else if (!empty($reset)) {
3358 // If it's not there and we're resetting, don't bother. Make a new one.
3359 $pref = new stdClass();
3360 $pref->name = 'email_bounce_count';
3361 $pref->value = 1;
3362 $pref->userid = $user->id;
3363 $DB->insert_record('user_preferences', $pref, false);
3368 * Determines if the logged in user is currently moving an activity
3370 * @param int $courseid The id of the course being tested
3371 * @return bool
3373 function ismoving($courseid) {
3374 global $USER;
3376 if (!empty($USER->activitycopy)) {
3377 return ($USER->activitycopycourse == $courseid);
3379 return false;
3383 * Returns a persons full name
3385 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3386 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3387 * specify one.
3389 * @param stdClass $user A {@link $USER} object to get full name of.
3390 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3391 * @return string
3393 function fullname($user, $override=false) {
3394 global $CFG, $SESSION;
3396 if (!isset($user->firstname) and !isset($user->lastname)) {
3397 return '';
3400 // Get all of the name fields.
3401 $allnames = get_all_user_name_fields();
3402 if ($CFG->debugdeveloper) {
3403 foreach ($allnames as $allname) {
3404 if (!property_exists($user, $allname)) {
3405 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3406 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3407 // Message has been sent, no point in sending the message multiple times.
3408 break;
3413 if (!$override) {
3414 if (!empty($CFG->forcefirstname)) {
3415 $user->firstname = $CFG->forcefirstname;
3417 if (!empty($CFG->forcelastname)) {
3418 $user->lastname = $CFG->forcelastname;
3422 if (!empty($SESSION->fullnamedisplay)) {
3423 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3426 $template = null;
3427 // If the fullnamedisplay setting is available, set the template to that.
3428 if (isset($CFG->fullnamedisplay)) {
3429 $template = $CFG->fullnamedisplay;
3431 // If the template is empty, or set to language, return the language string.
3432 if ((empty($template) || $template == 'language') && !$override) {
3433 return get_string('fullnamedisplay', null, $user);
3436 // Check to see if we are displaying according to the alternative full name format.
3437 if ($override) {
3438 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3439 // Default to show just the user names according to the fullnamedisplay string.
3440 return get_string('fullnamedisplay', null, $user);
3441 } else {
3442 // If the override is true, then change the template to use the complete name.
3443 $template = $CFG->alternativefullnameformat;
3447 $requirednames = array();
3448 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3449 foreach ($allnames as $allname) {
3450 if (strpos($template, $allname) !== false) {
3451 $requirednames[] = $allname;
3455 $displayname = $template;
3456 // Switch in the actual data into the template.
3457 foreach ($requirednames as $altname) {
3458 if (isset($user->$altname)) {
3459 // Using empty() on the below if statement causes breakages.
3460 if ((string)$user->$altname == '') {
3461 $displayname = str_replace($altname, 'EMPTY', $displayname);
3462 } else {
3463 $displayname = str_replace($altname, $user->$altname, $displayname);
3465 } else {
3466 $displayname = str_replace($altname, 'EMPTY', $displayname);
3469 // Tidy up any misc. characters (Not perfect, but gets most characters).
3470 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3471 // katakana and parenthesis.
3472 $patterns = array();
3473 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3474 // filled in by a user.
3475 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3476 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3477 // This regular expression is to remove any double spaces in the display name.
3478 $patterns[] = '/\s{2,}/u';
3479 foreach ($patterns as $pattern) {
3480 $displayname = preg_replace($pattern, ' ', $displayname);
3483 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3484 $displayname = trim($displayname);
3485 if (empty($displayname)) {
3486 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3487 // people in general feel is a good setting to fall back on.
3488 $displayname = $user->firstname;
3490 return $displayname;
3494 * A centralised location for the all name fields. Returns an array / sql string snippet.
3496 * @param bool $returnsql True for an sql select field snippet.
3497 * @param string $tableprefix table query prefix to use in front of each field.
3498 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3499 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3500 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3501 * @return array|string All name fields.
3503 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3504 // This array is provided in this order because when called by fullname() (above) if firstname is before
3505 // firstnamephonetic str_replace() will change the wrong placeholder.
3506 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3507 'lastnamephonetic' => 'lastnamephonetic',
3508 'middlename' => 'middlename',
3509 'alternatename' => 'alternatename',
3510 'firstname' => 'firstname',
3511 'lastname' => 'lastname');
3513 // Let's add a prefix to the array of user name fields if provided.
3514 if ($prefix) {
3515 foreach ($alternatenames as $key => $altname) {
3516 $alternatenames[$key] = $prefix . $altname;
3520 // If we want the end result to have firstname and lastname at the front / top of the result.
3521 if ($order) {
3522 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3523 for ($i = 0; $i < 2; $i++) {
3524 // Get the last element.
3525 $lastelement = end($alternatenames);
3526 // Remove it from the array.
3527 unset($alternatenames[$lastelement]);
3528 // Put the element back on the top of the array.
3529 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3533 // Create an sql field snippet if requested.
3534 if ($returnsql) {
3535 if ($tableprefix) {
3536 if ($fieldprefix) {
3537 foreach ($alternatenames as $key => $altname) {
3538 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3540 } else {
3541 foreach ($alternatenames as $key => $altname) {
3542 $alternatenames[$key] = $tableprefix . '.' . $altname;
3546 $alternatenames = implode(',', $alternatenames);
3548 return $alternatenames;
3552 * Reduces lines of duplicated code for getting user name fields.
3554 * See also {@link user_picture::unalias()}
3556 * @param object $addtoobject Object to add user name fields to.
3557 * @param object $secondobject Object that contains user name field information.
3558 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3559 * @param array $additionalfields Additional fields to be matched with data in the second object.
3560 * The key can be set to the user table field name.
3561 * @return object User name fields.
3563 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3564 $fields = get_all_user_name_fields(false, null, $prefix);
3565 if ($additionalfields) {
3566 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3567 // the key is a number and then sets the key to the array value.
3568 foreach ($additionalfields as $key => $value) {
3569 if (is_numeric($key)) {
3570 $additionalfields[$value] = $prefix . $value;
3571 unset($additionalfields[$key]);
3572 } else {
3573 $additionalfields[$key] = $prefix . $value;
3576 $fields = array_merge($fields, $additionalfields);
3578 foreach ($fields as $key => $field) {
3579 // Important that we have all of the user name fields present in the object that we are sending back.
3580 $addtoobject->$key = '';
3581 if (isset($secondobject->$field)) {
3582 $addtoobject->$key = $secondobject->$field;
3585 return $addtoobject;
3589 * Returns an array of values in order of occurance in a provided string.
3590 * The key in the result is the character postion in the string.
3592 * @param array $values Values to be found in the string format
3593 * @param string $stringformat The string which may contain values being searched for.
3594 * @return array An array of values in order according to placement in the string format.
3596 function order_in_string($values, $stringformat) {
3597 $valuearray = array();
3598 foreach ($values as $value) {
3599 $pattern = "/$value\b/";
3600 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3601 if (preg_match($pattern, $stringformat)) {
3602 $replacement = "thing";
3603 // Replace the value with something more unique to ensure we get the right position when using strpos().
3604 $newformat = preg_replace($pattern, $replacement, $stringformat);
3605 $position = strpos($newformat, $replacement);
3606 $valuearray[$position] = $value;
3609 ksort($valuearray);
3610 return $valuearray;
3614 * Checks if current user is shown any extra fields when listing users.
3616 * @param object $context Context
3617 * @param array $already Array of fields that we're going to show anyway
3618 * so don't bother listing them
3619 * @return array Array of field names from user table, not including anything
3620 * listed in $already
3622 function get_extra_user_fields($context, $already = array()) {
3623 global $CFG;
3625 // Only users with permission get the extra fields.
3626 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3627 return array();
3630 // Split showuseridentity on comma (filter needed in case the showuseridentity is empty).
3631 $extra = array_filter(explode(',', $CFG->showuseridentity));
3633 foreach ($extra as $key => $field) {
3634 if (in_array($field, $already)) {
3635 unset($extra[$key]);
3639 // If the identity fields are also among hidden fields, make sure the user can see them.
3640 $hiddenfields = array_filter(explode(',', $CFG->hiddenuserfields));
3641 $hiddenidentifiers = array_intersect($extra, $hiddenfields);
3643 if ($hiddenidentifiers) {
3644 if ($context->get_course_context(false)) {
3645 // We are somewhere inside a course.
3646 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3648 } else {
3649 // We are not inside a course.
3650 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
3653 if (!$canviewhiddenuserfields) {
3654 // Remove hidden identifiers from the list.
3655 $extra = array_diff($extra, $hiddenidentifiers);
3659 // Re-index the entries.
3660 $extra = array_values($extra);
3662 return $extra;
3666 * If the current user is to be shown extra user fields when listing or
3667 * selecting users, returns a string suitable for including in an SQL select
3668 * clause to retrieve those fields.
3670 * @param context $context Context
3671 * @param string $alias Alias of user table, e.g. 'u' (default none)
3672 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3673 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3674 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3676 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3677 $fields = get_extra_user_fields($context, $already);
3678 $result = '';
3679 // Add punctuation for alias.
3680 if ($alias !== '') {
3681 $alias .= '.';
3683 foreach ($fields as $field) {
3684 $result .= ', ' . $alias . $field;
3685 if ($prefix) {
3686 $result .= ' AS ' . $prefix . $field;
3689 return $result;
3693 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3694 * @param string $field Field name, e.g. 'phone1'
3695 * @return string Text description taken from language file, e.g. 'Phone number'
3697 function get_user_field_name($field) {
3698 // Some fields have language strings which are not the same as field name.
3699 switch ($field) {
3700 case 'url' : {
3701 return get_string('webpage');
3703 case 'icq' : {
3704 return get_string('icqnumber');
3706 case 'skype' : {
3707 return get_string('skypeid');
3709 case 'aim' : {
3710 return get_string('aimid');
3712 case 'yahoo' : {
3713 return get_string('yahooid');
3715 case 'msn' : {
3716 return get_string('msnid');
3718 case 'picture' : {
3719 return get_string('pictureofuser');
3722 // Otherwise just use the same lang string.
3723 return get_string($field);
3727 * Returns whether a given authentication plugin exists.
3729 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3730 * @return boolean Whether the plugin is available.
3732 function exists_auth_plugin($auth) {
3733 global $CFG;
3735 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3736 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3738 return false;
3742 * Checks if a given plugin is in the list of enabled authentication plugins.
3744 * @param string $auth Authentication plugin.
3745 * @return boolean Whether the plugin is enabled.
3747 function is_enabled_auth($auth) {
3748 if (empty($auth)) {
3749 return false;
3752 $enabled = get_enabled_auth_plugins();
3754 return in_array($auth, $enabled);
3758 * Returns an authentication plugin instance.
3760 * @param string $auth name of authentication plugin
3761 * @return auth_plugin_base An instance of the required authentication plugin.
3763 function get_auth_plugin($auth) {
3764 global $CFG;
3766 // Check the plugin exists first.
3767 if (! exists_auth_plugin($auth)) {
3768 print_error('authpluginnotfound', 'debug', '', $auth);
3771 // Return auth plugin instance.
3772 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3773 $class = "auth_plugin_$auth";
3774 return new $class;
3778 * Returns array of active auth plugins.
3780 * @param bool $fix fix $CFG->auth if needed
3781 * @return array
3783 function get_enabled_auth_plugins($fix=false) {
3784 global $CFG;
3786 $default = array('manual', 'nologin');
3788 if (empty($CFG->auth)) {
3789 $auths = array();
3790 } else {
3791 $auths = explode(',', $CFG->auth);
3794 if ($fix) {
3795 $auths = array_unique($auths);
3796 foreach ($auths as $k => $authname) {
3797 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3798 unset($auths[$k]);
3801 $newconfig = implode(',', $auths);
3802 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3803 set_config('auth', $newconfig);
3807 return (array_merge($default, $auths));
3811 * Returns true if an internal authentication method is being used.
3812 * if method not specified then, global default is assumed
3814 * @param string $auth Form of authentication required
3815 * @return bool
3817 function is_internal_auth($auth) {
3818 // Throws error if bad $auth.
3819 $authplugin = get_auth_plugin($auth);
3820 return $authplugin->is_internal();
3824 * Returns true if the user is a 'restored' one.
3826 * Used in the login process to inform the user and allow him/her to reset the password
3828 * @param string $username username to be checked
3829 * @return bool
3831 function is_restored_user($username) {
3832 global $CFG, $DB;
3834 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3838 * Returns an array of user fields
3840 * @return array User field/column names
3842 function get_user_fieldnames() {
3843 global $DB;
3845 $fieldarray = $DB->get_columns('user');
3846 unset($fieldarray['id']);
3847 $fieldarray = array_keys($fieldarray);
3849 return $fieldarray;
3853 * Creates a bare-bones user record
3855 * @todo Outline auth types and provide code example
3857 * @param string $username New user's username to add to record
3858 * @param string $password New user's password to add to record
3859 * @param string $auth Form of authentication required
3860 * @return stdClass A complete user object
3862 function create_user_record($username, $password, $auth = 'manual') {
3863 global $CFG, $DB;
3864 require_once($CFG->dirroot.'/user/profile/lib.php');
3865 require_once($CFG->dirroot.'/user/lib.php');
3867 // Just in case check text case.
3868 $username = trim(core_text::strtolower($username));
3870 $authplugin = get_auth_plugin($auth);
3871 $customfields = $authplugin->get_custom_user_profile_fields();
3872 $newuser = new stdClass();
3873 if ($newinfo = $authplugin->get_userinfo($username)) {
3874 $newinfo = truncate_userinfo($newinfo);
3875 foreach ($newinfo as $key => $value) {
3876 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3877 $newuser->$key = $value;
3882 if (!empty($newuser->email)) {
3883 if (email_is_not_allowed($newuser->email)) {
3884 unset($newuser->email);
3888 if (!isset($newuser->city)) {
3889 $newuser->city = '';
3892 $newuser->auth = $auth;
3893 $newuser->username = $username;
3895 // Fix for MDL-8480
3896 // user CFG lang for user if $newuser->lang is empty
3897 // or $user->lang is not an installed language.
3898 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3899 $newuser->lang = $CFG->lang;
3901 $newuser->confirmed = 1;
3902 $newuser->lastip = getremoteaddr();
3903 $newuser->timecreated = time();
3904 $newuser->timemodified = $newuser->timecreated;
3905 $newuser->mnethostid = $CFG->mnet_localhost_id;
3907 $newuser->id = user_create_user($newuser, false, false);
3909 // Save user profile data.
3910 profile_save_data($newuser);
3912 $user = get_complete_user_data('id', $newuser->id);
3913 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3914 set_user_preference('auth_forcepasswordchange', 1, $user);
3916 // Set the password.
3917 update_internal_user_password($user, $password);
3919 // Trigger event.
3920 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3922 return $user;
3926 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3928 * @param string $username user's username to update the record
3929 * @return stdClass A complete user object
3931 function update_user_record($username) {
3932 global $DB, $CFG;
3933 // Just in case check text case.
3934 $username = trim(core_text::strtolower($username));
3936 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3937 return update_user_record_by_id($oldinfo->id);
3941 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3943 * @param int $id user id
3944 * @return stdClass A complete user object
3946 function update_user_record_by_id($id) {
3947 global $DB, $CFG;
3948 require_once($CFG->dirroot."/user/profile/lib.php");
3949 require_once($CFG->dirroot.'/user/lib.php');
3951 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3952 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3954 $newuser = array();
3955 $userauth = get_auth_plugin($oldinfo->auth);
3957 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3958 $newinfo = truncate_userinfo($newinfo);
3959 $customfields = $userauth->get_custom_user_profile_fields();
3961 foreach ($newinfo as $key => $value) {
3962 $iscustom = in_array($key, $customfields);
3963 if (!$iscustom) {
3964 $key = strtolower($key);
3966 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3967 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3968 // Unknown or must not be changed.
3969 continue;
3971 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
3972 continue;
3974 $confval = $userauth->config->{'field_updatelocal_' . $key};
3975 $lockval = $userauth->config->{'field_lock_' . $key};
3976 if ($confval === 'onlogin') {
3977 // MDL-4207 Don't overwrite modified user profile values with
3978 // empty LDAP values when 'unlocked if empty' is set. The purpose
3979 // of the setting 'unlocked if empty' is to allow the user to fill
3980 // in a value for the selected field _if LDAP is giving
3981 // nothing_ for this field. Thus it makes sense to let this value
3982 // stand in until LDAP is giving a value for this field.
3983 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3984 if ($iscustom || (in_array($key, $userauth->userfields) &&
3985 ((string)$oldinfo->$key !== (string)$value))) {
3986 $newuser[$key] = (string)$value;
3991 if ($newuser) {
3992 $newuser['id'] = $oldinfo->id;
3993 $newuser['timemodified'] = time();
3994 user_update_user((object) $newuser, false, false);
3996 // Save user profile data.
3997 profile_save_data((object) $newuser);
3999 // Trigger event.
4000 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4004 return get_complete_user_data('id', $oldinfo->id);
4008 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4010 * @param array $info Array of user properties to truncate if needed
4011 * @return array The now truncated information that was passed in
4013 function truncate_userinfo(array $info) {
4014 // Define the limits.
4015 $limit = array(
4016 'username' => 100,
4017 'idnumber' => 255,
4018 'firstname' => 100,
4019 'lastname' => 100,
4020 'email' => 100,
4021 'icq' => 15,
4022 'phone1' => 20,
4023 'phone2' => 20,
4024 'institution' => 255,
4025 'department' => 255,
4026 'address' => 255,
4027 'city' => 120,
4028 'country' => 2,
4029 'url' => 255,
4032 // Apply where needed.
4033 foreach (array_keys($info) as $key) {
4034 if (!empty($limit[$key])) {
4035 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4039 return $info;
4043 * Marks user deleted in internal user database and notifies the auth plugin.
4044 * Also unenrols user from all roles and does other cleanup.
4046 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4048 * @param stdClass $user full user object before delete
4049 * @return boolean success
4050 * @throws coding_exception if invalid $user parameter detected
4052 function delete_user(stdClass $user) {
4053 global $CFG, $DB, $SESSION;
4054 require_once($CFG->libdir.'/grouplib.php');
4055 require_once($CFG->libdir.'/gradelib.php');
4056 require_once($CFG->dirroot.'/message/lib.php');
4057 require_once($CFG->dirroot.'/user/lib.php');
4059 // Make sure nobody sends bogus record type as parameter.
4060 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4061 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4064 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4065 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4066 debugging('Attempt to delete unknown user account.');
4067 return false;
4070 // There must be always exactly one guest record, originally the guest account was identified by username only,
4071 // now we use $CFG->siteguest for performance reasons.
4072 if ($user->username === 'guest' or isguestuser($user)) {
4073 debugging('Guest user account can not be deleted.');
4074 return false;
4077 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4078 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4079 if ($user->auth === 'manual' and is_siteadmin($user)) {
4080 debugging('Local administrator accounts can not be deleted.');
4081 return false;
4084 // Allow plugins to use this user object before we completely delete it.
4085 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4086 foreach ($pluginsfunction as $plugintype => $plugins) {
4087 foreach ($plugins as $pluginfunction) {
4088 $pluginfunction($user);
4093 // Keep user record before updating it, as we have to pass this to user_deleted event.
4094 $olduser = clone $user;
4096 // Keep a copy of user context, we need it for event.
4097 $usercontext = context_user::instance($user->id);
4099 // Delete all grades - backup is kept in grade_grades_history table.
4100 grade_user_delete($user->id);
4102 // TODO: remove from cohorts using standard API here.
4104 // Remove user tags.
4105 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4107 // Unconditionally unenrol from all courses.
4108 enrol_user_delete($user);
4110 // Unenrol from all roles in all contexts.
4111 // This might be slow but it is really needed - modules might do some extra cleanup!
4112 role_unassign_all(array('userid' => $user->id));
4114 // Now do a brute force cleanup.
4116 // Remove from all cohorts.
4117 $DB->delete_records('cohort_members', array('userid' => $user->id));
4119 // Remove from all groups.
4120 $DB->delete_records('groups_members', array('userid' => $user->id));
4122 // Brute force unenrol from all courses.
4123 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4125 // Purge user preferences.
4126 $DB->delete_records('user_preferences', array('userid' => $user->id));
4128 // Purge user extra profile info.
4129 $DB->delete_records('user_info_data', array('userid' => $user->id));
4131 // Purge log of previous password hashes.
4132 $DB->delete_records('user_password_history', array('userid' => $user->id));
4134 // Last course access not necessary either.
4135 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4136 // Remove all user tokens.
4137 $DB->delete_records('external_tokens', array('userid' => $user->id));
4139 // Unauthorise the user for all services.
4140 $DB->delete_records('external_services_users', array('userid' => $user->id));
4142 // Remove users private keys.
4143 $DB->delete_records('user_private_key', array('userid' => $user->id));
4145 // Remove users customised pages.
4146 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4148 // Delete user from $SESSION->bulk_users.
4149 if (isset($SESSION->bulk_users[$user->id])) {
4150 unset($SESSION->bulk_users[$user->id]);
4153 // Force logout - may fail if file based sessions used, sorry.
4154 \core\session\manager::kill_user_sessions($user->id);
4156 // Generate username from email address, or a fake email.
4157 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4158 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
4160 // Workaround for bulk deletes of users with the same email address.
4161 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4162 $delname++;
4165 // Mark internal user record as "deleted".
4166 $updateuser = new stdClass();
4167 $updateuser->id = $user->id;
4168 $updateuser->deleted = 1;
4169 $updateuser->username = $delname; // Remember it just in case.
4170 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4171 $updateuser->idnumber = ''; // Clear this field to free it up.
4172 $updateuser->picture = 0;
4173 $updateuser->timemodified = time();
4175 // Don't trigger update event, as user is being deleted.
4176 user_update_user($updateuser, false, false);
4178 // Delete all content associated with the user context, but not the context itself.
4179 $usercontext->delete_content();
4181 // Any plugin that needs to cleanup should register this event.
4182 // Trigger event.
4183 $event = \core\event\user_deleted::create(
4184 array(
4185 'objectid' => $user->id,
4186 'relateduserid' => $user->id,
4187 'context' => $usercontext,
4188 'other' => array(
4189 'username' => $user->username,
4190 'email' => $user->email,
4191 'idnumber' => $user->idnumber,
4192 'picture' => $user->picture,
4193 'mnethostid' => $user->mnethostid
4197 $event->add_record_snapshot('user', $olduser);
4198 $event->trigger();
4200 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4201 // should know about this updated property persisted to the user's table.
4202 $user->timemodified = $updateuser->timemodified;
4204 // Notify auth plugin - do not block the delete even when plugin fails.
4205 $authplugin = get_auth_plugin($user->auth);
4206 $authplugin->user_delete($user);
4208 return true;
4212 * Retrieve the guest user object.
4214 * @return stdClass A {@link $USER} object
4216 function guest_user() {
4217 global $CFG, $DB;
4219 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4220 $newuser->confirmed = 1;
4221 $newuser->lang = $CFG->lang;
4222 $newuser->lastip = getremoteaddr();
4225 return $newuser;
4229 * Authenticates a user against the chosen authentication mechanism
4231 * Given a username and password, this function looks them
4232 * up using the currently selected authentication mechanism,
4233 * and if the authentication is successful, it returns a
4234 * valid $user object from the 'user' table.
4236 * Uses auth_ functions from the currently active auth module
4238 * After authenticate_user_login() returns success, you will need to
4239 * log that the user has logged in, and call complete_user_login() to set
4240 * the session up.
4242 * Note: this function works only with non-mnet accounts!
4244 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4245 * @param string $password User's password
4246 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4247 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4248 * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4249 * @return stdClass|false A {@link $USER} object or false if error
4251 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4252 global $CFG, $DB;
4253 require_once("$CFG->libdir/authlib.php");
4255 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4256 // we have found the user
4258 } else if (!empty($CFG->authloginviaemail)) {
4259 if ($email = clean_param($username, PARAM_EMAIL)) {
4260 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4261 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4262 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4263 if (count($users) === 1) {
4264 // Use email for login only if unique.
4265 $user = reset($users);
4266 $user = get_complete_user_data('id', $user->id);
4267 $username = $user->username;
4269 unset($users);
4273 // Make sure this request came from the login form.
4274 if (!\core\session\manager::validate_login_token($logintoken)) {
4275 $failurereason = AUTH_LOGIN_FAILED;
4277 // Trigger login failed event.
4278 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4279 'other' => array('username' => $username, 'reason' => $failurereason)));
4280 $event->trigger();
4281 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4282 return false;
4285 $authsenabled = get_enabled_auth_plugins();
4287 if ($user) {
4288 // Use manual if auth not set.
4289 $auth = empty($user->auth) ? 'manual' : $user->auth;
4291 if (in_array($user->auth, $authsenabled)) {
4292 $authplugin = get_auth_plugin($user->auth);
4293 $authplugin->pre_user_login_hook($user);
4296 if (!empty($user->suspended)) {
4297 $failurereason = AUTH_LOGIN_SUSPENDED;
4299 // Trigger login failed event.
4300 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4301 'other' => array('username' => $username, 'reason' => $failurereason)));
4302 $event->trigger();
4303 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4304 return false;
4306 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4307 // Legacy way to suspend user.
4308 $failurereason = AUTH_LOGIN_SUSPENDED;
4310 // Trigger login failed event.
4311 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4312 'other' => array('username' => $username, 'reason' => $failurereason)));
4313 $event->trigger();
4314 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4315 return false;
4317 $auths = array($auth);
4319 } else {
4320 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4321 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4322 $failurereason = AUTH_LOGIN_NOUSER;
4324 // Trigger login failed event.
4325 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4326 'reason' => $failurereason)));
4327 $event->trigger();
4328 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4329 return false;
4332 // User does not exist.
4333 $auths = $authsenabled;
4334 $user = new stdClass();
4335 $user->id = 0;
4338 if ($ignorelockout) {
4339 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4340 // or this function is called from a SSO script.
4341 } else if ($user->id) {
4342 // Verify login lockout after other ways that may prevent user login.
4343 if (login_is_lockedout($user)) {
4344 $failurereason = AUTH_LOGIN_LOCKOUT;
4346 // Trigger login failed event.
4347 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4348 'other' => array('username' => $username, 'reason' => $failurereason)));
4349 $event->trigger();
4351 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4352 return false;
4354 } else {
4355 // We can not lockout non-existing accounts.
4358 foreach ($auths as $auth) {
4359 $authplugin = get_auth_plugin($auth);
4361 // On auth fail fall through to the next plugin.
4362 if (!$authplugin->user_login($username, $password)) {
4363 continue;
4366 // Successful authentication.
4367 if ($user->id) {
4368 // User already exists in database.
4369 if (empty($user->auth)) {
4370 // For some reason auth isn't set yet.
4371 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4372 $user->auth = $auth;
4375 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4376 // the current hash algorithm while we have access to the user's password.
4377 update_internal_user_password($user, $password);
4379 if ($authplugin->is_synchronised_with_external()) {
4380 // Update user record from external DB.
4381 $user = update_user_record_by_id($user->id);
4383 } else {
4384 // The user is authenticated but user creation may be disabled.
4385 if (!empty($CFG->authpreventaccountcreation)) {
4386 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4388 // Trigger login failed event.
4389 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4390 'reason' => $failurereason)));
4391 $event->trigger();
4393 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4394 $_SERVER['HTTP_USER_AGENT']);
4395 return false;
4396 } else {
4397 $user = create_user_record($username, $password, $auth);
4401 $authplugin->sync_roles($user);
4403 foreach ($authsenabled as $hau) {
4404 $hauth = get_auth_plugin($hau);
4405 $hauth->user_authenticated_hook($user, $username, $password);
4408 if (empty($user->id)) {
4409 $failurereason = AUTH_LOGIN_NOUSER;
4410 // Trigger login failed event.
4411 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4412 'reason' => $failurereason)));
4413 $event->trigger();
4414 return false;
4417 if (!empty($user->suspended)) {
4418 // Just in case some auth plugin suspended account.
4419 $failurereason = AUTH_LOGIN_SUSPENDED;
4420 // Trigger login failed event.
4421 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4422 'other' => array('username' => $username, 'reason' => $failurereason)));
4423 $event->trigger();
4424 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4425 return false;
4428 login_attempt_valid($user);
4429 $failurereason = AUTH_LOGIN_OK;
4430 return $user;
4433 // Failed if all the plugins have failed.
4434 if (debugging('', DEBUG_ALL)) {
4435 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4438 if ($user->id) {
4439 login_attempt_failed($user);
4440 $failurereason = AUTH_LOGIN_FAILED;
4441 // Trigger login failed event.
4442 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4443 'other' => array('username' => $username, 'reason' => $failurereason)));
4444 $event->trigger();
4445 } else {
4446 $failurereason = AUTH_LOGIN_NOUSER;
4447 // Trigger login failed event.
4448 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4449 'reason' => $failurereason)));
4450 $event->trigger();
4453 return false;
4457 * Call to complete the user login process after authenticate_user_login()
4458 * has succeeded. It will setup the $USER variable and other required bits
4459 * and pieces.
4461 * NOTE:
4462 * - It will NOT log anything -- up to the caller to decide what to log.
4463 * - this function does not set any cookies any more!
4465 * @param stdClass $user
4466 * @return stdClass A {@link $USER} object - BC only, do not use
4468 function complete_user_login($user) {
4469 global $CFG, $DB, $USER, $SESSION;
4471 \core\session\manager::login_user($user);
4473 // Reload preferences from DB.
4474 unset($USER->preference);
4475 check_user_preferences_loaded($USER);
4477 // Update login times.
4478 update_user_login_times();
4480 // Extra session prefs init.
4481 set_login_session_preferences();
4483 // Trigger login event.
4484 $event = \core\event\user_loggedin::create(
4485 array(
4486 'userid' => $USER->id,
4487 'objectid' => $USER->id,
4488 'other' => array('username' => $USER->username),
4491 $event->trigger();
4493 // Queue migrating the messaging data, if we need to.
4494 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4495 // Check if there are any legacy messages to migrate.
4496 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4497 \core_message\task\migrate_message_data::queue_task($USER->id);
4498 } else {
4499 set_user_preference('core_message_migrate_data', true, $USER->id);
4503 if (isguestuser()) {
4504 // No need to continue when user is THE guest.
4505 return $USER;
4508 if (CLI_SCRIPT) {
4509 // We can redirect to password change URL only in browser.
4510 return $USER;
4513 // Select password change url.
4514 $userauth = get_auth_plugin($USER->auth);
4516 // Check whether the user should be changing password.
4517 if (get_user_preferences('auth_forcepasswordchange', false)) {
4518 if ($userauth->can_change_password()) {
4519 if ($changeurl = $userauth->change_password_url()) {
4520 redirect($changeurl);
4521 } else {
4522 require_once($CFG->dirroot . '/login/lib.php');
4523 $SESSION->wantsurl = core_login_get_return_url();
4524 redirect($CFG->wwwroot.'/login/change_password.php');
4526 } else {
4527 print_error('nopasswordchangeforced', 'auth');
4530 return $USER;
4534 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4536 * @param string $password String to check.
4537 * @return boolean True if the $password matches the format of an md5 sum.
4539 function password_is_legacy_hash($password) {
4540 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4544 * Compare password against hash stored in user object to determine if it is valid.
4546 * If necessary it also updates the stored hash to the current format.
4548 * @param stdClass $user (Password property may be updated).
4549 * @param string $password Plain text password.
4550 * @return bool True if password is valid.
4552 function validate_internal_user_password($user, $password) {
4553 global $CFG;
4555 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4556 // Internal password is not used at all, it can not validate.
4557 return false;
4560 // If hash isn't a legacy (md5) hash, validate using the library function.
4561 if (!password_is_legacy_hash($user->password)) {
4562 return password_verify($password, $user->password);
4565 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4566 // is valid we can then update it to the new algorithm.
4568 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4569 $validated = false;
4571 if ($user->password === md5($password.$sitesalt)
4572 or $user->password === md5($password)
4573 or $user->password === md5(addslashes($password).$sitesalt)
4574 or $user->password === md5(addslashes($password))) {
4575 // Note: we are intentionally using the addslashes() here because we
4576 // need to accept old password hashes of passwords with magic quotes.
4577 $validated = true;
4579 } else {
4580 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4581 $alt = 'passwordsaltalt'.$i;
4582 if (!empty($CFG->$alt)) {
4583 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4584 $validated = true;
4585 break;
4591 if ($validated) {
4592 // If the password matches the existing md5 hash, update to the
4593 // current hash algorithm while we have access to the user's password.
4594 update_internal_user_password($user, $password);
4597 return $validated;
4601 * Calculate hash for a plain text password.
4603 * @param string $password Plain text password to be hashed.
4604 * @param bool $fasthash If true, use a low cost factor when generating the hash
4605 * This is much faster to generate but makes the hash
4606 * less secure. It is used when lots of hashes need to
4607 * be generated quickly.
4608 * @return string The hashed password.
4610 * @throws moodle_exception If a problem occurs while generating the hash.
4612 function hash_internal_user_password($password, $fasthash = false) {
4613 global $CFG;
4615 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4616 $options = ($fasthash) ? array('cost' => 4) : array();
4618 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4620 if ($generatedhash === false || $generatedhash === null) {
4621 throw new moodle_exception('Failed to generate password hash.');
4624 return $generatedhash;
4628 * Update password hash in user object (if necessary).
4630 * The password is updated if:
4631 * 1. The password has changed (the hash of $user->password is different
4632 * to the hash of $password).
4633 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4634 * md5 algorithm).
4636 * Updating the password will modify the $user object and the database
4637 * record to use the current hashing algorithm.
4638 * It will remove Web Services user tokens too.
4640 * @param stdClass $user User object (password property may be updated).
4641 * @param string $password Plain text password.
4642 * @param bool $fasthash If true, use a low cost factor when generating the hash
4643 * This is much faster to generate but makes the hash
4644 * less secure. It is used when lots of hashes need to
4645 * be generated quickly.
4646 * @return bool Always returns true.
4648 function update_internal_user_password($user, $password, $fasthash = false) {
4649 global $CFG, $DB;
4651 // Figure out what the hashed password should be.
4652 if (!isset($user->auth)) {
4653 debugging('User record in update_internal_user_password() must include field auth',
4654 DEBUG_DEVELOPER);
4655 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4657 $authplugin = get_auth_plugin($user->auth);
4658 if ($authplugin->prevent_local_passwords()) {
4659 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4660 } else {
4661 $hashedpassword = hash_internal_user_password($password, $fasthash);
4664 $algorithmchanged = false;
4666 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4667 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4668 $passwordchanged = ($user->password !== $hashedpassword);
4670 } else if (isset($user->password)) {
4671 // If verification fails then it means the password has changed.
4672 $passwordchanged = !password_verify($password, $user->password);
4673 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4674 } else {
4675 // While creating new user, password in unset in $user object, to avoid
4676 // saving it with user_create()
4677 $passwordchanged = true;
4680 if ($passwordchanged || $algorithmchanged) {
4681 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4682 $user->password = $hashedpassword;
4684 // Trigger event.
4685 $user = $DB->get_record('user', array('id' => $user->id));
4686 \core\event\user_password_updated::create_from_user($user)->trigger();
4688 // Remove WS user tokens.
4689 if (!empty($CFG->passwordchangetokendeletion)) {
4690 require_once($CFG->dirroot.'/webservice/lib.php');
4691 webservice::delete_user_ws_tokens($user->id);
4695 return true;
4699 * Get a complete user record, which includes all the info in the user record.
4701 * Intended for setting as $USER session variable
4703 * @param string $field The user field to be checked for a given value.
4704 * @param string $value The value to match for $field.
4705 * @param int $mnethostid
4706 * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4707 * found. Otherwise, it will just return false.
4708 * @return mixed False, or A {@link $USER} object.
4710 function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4711 global $CFG, $DB;
4713 if (!$field || !$value) {
4714 return false;
4717 // Change the field to lowercase.
4718 $field = core_text::strtolower($field);
4720 // List of case insensitive fields.
4721 $caseinsensitivefields = ['email'];
4723 // Username input is forced to lowercase and should be case sensitive.
4724 if ($field == 'username') {
4725 $value = core_text::strtolower($value);
4728 // Build the WHERE clause for an SQL query.
4729 $params = array('fieldval' => $value);
4731 // Do a case-insensitive query, if necessary.
4732 if (in_array($field, $caseinsensitivefields)) {
4733 $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4734 } else {
4735 $fieldselect = "$field = :fieldval";
4737 $constraints = "$fieldselect AND deleted <> 1";
4739 // If we are loading user data based on anything other than id,
4740 // we must also restrict our search based on mnet host.
4741 if ($field != 'id') {
4742 if (empty($mnethostid)) {
4743 // If empty, we restrict to local users.
4744 $mnethostid = $CFG->mnet_localhost_id;
4747 if (!empty($mnethostid)) {
4748 $params['mnethostid'] = $mnethostid;
4749 $constraints .= " AND mnethostid = :mnethostid";
4752 // Get all the basic user data.
4753 try {
4754 // Make sure that there's only a single record that matches our query.
4755 // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4756 // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4757 $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST);
4758 } catch (dml_exception $exception) {
4759 if ($throwexception) {
4760 throw $exception;
4761 } else {
4762 // Return false when no records or multiple records were found.
4763 return false;
4767 // Get various settings and preferences.
4769 // Preload preference cache.
4770 check_user_preferences_loaded($user);
4772 // Load course enrolment related stuff.
4773 $user->lastcourseaccess = array(); // During last session.
4774 $user->currentcourseaccess = array(); // During current session.
4775 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4776 foreach ($lastaccesses as $lastaccess) {
4777 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4781 $sql = "SELECT g.id, g.courseid
4782 FROM {groups} g, {groups_members} gm
4783 WHERE gm.groupid=g.id AND gm.userid=?";
4785 // This is a special hack to speedup calendar display.
4786 $user->groupmember = array();
4787 if (!isguestuser($user)) {
4788 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4789 foreach ($groups as $group) {
4790 if (!array_key_exists($group->courseid, $user->groupmember)) {
4791 $user->groupmember[$group->courseid] = array();
4793 $user->groupmember[$group->courseid][$group->id] = $group->id;
4798 // Add cohort theme.
4799 if (!empty($CFG->allowcohortthemes)) {
4800 require_once($CFG->dirroot . '/cohort/lib.php');
4801 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4802 $user->cohorttheme = $cohorttheme;
4806 // Add the custom profile fields to the user record.
4807 $user->profile = array();
4808 if (!isguestuser($user)) {
4809 require_once($CFG->dirroot.'/user/profile/lib.php');
4810 profile_load_custom_fields($user);
4813 // Rewrite some variables if necessary.
4814 if (!empty($user->description)) {
4815 // No need to cart all of it around.
4816 $user->description = true;
4818 if (isguestuser($user)) {
4819 // Guest language always same as site.
4820 $user->lang = $CFG->lang;
4821 // Name always in current language.
4822 $user->firstname = get_string('guestuser');
4823 $user->lastname = ' ';
4826 return $user;
4830 * Validate a password against the configured password policy
4832 * @param string $password the password to be checked against the password policy
4833 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4834 * @return bool true if the password is valid according to the policy. false otherwise.
4836 function check_password_policy($password, &$errmsg) {
4837 global $CFG;
4839 if (empty($CFG->passwordpolicy)) {
4840 return true;
4843 $errmsg = '';
4844 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4845 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4848 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4849 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4852 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4853 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4856 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4857 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4860 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4861 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4863 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4864 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4867 if ($errmsg == '') {
4868 return true;
4869 } else {
4870 return false;
4876 * When logging in, this function is run to set certain preferences for the current SESSION.
4878 function set_login_session_preferences() {
4879 global $SESSION;
4881 $SESSION->justloggedin = true;
4883 unset($SESSION->lang);
4884 unset($SESSION->forcelang);
4885 unset($SESSION->load_navigation_admin);
4890 * Delete a course, including all related data from the database, and any associated files.
4892 * @param mixed $courseorid The id of the course or course object to delete.
4893 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4894 * @return bool true if all the removals succeeded. false if there were any failures. If this
4895 * method returns false, some of the removals will probably have succeeded, and others
4896 * failed, but you have no way of knowing which.
4898 function delete_course($courseorid, $showfeedback = true) {
4899 global $DB;
4901 if (is_object($courseorid)) {
4902 $courseid = $courseorid->id;
4903 $course = $courseorid;
4904 } else {
4905 $courseid = $courseorid;
4906 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4907 return false;
4910 $context = context_course::instance($courseid);
4912 // Frontpage course can not be deleted!!
4913 if ($courseid == SITEID) {
4914 return false;
4917 // Allow plugins to use this course before we completely delete it.
4918 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
4919 foreach ($pluginsfunction as $plugintype => $plugins) {
4920 foreach ($plugins as $pluginfunction) {
4921 $pluginfunction($course);
4926 // Make the course completely empty.
4927 remove_course_contents($courseid, $showfeedback);
4929 // Delete the course and related context instance.
4930 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4932 $DB->delete_records("course", array("id" => $courseid));
4933 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4935 // Reset all course related caches here.
4936 if (class_exists('format_base', false)) {
4937 format_base::reset_course_cache($courseid);
4940 // Trigger a course deleted event.
4941 $event = \core\event\course_deleted::create(array(
4942 'objectid' => $course->id,
4943 'context' => $context,
4944 'other' => array(
4945 'shortname' => $course->shortname,
4946 'fullname' => $course->fullname,
4947 'idnumber' => $course->idnumber
4950 $event->add_record_snapshot('course', $course);
4951 $event->trigger();
4953 return true;
4957 * Clear a course out completely, deleting all content but don't delete the course itself.
4959 * This function does not verify any permissions.
4961 * Please note this function also deletes all user enrolments,
4962 * enrolment instances and role assignments by default.
4964 * $options:
4965 * - 'keep_roles_and_enrolments' - false by default
4966 * - 'keep_groups_and_groupings' - false by default
4968 * @param int $courseid The id of the course that is being deleted
4969 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4970 * @param array $options extra options
4971 * @return bool true if all the removals succeeded. false if there were any failures. If this
4972 * method returns false, some of the removals will probably have succeeded, and others
4973 * failed, but you have no way of knowing which.
4975 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4976 global $CFG, $DB, $OUTPUT;
4978 require_once($CFG->libdir.'/badgeslib.php');
4979 require_once($CFG->libdir.'/completionlib.php');
4980 require_once($CFG->libdir.'/questionlib.php');
4981 require_once($CFG->libdir.'/gradelib.php');
4982 require_once($CFG->dirroot.'/group/lib.php');
4983 require_once($CFG->dirroot.'/comment/lib.php');
4984 require_once($CFG->dirroot.'/rating/lib.php');
4985 require_once($CFG->dirroot.'/notes/lib.php');
4987 // Handle course badges.
4988 badges_handle_course_deletion($courseid);
4990 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4991 $strdeleted = get_string('deleted').' - ';
4993 // Some crazy wishlist of stuff we should skip during purging of course content.
4994 $options = (array)$options;
4996 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
4997 $coursecontext = context_course::instance($courseid);
4998 $fs = get_file_storage();
5000 // Delete course completion information, this has to be done before grades and enrols.
5001 $cc = new completion_info($course);
5002 $cc->clear_criteria();
5003 if ($showfeedback) {
5004 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5007 // Remove all data from gradebook - this needs to be done before course modules
5008 // because while deleting this information, the system may need to reference
5009 // the course modules that own the grades.
5010 remove_course_grades($courseid, $showfeedback);
5011 remove_grade_letters($coursecontext, $showfeedback);
5013 // Delete course blocks in any all child contexts,
5014 // they may depend on modules so delete them first.
5015 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5016 foreach ($childcontexts as $childcontext) {
5017 blocks_delete_all_for_context($childcontext->id);
5019 unset($childcontexts);
5020 blocks_delete_all_for_context($coursecontext->id);
5021 if ($showfeedback) {
5022 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5025 // Get the list of all modules that are properly installed.
5026 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5028 // Delete every instance of every module,
5029 // this has to be done before deleting of course level stuff.
5030 $locations = core_component::get_plugin_list('mod');
5031 foreach ($locations as $modname => $moddir) {
5032 if ($modname === 'NEWMODULE') {
5033 continue;
5035 if (array_key_exists($modname, $allmodules)) {
5036 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5037 FROM {".$modname."} m
5038 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5039 WHERE m.course = :courseid";
5040 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5041 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5043 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5044 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5045 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
5047 if ($instances) {
5048 foreach ($instances as $cm) {
5049 if ($cm->id) {
5050 // Delete activity context questions and question categories.
5051 question_delete_activity($cm, $showfeedback);
5052 // Notify the competency subsystem.
5053 \core_competency\api::hook_course_module_deleted($cm);
5055 if (function_exists($moddelete)) {
5056 // This purges all module data in related tables, extra user prefs, settings, etc.
5057 $moddelete($cm->modinstance);
5058 } else {
5059 // NOTE: we should not allow installation of modules with missing delete support!
5060 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5061 $DB->delete_records($modname, array('id' => $cm->modinstance));
5064 if ($cm->id) {
5065 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5066 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5067 $DB->delete_records('course_modules', array('id' => $cm->id));
5071 if (function_exists($moddeletecourse)) {
5072 // Execute optional course cleanup callback. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
5073 debugging("Callback delete_course is deprecated. Function $moddeletecourse should be converted " .
5074 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER);
5075 $moddeletecourse($course, $showfeedback);
5077 if ($instances and $showfeedback) {
5078 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5080 } else {
5081 // Ooops, this module is not properly installed, force-delete it in the next block.
5085 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5087 // Delete completion defaults.
5088 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5090 // Remove all data from availability and completion tables that is associated
5091 // with course-modules belonging to this course. Note this is done even if the
5092 // features are not enabled now, in case they were enabled previously.
5093 $DB->delete_records_select('course_modules_completion',
5094 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5095 array($courseid));
5097 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5098 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5099 $allmodulesbyid = array_flip($allmodules);
5100 foreach ($cms as $cm) {
5101 if (array_key_exists($cm->module, $allmodulesbyid)) {
5102 try {
5103 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5104 } catch (Exception $e) {
5105 // Ignore weird or missing table problems.
5108 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5109 $DB->delete_records('course_modules', array('id' => $cm->id));
5112 if ($showfeedback) {
5113 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5116 // Cleanup the rest of plugins. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
5117 $cleanuplugintypes = array('report', 'coursereport', 'format');
5118 $callbacks = get_plugins_with_function('delete_course', 'lib.php');
5119 foreach ($cleanuplugintypes as $type) {
5120 if (!empty($callbacks[$type])) {
5121 foreach ($callbacks[$type] as $pluginfunction) {
5122 debugging("Callback delete_course is deprecated. Function $pluginfunction should be converted " .
5123 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER);
5124 $pluginfunction($course->id, $showfeedback);
5126 if ($showfeedback) {
5127 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5132 // Delete questions and question categories.
5133 question_delete_course($course, $showfeedback);
5134 if ($showfeedback) {
5135 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5138 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5139 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5140 foreach ($childcontexts as $childcontext) {
5141 $childcontext->delete();
5143 unset($childcontexts);
5145 // Remove roles and enrolments by default.
5146 if (empty($options['keep_roles_and_enrolments'])) {
5147 // This hack is used in restore when deleting contents of existing course.
5148 // During restore, we should remove only enrolment related data that the user performing the restore has a
5149 // permission to remove.
5150 $userid = $options['userid'] ?? null;
5151 enrol_course_delete($course, $userid);
5152 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5153 if ($showfeedback) {
5154 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5158 // Delete any groups, removing members and grouping/course links first.
5159 if (empty($options['keep_groups_and_groupings'])) {
5160 groups_delete_groupings($course->id, $showfeedback);
5161 groups_delete_groups($course->id, $showfeedback);
5164 // Filters be gone!
5165 filter_delete_all_for_context($coursecontext->id);
5167 // Notes, you shall not pass!
5168 note_delete_all($course->id);
5170 // Die comments!
5171 comment::delete_comments($coursecontext->id);
5173 // Ratings are history too.
5174 $delopt = new stdclass();
5175 $delopt->contextid = $coursecontext->id;
5176 $rm = new rating_manager();
5177 $rm->delete_ratings($delopt);
5179 // Delete course tags.
5180 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5182 // Notify the competency subsystem.
5183 \core_competency\api::hook_course_deleted($course);
5185 // Delete calendar events.
5186 $DB->delete_records('event', array('courseid' => $course->id));
5187 $fs->delete_area_files($coursecontext->id, 'calendar');
5189 // Delete all related records in other core tables that may have a courseid
5190 // This array stores the tables that need to be cleared, as
5191 // table_name => column_name that contains the course id.
5192 $tablestoclear = array(
5193 'backup_courses' => 'courseid', // Scheduled backup stuff.
5194 'user_lastaccess' => 'courseid', // User access info.
5196 foreach ($tablestoclear as $table => $col) {
5197 $DB->delete_records($table, array($col => $course->id));
5200 // Delete all course backup files.
5201 $fs->delete_area_files($coursecontext->id, 'backup');
5203 // Cleanup course record - remove links to deleted stuff.
5204 $oldcourse = new stdClass();
5205 $oldcourse->id = $course->id;
5206 $oldcourse->summary = '';
5207 $oldcourse->cacherev = 0;
5208 $oldcourse->legacyfiles = 0;
5209 if (!empty($options['keep_groups_and_groupings'])) {
5210 $oldcourse->defaultgroupingid = 0;
5212 $DB->update_record('course', $oldcourse);
5214 // Delete course sections.
5215 $DB->delete_records('course_sections', array('course' => $course->id));
5217 // Delete legacy, section and any other course files.
5218 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5220 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5221 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5222 // Easy, do not delete the context itself...
5223 $coursecontext->delete_content();
5224 } else {
5225 // Hack alert!!!!
5226 // We can not drop all context stuff because it would bork enrolments and roles,
5227 // there might be also files used by enrol plugins...
5230 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5231 // also some non-standard unsupported plugins may try to store something there.
5232 fulldelete($CFG->dataroot.'/'.$course->id);
5234 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5235 $cachemodinfo = cache::make('core', 'coursemodinfo');
5236 $cachemodinfo->delete($courseid);
5238 // Trigger a course content deleted event.
5239 $event = \core\event\course_content_deleted::create(array(
5240 'objectid' => $course->id,
5241 'context' => $coursecontext,
5242 'other' => array('shortname' => $course->shortname,
5243 'fullname' => $course->fullname,
5244 'options' => $options) // Passing this for legacy reasons.
5246 $event->add_record_snapshot('course', $course);
5247 $event->trigger();
5249 return true;
5253 * Change dates in module - used from course reset.
5255 * @param string $modname forum, assignment, etc
5256 * @param array $fields array of date fields from mod table
5257 * @param int $timeshift time difference
5258 * @param int $courseid
5259 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5260 * @return bool success
5262 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5263 global $CFG, $DB;
5264 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5266 $return = true;
5267 $params = array($timeshift, $courseid);
5268 foreach ($fields as $field) {
5269 $updatesql = "UPDATE {".$modname."}
5270 SET $field = $field + ?
5271 WHERE course=? AND $field<>0";
5272 if ($modid) {
5273 $updatesql .= ' AND id=?';
5274 $params[] = $modid;
5276 $return = $DB->execute($updatesql, $params) && $return;
5279 return $return;
5283 * This function will empty a course of user data.
5284 * It will retain the activities and the structure of the course.
5286 * @param object $data an object containing all the settings including courseid (without magic quotes)
5287 * @return array status array of array component, item, error
5289 function reset_course_userdata($data) {
5290 global $CFG, $DB;
5291 require_once($CFG->libdir.'/gradelib.php');
5292 require_once($CFG->libdir.'/completionlib.php');
5293 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5294 require_once($CFG->dirroot.'/group/lib.php');
5296 $data->courseid = $data->id;
5297 $context = context_course::instance($data->courseid);
5299 $eventparams = array(
5300 'context' => $context,
5301 'courseid' => $data->id,
5302 'other' => array(
5303 'reset_options' => (array) $data
5306 $event = \core\event\course_reset_started::create($eventparams);
5307 $event->trigger();
5309 // Calculate the time shift of dates.
5310 if (!empty($data->reset_start_date)) {
5311 // Time part of course startdate should be zero.
5312 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5313 } else {
5314 $data->timeshift = 0;
5317 // Result array: component, item, error.
5318 $status = array();
5320 // Start the resetting.
5321 $componentstr = get_string('general');
5323 // Move the course start time.
5324 if (!empty($data->reset_start_date) and $data->timeshift) {
5325 // Change course start data.
5326 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5327 // Update all course and group events - do not move activity events.
5328 $updatesql = "UPDATE {event}
5329 SET timestart = timestart + ?
5330 WHERE courseid=? AND instance=0";
5331 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5333 // Update any date activity restrictions.
5334 if ($CFG->enableavailability) {
5335 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5338 // Update completion expected dates.
5339 if ($CFG->enablecompletion) {
5340 $modinfo = get_fast_modinfo($data->courseid);
5341 $changed = false;
5342 foreach ($modinfo->get_cms() as $cm) {
5343 if ($cm->completion && !empty($cm->completionexpected)) {
5344 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5345 array('id' => $cm->id));
5346 $changed = true;
5350 // Clear course cache if changes made.
5351 if ($changed) {
5352 rebuild_course_cache($data->courseid, true);
5355 // Update course date completion criteria.
5356 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5359 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5362 if (!empty($data->reset_end_date)) {
5363 // If the user set a end date value respect it.
5364 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5365 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5366 // If there is a time shift apply it to the end date as well.
5367 $enddate = $data->reset_end_date_old + $data->timeshift;
5368 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5371 if (!empty($data->reset_events)) {
5372 $DB->delete_records('event', array('courseid' => $data->courseid));
5373 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5376 if (!empty($data->reset_notes)) {
5377 require_once($CFG->dirroot.'/notes/lib.php');
5378 note_delete_all($data->courseid);
5379 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5382 if (!empty($data->delete_blog_associations)) {
5383 require_once($CFG->dirroot.'/blog/lib.php');
5384 blog_remove_associations_for_course($data->courseid);
5385 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5388 if (!empty($data->reset_completion)) {
5389 // Delete course and activity completion information.
5390 $course = $DB->get_record('course', array('id' => $data->courseid));
5391 $cc = new completion_info($course);
5392 $cc->delete_all_completion_data();
5393 $status[] = array('component' => $componentstr,
5394 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5397 if (!empty($data->reset_competency_ratings)) {
5398 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5399 $status[] = array('component' => $componentstr,
5400 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5403 $componentstr = get_string('roles');
5405 if (!empty($data->reset_roles_overrides)) {
5406 $children = $context->get_child_contexts();
5407 foreach ($children as $child) {
5408 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5410 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5411 // Force refresh for logged in users.
5412 $context->mark_dirty();
5413 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5416 if (!empty($data->reset_roles_local)) {
5417 $children = $context->get_child_contexts();
5418 foreach ($children as $child) {
5419 role_unassign_all(array('contextid' => $child->id));
5421 // Force refresh for logged in users.
5422 $context->mark_dirty();
5423 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5426 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5427 $data->unenrolled = array();
5428 if (!empty($data->unenrol_users)) {
5429 $plugins = enrol_get_plugins(true);
5430 $instances = enrol_get_instances($data->courseid, true);
5431 foreach ($instances as $key => $instance) {
5432 if (!isset($plugins[$instance->enrol])) {
5433 unset($instances[$key]);
5434 continue;
5438 $usersroles = enrol_get_course_users_roles($data->courseid);
5439 foreach ($data->unenrol_users as $withroleid) {
5440 if ($withroleid) {
5441 $sql = "SELECT ue.*
5442 FROM {user_enrolments} ue
5443 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5444 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5445 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5446 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5448 } else {
5449 // Without any role assigned at course context.
5450 $sql = "SELECT ue.*
5451 FROM {user_enrolments} ue
5452 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5453 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5454 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5455 WHERE ra.id IS null";
5456 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5459 $rs = $DB->get_recordset_sql($sql, $params);
5460 foreach ($rs as $ue) {
5461 if (!isset($instances[$ue->enrolid])) {
5462 continue;
5464 $instance = $instances[$ue->enrolid];
5465 $plugin = $plugins[$instance->enrol];
5466 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5467 continue;
5470 if ($withroleid && count($usersroles[$ue->userid]) > 1) {
5471 // If we don't remove all roles and user has more than one role, just remove this role.
5472 role_unassign($withroleid, $ue->userid, $context->id);
5474 unset($usersroles[$ue->userid][$withroleid]);
5475 } else {
5476 // If we remove all roles or user has only one role, unenrol user from course.
5477 $plugin->unenrol_user($instance, $ue->userid);
5479 $data->unenrolled[$ue->userid] = $ue->userid;
5481 $rs->close();
5484 if (!empty($data->unenrolled)) {
5485 $status[] = array(
5486 'component' => $componentstr,
5487 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5488 'error' => false
5492 $componentstr = get_string('groups');
5494 // Remove all group members.
5495 if (!empty($data->reset_groups_members)) {
5496 groups_delete_group_members($data->courseid);
5497 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5500 // Remove all groups.
5501 if (!empty($data->reset_groups_remove)) {
5502 groups_delete_groups($data->courseid, false);
5503 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5506 // Remove all grouping members.
5507 if (!empty($data->reset_groupings_members)) {
5508 groups_delete_groupings_groups($data->courseid, false);
5509 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5512 // Remove all groupings.
5513 if (!empty($data->reset_groupings_remove)) {
5514 groups_delete_groupings($data->courseid, false);
5515 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5518 // Look in every instance of every module for data to delete.
5519 $unsupportedmods = array();
5520 if ($allmods = $DB->get_records('modules') ) {
5521 foreach ($allmods as $mod) {
5522 $modname = $mod->name;
5523 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5524 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5525 if (file_exists($modfile)) {
5526 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5527 continue; // Skip mods with no instances.
5529 include_once($modfile);
5530 if (function_exists($moddeleteuserdata)) {
5531 $modstatus = $moddeleteuserdata($data);
5532 if (is_array($modstatus)) {
5533 $status = array_merge($status, $modstatus);
5534 } else {
5535 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5537 } else {
5538 $unsupportedmods[] = $mod;
5540 } else {
5541 debugging('Missing lib.php in '.$modname.' module!');
5543 // Update calendar events for all modules.
5544 course_module_bulk_update_calendar_events($modname, $data->courseid);
5548 // Mention unsupported mods.
5549 if (!empty($unsupportedmods)) {
5550 foreach ($unsupportedmods as $mod) {
5551 $status[] = array(
5552 'component' => get_string('modulenameplural', $mod->name),
5553 'item' => '',
5554 'error' => get_string('resetnotimplemented')
5559 $componentstr = get_string('gradebook', 'grades');
5560 // Reset gradebook,.
5561 if (!empty($data->reset_gradebook_items)) {
5562 remove_course_grades($data->courseid, false);
5563 grade_grab_course_grades($data->courseid);
5564 grade_regrade_final_grades($data->courseid);
5565 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5567 } else if (!empty($data->reset_gradebook_grades)) {
5568 grade_course_reset($data->courseid);
5569 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5571 // Reset comments.
5572 if (!empty($data->reset_comments)) {
5573 require_once($CFG->dirroot.'/comment/lib.php');
5574 comment::reset_course_page_comments($context);
5577 $event = \core\event\course_reset_ended::create($eventparams);
5578 $event->trigger();
5580 return $status;
5584 * Generate an email processing address.
5586 * @param int $modid
5587 * @param string $modargs
5588 * @return string Returns email processing address
5590 function generate_email_processing_address($modid, $modargs) {
5591 global $CFG;
5593 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5594 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5600 * @todo Finish documenting this function
5602 * @param string $modargs
5603 * @param string $body Currently unused
5605 function moodle_process_email($modargs, $body) {
5606 global $DB;
5608 // The first char should be an unencoded letter. We'll take this as an action.
5609 switch ($modargs{0}) {
5610 case 'B': { // Bounce.
5611 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5612 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5613 // Check the half md5 of their email.
5614 $md5check = substr(md5($user->email), 0, 16);
5615 if ($md5check == substr($modargs, -16)) {
5616 set_bounce_count($user);
5618 // Else maybe they've already changed it?
5621 break;
5622 // Maybe more later?
5626 // CORRESPONDENCE.
5629 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5631 * @param string $action 'get', 'buffer', 'close' or 'flush'
5632 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5634 function get_mailer($action='get') {
5635 global $CFG;
5637 /** @var moodle_phpmailer $mailer */
5638 static $mailer = null;
5639 static $counter = 0;
5641 if (!isset($CFG->smtpmaxbulk)) {
5642 $CFG->smtpmaxbulk = 1;
5645 if ($action == 'get') {
5646 $prevkeepalive = false;
5648 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5649 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5650 $counter++;
5651 // Reset the mailer.
5652 $mailer->Priority = 3;
5653 $mailer->CharSet = 'UTF-8'; // Our default.
5654 $mailer->ContentType = "text/plain";
5655 $mailer->Encoding = "8bit";
5656 $mailer->From = "root@localhost";
5657 $mailer->FromName = "Root User";
5658 $mailer->Sender = "";
5659 $mailer->Subject = "";
5660 $mailer->Body = "";
5661 $mailer->AltBody = "";
5662 $mailer->ConfirmReadingTo = "";
5664 $mailer->clearAllRecipients();
5665 $mailer->clearReplyTos();
5666 $mailer->clearAttachments();
5667 $mailer->clearCustomHeaders();
5668 return $mailer;
5671 $prevkeepalive = $mailer->SMTPKeepAlive;
5672 get_mailer('flush');
5675 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5676 $mailer = new moodle_phpmailer();
5678 $counter = 1;
5680 if ($CFG->smtphosts == 'qmail') {
5681 // Use Qmail system.
5682 $mailer->isQmail();
5684 } else if (empty($CFG->smtphosts)) {
5685 // Use PHP mail() = sendmail.
5686 $mailer->isMail();
5688 } else {
5689 // Use SMTP directly.
5690 $mailer->isSMTP();
5691 if (!empty($CFG->debugsmtp) && (!empty($CFG->debugdeveloper))) {
5692 $mailer->SMTPDebug = 3;
5694 // Specify main and backup servers.
5695 $mailer->Host = $CFG->smtphosts;
5696 // Specify secure connection protocol.
5697 $mailer->SMTPSecure = $CFG->smtpsecure;
5698 // Use previous keepalive.
5699 $mailer->SMTPKeepAlive = $prevkeepalive;
5701 if ($CFG->smtpuser) {
5702 // Use SMTP authentication.
5703 $mailer->SMTPAuth = true;
5704 $mailer->Username = $CFG->smtpuser;
5705 $mailer->Password = $CFG->smtppass;
5709 return $mailer;
5712 $nothing = null;
5714 // Keep smtp session open after sending.
5715 if ($action == 'buffer') {
5716 if (!empty($CFG->smtpmaxbulk)) {
5717 get_mailer('flush');
5718 $m = get_mailer();
5719 if ($m->Mailer == 'smtp') {
5720 $m->SMTPKeepAlive = true;
5723 return $nothing;
5726 // Close smtp session, but continue buffering.
5727 if ($action == 'flush') {
5728 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5729 if (!empty($mailer->SMTPDebug)) {
5730 echo '<pre>'."\n";
5732 $mailer->SmtpClose();
5733 if (!empty($mailer->SMTPDebug)) {
5734 echo '</pre>';
5737 return $nothing;
5740 // Close smtp session, do not buffer anymore.
5741 if ($action == 'close') {
5742 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5743 get_mailer('flush');
5744 $mailer->SMTPKeepAlive = false;
5746 $mailer = null; // Better force new instance.
5747 return $nothing;
5752 * A helper function to test for email diversion
5754 * @param string $email
5755 * @return bool Returns true if the email should be diverted
5757 function email_should_be_diverted($email) {
5758 global $CFG;
5760 if (empty($CFG->divertallemailsto)) {
5761 return false;
5764 if (empty($CFG->divertallemailsexcept)) {
5765 return true;
5768 $patterns = array_map('trim', explode(',', $CFG->divertallemailsexcept));
5769 foreach ($patterns as $pattern) {
5770 if (preg_match("/$pattern/", $email)) {
5771 return false;
5775 return true;
5779 * Generate a unique email Message-ID using the moodle domain and install path
5781 * @param string $localpart An optional unique message id prefix.
5782 * @return string The formatted ID ready for appending to the email headers.
5784 function generate_email_messageid($localpart = null) {
5785 global $CFG;
5787 $urlinfo = parse_url($CFG->wwwroot);
5788 $base = '@' . $urlinfo['host'];
5790 // If multiple moodles are on the same domain we want to tell them
5791 // apart so we add the install path to the local part. This means
5792 // that the id local part should never contain a / character so
5793 // we can correctly parse the id to reassemble the wwwroot.
5794 if (isset($urlinfo['path'])) {
5795 $base = $urlinfo['path'] . $base;
5798 if (empty($localpart)) {
5799 $localpart = uniqid('', true);
5802 // Because we may have an option /installpath suffix to the local part
5803 // of the id we need to escape any / chars which are in the $localpart.
5804 $localpart = str_replace('/', '%2F', $localpart);
5806 return '<' . $localpart . $base . '>';
5810 * Send an email to a specified user
5812 * @param stdClass $user A {@link $USER} object
5813 * @param stdClass $from A {@link $USER} object
5814 * @param string $subject plain text subject line of the email
5815 * @param string $messagetext plain text version of the message
5816 * @param string $messagehtml complete html version of the message (optional)
5817 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5818 * @param string $attachname the name of the file (extension indicates MIME)
5819 * @param bool $usetrueaddress determines whether $from email address should
5820 * be sent out. Will be overruled by user profile setting for maildisplay
5821 * @param string $replyto Email address to reply to
5822 * @param string $replytoname Name of reply to recipient
5823 * @param int $wordwrapwidth custom word wrap width, default 79
5824 * @return bool Returns true if mail was sent OK and false if there was an error.
5826 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5827 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5829 global $CFG, $PAGE, $SITE;
5831 if (empty($user) or empty($user->id)) {
5832 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5833 return false;
5836 if (empty($user->email)) {
5837 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5838 return false;
5841 if (!empty($user->deleted)) {
5842 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5843 return false;
5846 if (defined('BEHAT_SITE_RUNNING')) {
5847 // Fake email sending in behat.
5848 return true;
5851 if (!empty($CFG->noemailever)) {
5852 // Hidden setting for development sites, set in config.php if needed.
5853 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5854 return true;
5857 if (email_should_be_diverted($user->email)) {
5858 $subject = "[DIVERTED {$user->email}] $subject";
5859 $user = clone($user);
5860 $user->email = $CFG->divertallemailsto;
5863 // Skip mail to suspended users.
5864 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5865 return true;
5868 if (!validate_email($user->email)) {
5869 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5870 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5871 return false;
5874 if (over_bounce_threshold($user)) {
5875 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5876 return false;
5879 // TLD .invalid is specifically reserved for invalid domain names.
5880 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5881 if (substr($user->email, -8) == '.invalid') {
5882 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5883 return true; // This is not an error.
5886 // If the user is a remote mnet user, parse the email text for URL to the
5887 // wwwroot and modify the url to direct the user's browser to login at their
5888 // home site (identity provider - idp) before hitting the link itself.
5889 if (is_mnet_remote_user($user)) {
5890 require_once($CFG->dirroot.'/mnet/lib.php');
5892 $jumpurl = mnet_get_idp_jump_url($user);
5893 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5895 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5896 $callback,
5897 $messagetext);
5898 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5899 $callback,
5900 $messagehtml);
5902 $mail = get_mailer();
5904 if (!empty($mail->SMTPDebug)) {
5905 echo '<pre>' . "\n";
5908 $temprecipients = array();
5909 $tempreplyto = array();
5911 // Make sure that we fall back onto some reasonable no-reply address.
5912 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
5913 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
5915 if (!validate_email($noreplyaddress)) {
5916 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
5917 $noreplyaddress = $noreplyaddressdefault;
5920 // Make up an email address for handling bounces.
5921 if (!empty($CFG->handlebounces)) {
5922 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5923 $mail->Sender = generate_email_processing_address(0, $modargs);
5924 } else {
5925 $mail->Sender = $noreplyaddress;
5928 // Make sure that the explicit replyto is valid, fall back to the implicit one.
5929 if (!empty($replyto) && !validate_email($replyto)) {
5930 debugging('email_to_user: Invalid replyto-email '.s($replyto));
5931 $replyto = $noreplyaddress;
5934 if (is_string($from)) { // So we can pass whatever we want if there is need.
5935 $mail->From = $noreplyaddress;
5936 $mail->FromName = $from;
5937 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
5938 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
5939 // in a course with the sender.
5940 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
5941 if (!validate_email($from->email)) {
5942 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
5943 // Better not to use $noreplyaddress in this case.
5944 return false;
5946 $mail->From = $from->email;
5947 $fromdetails = new stdClass();
5948 $fromdetails->name = fullname($from);
5949 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5950 $fromdetails->siteshortname = format_string($SITE->shortname);
5951 $fromstring = $fromdetails->name;
5952 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
5953 $fromstring = get_string('emailvia', 'core', $fromdetails);
5955 $mail->FromName = $fromstring;
5956 if (empty($replyto)) {
5957 $tempreplyto[] = array($from->email, fullname($from));
5959 } else {
5960 $mail->From = $noreplyaddress;
5961 $fromdetails = new stdClass();
5962 $fromdetails->name = fullname($from);
5963 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5964 $fromdetails->siteshortname = format_string($SITE->shortname);
5965 $fromstring = $fromdetails->name;
5966 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
5967 $fromstring = get_string('emailvia', 'core', $fromdetails);
5969 $mail->FromName = $fromstring;
5970 if (empty($replyto)) {
5971 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
5975 if (!empty($replyto)) {
5976 $tempreplyto[] = array($replyto, $replytoname);
5979 $temprecipients[] = array($user->email, fullname($user));
5981 // Set word wrap.
5982 $mail->WordWrap = $wordwrapwidth;
5984 if (!empty($from->customheaders)) {
5985 // Add custom headers.
5986 if (is_array($from->customheaders)) {
5987 foreach ($from->customheaders as $customheader) {
5988 $mail->addCustomHeader($customheader);
5990 } else {
5991 $mail->addCustomHeader($from->customheaders);
5995 // If the X-PHP-Originating-Script email header is on then also add an additional
5996 // header with details of where exactly in moodle the email was triggered from,
5997 // either a call to message_send() or to email_to_user().
5998 if (ini_get('mail.add_x_header')) {
6000 $stack = debug_backtrace(false);
6001 $origin = $stack[0];
6003 foreach ($stack as $depth => $call) {
6004 if ($call['function'] == 'message_send') {
6005 $origin = $call;
6009 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
6010 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
6011 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
6014 if (!empty($from->priority)) {
6015 $mail->Priority = $from->priority;
6018 $renderer = $PAGE->get_renderer('core');
6019 $context = array(
6020 'sitefullname' => $SITE->fullname,
6021 'siteshortname' => $SITE->shortname,
6022 'sitewwwroot' => $CFG->wwwroot,
6023 'subject' => $subject,
6024 'to' => $user->email,
6025 'toname' => fullname($user),
6026 'from' => $mail->From,
6027 'fromname' => $mail->FromName,
6029 if (!empty($tempreplyto[0])) {
6030 $context['replyto'] = $tempreplyto[0][0];
6031 $context['replytoname'] = $tempreplyto[0][1];
6033 if ($user->id > 0) {
6034 $context['touserid'] = $user->id;
6035 $context['tousername'] = $user->username;
6038 if (!empty($user->mailformat) && $user->mailformat == 1) {
6039 // Only process html templates if the user preferences allow html email.
6041 if ($messagehtml) {
6042 // If html has been given then pass it through the template.
6043 $context['body'] = $messagehtml;
6044 $messagehtml = $renderer->render_from_template('core/email_html', $context);
6046 } else {
6047 // If no html has been given, BUT there is an html wrapping template then
6048 // auto convert the text to html and then wrap it.
6049 $autohtml = trim(text_to_html($messagetext));
6050 $context['body'] = $autohtml;
6051 $temphtml = $renderer->render_from_template('core/email_html', $context);
6052 if ($autohtml != $temphtml) {
6053 $messagehtml = $temphtml;
6058 $context['body'] = $messagetext;
6059 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
6060 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
6061 $messagetext = $renderer->render_from_template('core/email_text', $context);
6063 // Autogenerate a MessageID if it's missing.
6064 if (empty($mail->MessageID)) {
6065 $mail->MessageID = generate_email_messageid();
6068 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6069 // Don't ever send HTML to users who don't want it.
6070 $mail->isHTML(true);
6071 $mail->Encoding = 'quoted-printable';
6072 $mail->Body = $messagehtml;
6073 $mail->AltBody = "\n$messagetext\n";
6074 } else {
6075 $mail->IsHTML(false);
6076 $mail->Body = "\n$messagetext\n";
6079 if ($attachment && $attachname) {
6080 if (preg_match( "~\\.\\.~" , $attachment )) {
6081 // Security check for ".." in dir path.
6082 $supportuser = core_user::get_support_user();
6083 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6084 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6085 } else {
6086 require_once($CFG->libdir.'/filelib.php');
6087 $mimetype = mimeinfo('type', $attachname);
6089 $attachmentpath = $attachment;
6091 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6092 $attachpath = str_replace('\\', '/', $attachmentpath);
6093 // Make sure both variables are normalised before comparing.
6094 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
6096 // If the attachment is a full path to a file in the tempdir, use it as is,
6097 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6098 if (strpos($attachpath, $temppath) !== 0) {
6099 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
6102 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
6106 // Check if the email should be sent in an other charset then the default UTF-8.
6107 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6109 // Use the defined site mail charset or eventually the one preferred by the recipient.
6110 $charset = $CFG->sitemailcharset;
6111 if (!empty($CFG->allowusermailcharset)) {
6112 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6113 $charset = $useremailcharset;
6117 // Convert all the necessary strings if the charset is supported.
6118 $charsets = get_list_of_charsets();
6119 unset($charsets['UTF-8']);
6120 if (in_array($charset, $charsets)) {
6121 $mail->CharSet = $charset;
6122 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6123 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6124 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6125 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6127 foreach ($temprecipients as $key => $values) {
6128 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6130 foreach ($tempreplyto as $key => $values) {
6131 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6136 foreach ($temprecipients as $values) {
6137 $mail->addAddress($values[0], $values[1]);
6139 foreach ($tempreplyto as $values) {
6140 $mail->addReplyTo($values[0], $values[1]);
6143 if ($mail->send()) {
6144 set_send_count($user);
6145 if (!empty($mail->SMTPDebug)) {
6146 echo '</pre>';
6148 return true;
6149 } else {
6150 // Trigger event for failing to send email.
6151 $event = \core\event\email_failed::create(array(
6152 'context' => context_system::instance(),
6153 'userid' => $from->id,
6154 'relateduserid' => $user->id,
6155 'other' => array(
6156 'subject' => $subject,
6157 'message' => $messagetext,
6158 'errorinfo' => $mail->ErrorInfo
6161 $event->trigger();
6162 if (CLI_SCRIPT) {
6163 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6165 if (!empty($mail->SMTPDebug)) {
6166 echo '</pre>';
6168 return false;
6173 * Check to see if a user's real email address should be used for the "From" field.
6175 * @param object $from The user object for the user we are sending the email from.
6176 * @param object $user The user object that we are sending the email to.
6177 * @param array $unused No longer used.
6178 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6180 function can_send_from_real_email_address($from, $user, $unused = null) {
6181 global $CFG;
6182 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6183 return false;
6185 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6186 // Email is in the list of allowed domains for sending email,
6187 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6188 // in a course with the sender.
6189 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6190 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6191 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6192 && enrol_get_shared_courses($user, $from, false, true)))) {
6193 return true;
6195 return false;
6199 * Generate a signoff for emails based on support settings
6201 * @return string
6203 function generate_email_signoff() {
6204 global $CFG;
6206 $signoff = "\n";
6207 if (!empty($CFG->supportname)) {
6208 $signoff .= $CFG->supportname."\n";
6210 if (!empty($CFG->supportemail)) {
6211 $signoff .= $CFG->supportemail."\n";
6213 if (!empty($CFG->supportpage)) {
6214 $signoff .= $CFG->supportpage."\n";
6216 return $signoff;
6220 * Sets specified user's password and send the new password to the user via email.
6222 * @param stdClass $user A {@link $USER} object
6223 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6224 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6226 function setnew_password_and_mail($user, $fasthash = false) {
6227 global $CFG, $DB;
6229 // We try to send the mail in language the user understands,
6230 // unfortunately the filter_string() does not support alternative langs yet
6231 // so multilang will not work properly for site->fullname.
6232 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6234 $site = get_site();
6236 $supportuser = core_user::get_support_user();
6238 $newpassword = generate_password();
6240 update_internal_user_password($user, $newpassword, $fasthash);
6242 $a = new stdClass();
6243 $a->firstname = fullname($user, true);
6244 $a->sitename = format_string($site->fullname);
6245 $a->username = $user->username;
6246 $a->newpassword = $newpassword;
6247 $a->link = $CFG->wwwroot .'/login/?lang='.$lang;
6248 $a->signoff = generate_email_signoff();
6250 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6252 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6254 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6255 return email_to_user($user, $supportuser, $subject, $message);
6260 * Resets specified user's password and send the new password to the user via email.
6262 * @param stdClass $user A {@link $USER} object
6263 * @return bool Returns true if mail was sent OK and false if there was an error.
6265 function reset_password_and_mail($user) {
6266 global $CFG;
6268 $site = get_site();
6269 $supportuser = core_user::get_support_user();
6271 $userauth = get_auth_plugin($user->auth);
6272 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6273 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6274 return false;
6277 $newpassword = generate_password();
6279 if (!$userauth->user_update_password($user, $newpassword)) {
6280 print_error("cannotsetpassword");
6283 $a = new stdClass();
6284 $a->firstname = $user->firstname;
6285 $a->lastname = $user->lastname;
6286 $a->sitename = format_string($site->fullname);
6287 $a->username = $user->username;
6288 $a->newpassword = $newpassword;
6289 $a->link = $CFG->wwwroot .'/login/change_password.php';
6290 $a->signoff = generate_email_signoff();
6292 $message = get_string('newpasswordtext', '', $a);
6294 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6296 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6298 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6299 return email_to_user($user, $supportuser, $subject, $message);
6303 * Send email to specified user with confirmation text and activation link.
6305 * @param stdClass $user A {@link $USER} object
6306 * @param string $confirmationurl user confirmation URL
6307 * @return bool Returns true if mail was sent OK and false if there was an error.
6309 function send_confirmation_email($user, $confirmationurl = null) {
6310 global $CFG;
6312 $site = get_site();
6313 $supportuser = core_user::get_support_user();
6315 $data = new stdClass();
6316 $data->firstname = fullname($user);
6317 $data->sitename = format_string($site->fullname);
6318 $data->admin = generate_email_signoff();
6320 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6322 if (empty($confirmationurl)) {
6323 $confirmationurl = '/login/confirm.php';
6326 $confirmationurl = new moodle_url($confirmationurl);
6327 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6328 $confirmationurl->remove_params('data');
6329 $confirmationpath = $confirmationurl->out(false);
6331 // We need to custom encode the username to include trailing dots in the link.
6332 // Because of this custom encoding we can't use moodle_url directly.
6333 // Determine if a query string is present in the confirmation url.
6334 $hasquerystring = strpos($confirmationpath, '?') !== false;
6335 // Perform normal url encoding of the username first.
6336 $username = urlencode($user->username);
6337 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6338 $username = str_replace('.', '%2E', $username);
6340 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6342 $message = get_string('emailconfirmation', '', $data);
6343 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6345 $user->mailformat = 1; // Always send HTML version as well.
6347 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6348 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6352 * Sends a password change confirmation email.
6354 * @param stdClass $user A {@link $USER} object
6355 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6356 * @return bool Returns true if mail was sent OK and false if there was an error.
6358 function send_password_change_confirmation_email($user, $resetrecord) {
6359 global $CFG;
6361 $site = get_site();
6362 $supportuser = core_user::get_support_user();
6363 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6365 $data = new stdClass();
6366 $data->firstname = $user->firstname;
6367 $data->lastname = $user->lastname;
6368 $data->username = $user->username;
6369 $data->sitename = format_string($site->fullname);
6370 $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6371 $data->admin = generate_email_signoff();
6372 $data->resetminutes = $pwresetmins;
6374 $message = get_string('emailresetconfirmation', '', $data);
6375 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6377 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6378 return email_to_user($user, $supportuser, $subject, $message);
6383 * Sends an email containinginformation on how to change your password.
6385 * @param stdClass $user A {@link $USER} object
6386 * @return bool Returns true if mail was sent OK and false if there was an error.
6388 function send_password_change_info($user) {
6389 global $CFG;
6391 $site = get_site();
6392 $supportuser = core_user::get_support_user();
6393 $systemcontext = context_system::instance();
6395 $data = new stdClass();
6396 $data->firstname = $user->firstname;
6397 $data->lastname = $user->lastname;
6398 $data->username = $user->username;
6399 $data->sitename = format_string($site->fullname);
6400 $data->admin = generate_email_signoff();
6402 $userauth = get_auth_plugin($user->auth);
6404 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6405 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6406 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6407 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6408 return email_to_user($user, $supportuser, $subject, $message);
6411 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6412 // We have some external url for password changing.
6413 $data->link .= $userauth->change_password_url();
6415 } else {
6416 // No way to change password, sorry.
6417 $data->link = '';
6420 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6421 $message = get_string('emailpasswordchangeinfo', '', $data);
6422 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6423 } else {
6424 $message = get_string('emailpasswordchangeinfofail', '', $data);
6425 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6428 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6429 return email_to_user($user, $supportuser, $subject, $message);
6434 * Check that an email is allowed. It returns an error message if there was a problem.
6436 * @param string $email Content of email
6437 * @return string|false
6439 function email_is_not_allowed($email) {
6440 global $CFG;
6442 // Comparing lowercase domains.
6443 $email = strtolower($email);
6444 if (!empty($CFG->allowemailaddresses)) {
6445 $allowed = explode(' ', strtolower($CFG->allowemailaddresses));
6446 foreach ($allowed as $allowedpattern) {
6447 $allowedpattern = trim($allowedpattern);
6448 if (!$allowedpattern) {
6449 continue;
6451 if (strpos($allowedpattern, '.') === 0) {
6452 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6453 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6454 return false;
6457 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6458 return false;
6461 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6463 } else if (!empty($CFG->denyemailaddresses)) {
6464 $denied = explode(' ', strtolower($CFG->denyemailaddresses));
6465 foreach ($denied as $deniedpattern) {
6466 $deniedpattern = trim($deniedpattern);
6467 if (!$deniedpattern) {
6468 continue;
6470 if (strpos($deniedpattern, '.') === 0) {
6471 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6472 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6473 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6476 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6477 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6482 return false;
6485 // FILE HANDLING.
6488 * Returns local file storage instance
6490 * @return file_storage
6492 function get_file_storage($reset = false) {
6493 global $CFG;
6495 static $fs = null;
6497 if ($reset) {
6498 $fs = null;
6499 return;
6502 if ($fs) {
6503 return $fs;
6506 require_once("$CFG->libdir/filelib.php");
6508 $fs = new file_storage();
6510 return $fs;
6514 * Returns local file storage instance
6516 * @return file_browser
6518 function get_file_browser() {
6519 global $CFG;
6521 static $fb = null;
6523 if ($fb) {
6524 return $fb;
6527 require_once("$CFG->libdir/filelib.php");
6529 $fb = new file_browser();
6531 return $fb;
6535 * Returns file packer
6537 * @param string $mimetype default application/zip
6538 * @return file_packer
6540 function get_file_packer($mimetype='application/zip') {
6541 global $CFG;
6543 static $fp = array();
6545 if (isset($fp[$mimetype])) {
6546 return $fp[$mimetype];
6549 switch ($mimetype) {
6550 case 'application/zip':
6551 case 'application/vnd.moodle.profiling':
6552 $classname = 'zip_packer';
6553 break;
6555 case 'application/x-gzip' :
6556 $classname = 'tgz_packer';
6557 break;
6559 case 'application/vnd.moodle.backup':
6560 $classname = 'mbz_packer';
6561 break;
6563 default:
6564 return false;
6567 require_once("$CFG->libdir/filestorage/$classname.php");
6568 $fp[$mimetype] = new $classname();
6570 return $fp[$mimetype];
6574 * Returns current name of file on disk if it exists.
6576 * @param string $newfile File to be verified
6577 * @return string Current name of file on disk if true
6579 function valid_uploaded_file($newfile) {
6580 if (empty($newfile)) {
6581 return '';
6583 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6584 return $newfile['tmp_name'];
6585 } else {
6586 return '';
6591 * Returns the maximum size for uploading files.
6593 * There are seven possible upload limits:
6594 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6595 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6596 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6597 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6598 * 5. by the Moodle admin in $CFG->maxbytes
6599 * 6. by the teacher in the current course $course->maxbytes
6600 * 7. by the teacher for the current module, eg $assignment->maxbytes
6602 * These last two are passed to this function as arguments (in bytes).
6603 * Anything defined as 0 is ignored.
6604 * The smallest of all the non-zero numbers is returned.
6606 * @todo Finish documenting this function
6608 * @param int $sitebytes Set maximum size
6609 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6610 * @param int $modulebytes Current module ->maxbytes (in bytes)
6611 * @param bool $unused This parameter has been deprecated and is not used any more.
6612 * @return int The maximum size for uploading files.
6614 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6616 if (! $filesize = ini_get('upload_max_filesize')) {
6617 $filesize = '5M';
6619 $minimumsize = get_real_size($filesize);
6621 if ($postsize = ini_get('post_max_size')) {
6622 $postsize = get_real_size($postsize);
6623 if ($postsize < $minimumsize) {
6624 $minimumsize = $postsize;
6628 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6629 $minimumsize = $sitebytes;
6632 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6633 $minimumsize = $coursebytes;
6636 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6637 $minimumsize = $modulebytes;
6640 return $minimumsize;
6644 * Returns the maximum size for uploading files for the current user
6646 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6648 * @param context $context The context in which to check user capabilities
6649 * @param int $sitebytes Set maximum size
6650 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6651 * @param int $modulebytes Current module ->maxbytes (in bytes)
6652 * @param stdClass $user The user
6653 * @param bool $unused This parameter has been deprecated and is not used any more.
6654 * @return int The maximum size for uploading files.
6656 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6657 $unused = false) {
6658 global $USER;
6660 if (empty($user)) {
6661 $user = $USER;
6664 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6665 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6668 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6672 * Returns an array of possible sizes in local language
6674 * Related to {@link get_max_upload_file_size()} - this function returns an
6675 * array of possible sizes in an array, translated to the
6676 * local language.
6678 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6680 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6681 * with the value set to 0. This option will be the first in the list.
6683 * @uses SORT_NUMERIC
6684 * @param int $sitebytes Set maximum size
6685 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6686 * @param int $modulebytes Current module ->maxbytes (in bytes)
6687 * @param int|array $custombytes custom upload size/s which will be added to list,
6688 * Only value/s smaller then maxsize will be added to list.
6689 * @return array
6691 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6692 global $CFG;
6694 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6695 return array();
6698 if ($sitebytes == 0) {
6699 // Will get the minimum of upload_max_filesize or post_max_size.
6700 $sitebytes = get_max_upload_file_size();
6703 $filesize = array();
6704 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6705 5242880, 10485760, 20971520, 52428800, 104857600,
6706 262144000, 524288000, 786432000, 1073741824,
6707 2147483648, 4294967296, 8589934592);
6709 // If custombytes is given and is valid then add it to the list.
6710 if (is_number($custombytes) and $custombytes > 0) {
6711 $custombytes = (int)$custombytes;
6712 if (!in_array($custombytes, $sizelist)) {
6713 $sizelist[] = $custombytes;
6715 } else if (is_array($custombytes)) {
6716 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6719 // Allow maxbytes to be selected if it falls outside the above boundaries.
6720 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6721 // Note: get_real_size() is used in order to prevent problems with invalid values.
6722 $sizelist[] = get_real_size($CFG->maxbytes);
6725 foreach ($sizelist as $sizebytes) {
6726 if ($sizebytes < $maxsize && $sizebytes > 0) {
6727 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6731 $limitlevel = '';
6732 $displaysize = '';
6733 if ($modulebytes &&
6734 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6735 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6736 $limitlevel = get_string('activity', 'core');
6737 $displaysize = display_size($modulebytes);
6738 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6740 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6741 $limitlevel = get_string('course', 'core');
6742 $displaysize = display_size($coursebytes);
6743 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6745 } else if ($sitebytes) {
6746 $limitlevel = get_string('site', 'core');
6747 $displaysize = display_size($sitebytes);
6748 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6751 krsort($filesize, SORT_NUMERIC);
6752 if ($limitlevel) {
6753 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6754 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6757 return $filesize;
6761 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6763 * If excludefiles is defined, then that file/directory is ignored
6764 * If getdirs is true, then (sub)directories are included in the output
6765 * If getfiles is true, then files are included in the output
6766 * (at least one of these must be true!)
6768 * @todo Finish documenting this function. Add examples of $excludefile usage.
6770 * @param string $rootdir A given root directory to start from
6771 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6772 * @param bool $descend If true then subdirectories are recursed as well
6773 * @param bool $getdirs If true then (sub)directories are included in the output
6774 * @param bool $getfiles If true then files are included in the output
6775 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6777 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6779 $dirs = array();
6781 if (!$getdirs and !$getfiles) { // Nothing to show.
6782 return $dirs;
6785 if (!is_dir($rootdir)) { // Must be a directory.
6786 return $dirs;
6789 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6790 return $dirs;
6793 if (!is_array($excludefiles)) {
6794 $excludefiles = array($excludefiles);
6797 while (false !== ($file = readdir($dir))) {
6798 $firstchar = substr($file, 0, 1);
6799 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6800 continue;
6802 $fullfile = $rootdir .'/'. $file;
6803 if (filetype($fullfile) == 'dir') {
6804 if ($getdirs) {
6805 $dirs[] = $file;
6807 if ($descend) {
6808 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6809 foreach ($subdirs as $subdir) {
6810 $dirs[] = $file .'/'. $subdir;
6813 } else if ($getfiles) {
6814 $dirs[] = $file;
6817 closedir($dir);
6819 asort($dirs);
6821 return $dirs;
6826 * Adds up all the files in a directory and works out the size.
6828 * @param string $rootdir The directory to start from
6829 * @param string $excludefile A file to exclude when summing directory size
6830 * @return int The summed size of all files and subfiles within the root directory
6832 function get_directory_size($rootdir, $excludefile='') {
6833 global $CFG;
6835 // Do it this way if we can, it's much faster.
6836 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6837 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6838 $output = null;
6839 $return = null;
6840 exec($command, $output, $return);
6841 if (is_array($output)) {
6842 // We told it to return k.
6843 return get_real_size(intval($output[0]).'k');
6847 if (!is_dir($rootdir)) {
6848 // Must be a directory.
6849 return 0;
6852 if (!$dir = @opendir($rootdir)) {
6853 // Can't open it for some reason.
6854 return 0;
6857 $size = 0;
6859 while (false !== ($file = readdir($dir))) {
6860 $firstchar = substr($file, 0, 1);
6861 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6862 continue;
6864 $fullfile = $rootdir .'/'. $file;
6865 if (filetype($fullfile) == 'dir') {
6866 $size += get_directory_size($fullfile, $excludefile);
6867 } else {
6868 $size += filesize($fullfile);
6871 closedir($dir);
6873 return $size;
6877 * Converts bytes into display form
6879 * @static string $gb Localized string for size in gigabytes
6880 * @static string $mb Localized string for size in megabytes
6881 * @static string $kb Localized string for size in kilobytes
6882 * @static string $b Localized string for size in bytes
6883 * @param int $size The size to convert to human readable form
6884 * @return string
6886 function display_size($size) {
6888 static $gb, $mb, $kb, $b;
6890 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6891 return get_string('unlimited');
6894 if (empty($gb)) {
6895 $gb = get_string('sizegb');
6896 $mb = get_string('sizemb');
6897 $kb = get_string('sizekb');
6898 $b = get_string('sizeb');
6901 if ($size >= 1073741824) {
6902 $size = round($size / 1073741824 * 10) / 10 . $gb;
6903 } else if ($size >= 1048576) {
6904 $size = round($size / 1048576 * 10) / 10 . $mb;
6905 } else if ($size >= 1024) {
6906 $size = round($size / 1024 * 10) / 10 . $kb;
6907 } else {
6908 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6910 return $size;
6914 * Cleans a given filename by removing suspicious or troublesome characters
6916 * @see clean_param()
6917 * @param string $string file name
6918 * @return string cleaned file name
6920 function clean_filename($string) {
6921 return clean_param($string, PARAM_FILE);
6924 // STRING TRANSLATION.
6927 * Returns the code for the current language
6929 * @category string
6930 * @return string
6932 function current_language() {
6933 global $CFG, $USER, $SESSION, $COURSE;
6935 if (!empty($SESSION->forcelang)) {
6936 // Allows overriding course-forced language (useful for admins to check
6937 // issues in courses whose language they don't understand).
6938 // Also used by some code to temporarily get language-related information in a
6939 // specific language (see force_current_language()).
6940 $return = $SESSION->forcelang;
6942 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6943 // Course language can override all other settings for this page.
6944 $return = $COURSE->lang;
6946 } else if (!empty($SESSION->lang)) {
6947 // Session language can override other settings.
6948 $return = $SESSION->lang;
6950 } else if (!empty($USER->lang)) {
6951 $return = $USER->lang;
6953 } else if (isset($CFG->lang)) {
6954 $return = $CFG->lang;
6956 } else {
6957 $return = 'en';
6960 // Just in case this slipped in from somewhere by accident.
6961 $return = str_replace('_utf8', '', $return);
6963 return $return;
6967 * Returns parent language of current active language if defined
6969 * @category string
6970 * @param string $lang null means current language
6971 * @return string
6973 function get_parent_language($lang=null) {
6975 // Let's hack around the current language.
6976 if (!empty($lang)) {
6977 $oldforcelang = force_current_language($lang);
6980 $parentlang = get_string('parentlanguage', 'langconfig');
6981 if ($parentlang === 'en') {
6982 $parentlang = '';
6985 // Let's hack around the current language.
6986 if (!empty($lang)) {
6987 force_current_language($oldforcelang);
6990 return $parentlang;
6994 * Force the current language to get strings and dates localised in the given language.
6996 * After calling this function, all strings will be provided in the given language
6997 * until this function is called again, or equivalent code is run.
6999 * @param string $language
7000 * @return string previous $SESSION->forcelang value
7002 function force_current_language($language) {
7003 global $SESSION;
7004 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
7005 if ($language !== $sessionforcelang) {
7006 // Seting forcelang to null or an empty string disables it's effect.
7007 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
7008 $SESSION->forcelang = $language;
7009 moodle_setlocale();
7012 return $sessionforcelang;
7016 * Returns current string_manager instance.
7018 * The param $forcereload is needed for CLI installer only where the string_manager instance
7019 * must be replaced during the install.php script life time.
7021 * @category string
7022 * @param bool $forcereload shall the singleton be released and new instance created instead?
7023 * @return core_string_manager
7025 function get_string_manager($forcereload=false) {
7026 global $CFG;
7028 static $singleton = null;
7030 if ($forcereload) {
7031 $singleton = null;
7033 if ($singleton === null) {
7034 if (empty($CFG->early_install_lang)) {
7036 if (empty($CFG->langlist)) {
7037 $translist = array();
7038 } else {
7039 $translist = explode(',', $CFG->langlist);
7040 $translist = array_map('trim', $translist);
7043 if (!empty($CFG->config_php_settings['customstringmanager'])) {
7044 $classname = $CFG->config_php_settings['customstringmanager'];
7046 if (class_exists($classname)) {
7047 $implements = class_implements($classname);
7049 if (isset($implements['core_string_manager'])) {
7050 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist);
7051 return $singleton;
7053 } else {
7054 debugging('Unable to instantiate custom string manager: class '.$classname.
7055 ' does not implement the core_string_manager interface.');
7058 } else {
7059 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7063 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
7065 } else {
7066 $singleton = new core_string_manager_install();
7070 return $singleton;
7074 * Returns a localized string.
7076 * Returns the translated string specified by $identifier as
7077 * for $module. Uses the same format files as STphp.
7078 * $a is an object, string or number that can be used
7079 * within translation strings
7081 * eg 'hello {$a->firstname} {$a->lastname}'
7082 * or 'hello {$a}'
7084 * If you would like to directly echo the localized string use
7085 * the function {@link print_string()}
7087 * Example usage of this function involves finding the string you would
7088 * like a local equivalent of and using its identifier and module information
7089 * to retrieve it.<br/>
7090 * If you open moodle/lang/en/moodle.php and look near line 278
7091 * you will find a string to prompt a user for their word for 'course'
7092 * <code>
7093 * $string['course'] = 'Course';
7094 * </code>
7095 * So if you want to display the string 'Course'
7096 * in any language that supports it on your site
7097 * you just need to use the identifier 'course'
7098 * <code>
7099 * $mystring = '<strong>'. get_string('course') .'</strong>';
7100 * or
7101 * </code>
7102 * If the string you want is in another file you'd take a slightly
7103 * different approach. Looking in moodle/lang/en/calendar.php you find
7104 * around line 75:
7105 * <code>
7106 * $string['typecourse'] = 'Course event';
7107 * </code>
7108 * If you want to display the string "Course event" in any language
7109 * supported you would use the identifier 'typecourse' and the module 'calendar'
7110 * (because it is in the file calendar.php):
7111 * <code>
7112 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7113 * </code>
7115 * As a last resort, should the identifier fail to map to a string
7116 * the returned string will be [[ $identifier ]]
7118 * In Moodle 2.3 there is a new argument to this function $lazyload.
7119 * Setting $lazyload to true causes get_string to return a lang_string object
7120 * rather than the string itself. The fetching of the string is then put off until
7121 * the string object is first used. The object can be used by calling it's out
7122 * method or by casting the object to a string, either directly e.g.
7123 * (string)$stringobject
7124 * or indirectly by using the string within another string or echoing it out e.g.
7125 * echo $stringobject
7126 * return "<p>{$stringobject}</p>";
7127 * It is worth noting that using $lazyload and attempting to use the string as an
7128 * array key will cause a fatal error as objects cannot be used as array keys.
7129 * But you should never do that anyway!
7130 * For more information {@link lang_string}
7132 * @category string
7133 * @param string $identifier The key identifier for the localized string
7134 * @param string $component The module where the key identifier is stored,
7135 * usually expressed as the filename in the language pack without the
7136 * .php on the end but can also be written as mod/forum or grade/export/xls.
7137 * If none is specified then moodle.php is used.
7138 * @param string|object|array $a An object, string or number that can be used
7139 * within translation strings
7140 * @param bool $lazyload If set to true a string object is returned instead of
7141 * the string itself. The string then isn't calculated until it is first used.
7142 * @return string The localized string.
7143 * @throws coding_exception
7145 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7146 global $CFG;
7148 // If the lazy load argument has been supplied return a lang_string object
7149 // instead.
7150 // We need to make sure it is true (and a bool) as you will see below there
7151 // used to be a forth argument at one point.
7152 if ($lazyload === true) {
7153 return new lang_string($identifier, $component, $a);
7156 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7157 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7160 // There is now a forth argument again, this time it is a boolean however so
7161 // we can still check for the old extralocations parameter.
7162 if (!is_bool($lazyload) && !empty($lazyload)) {
7163 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7166 if (strpos($component, '/') !== false) {
7167 debugging('The module name you passed to get_string is the deprecated format ' .
7168 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7169 $componentpath = explode('/', $component);
7171 switch ($componentpath[0]) {
7172 case 'mod':
7173 $component = $componentpath[1];
7174 break;
7175 case 'blocks':
7176 case 'block':
7177 $component = 'block_'.$componentpath[1];
7178 break;
7179 case 'enrol':
7180 $component = 'enrol_'.$componentpath[1];
7181 break;
7182 case 'format':
7183 $component = 'format_'.$componentpath[1];
7184 break;
7185 case 'grade':
7186 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7187 break;
7191 $result = get_string_manager()->get_string($identifier, $component, $a);
7193 // Debugging feature lets you display string identifier and component.
7194 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7195 $result .= ' {' . $identifier . '/' . $component . '}';
7197 return $result;
7201 * Converts an array of strings to their localized value.
7203 * @param array $array An array of strings
7204 * @param string $component The language module that these strings can be found in.
7205 * @return stdClass translated strings.
7207 function get_strings($array, $component = '') {
7208 $string = new stdClass;
7209 foreach ($array as $item) {
7210 $string->$item = get_string($item, $component);
7212 return $string;
7216 * Prints out a translated string.
7218 * Prints out a translated string using the return value from the {@link get_string()} function.
7220 * Example usage of this function when the string is in the moodle.php file:<br/>
7221 * <code>
7222 * echo '<strong>';
7223 * print_string('course');
7224 * echo '</strong>';
7225 * </code>
7227 * Example usage of this function when the string is not in the moodle.php file:<br/>
7228 * <code>
7229 * echo '<h1>';
7230 * print_string('typecourse', 'calendar');
7231 * echo '</h1>';
7232 * </code>
7234 * @category string
7235 * @param string $identifier The key identifier for the localized string
7236 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7237 * @param string|object|array $a An object, string or number that can be used within translation strings
7239 function print_string($identifier, $component = '', $a = null) {
7240 echo get_string($identifier, $component, $a);
7244 * Returns a list of charset codes
7246 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7247 * (checking that such charset is supported by the texlib library!)
7249 * @return array And associative array with contents in the form of charset => charset
7251 function get_list_of_charsets() {
7253 $charsets = array(
7254 'EUC-JP' => 'EUC-JP',
7255 'ISO-2022-JP'=> 'ISO-2022-JP',
7256 'ISO-8859-1' => 'ISO-8859-1',
7257 'SHIFT-JIS' => 'SHIFT-JIS',
7258 'GB2312' => 'GB2312',
7259 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7260 'UTF-8' => 'UTF-8');
7262 asort($charsets);
7264 return $charsets;
7268 * Returns a list of valid and compatible themes
7270 * @return array
7272 function get_list_of_themes() {
7273 global $CFG;
7275 $themes = array();
7277 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7278 $themelist = explode(',', $CFG->themelist);
7279 } else {
7280 $themelist = array_keys(core_component::get_plugin_list("theme"));
7283 foreach ($themelist as $key => $themename) {
7284 $theme = theme_config::load($themename);
7285 $themes[$themename] = $theme;
7288 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7290 return $themes;
7294 * Factory function for emoticon_manager
7296 * @return emoticon_manager singleton
7298 function get_emoticon_manager() {
7299 static $singleton = null;
7301 if (is_null($singleton)) {
7302 $singleton = new emoticon_manager();
7305 return $singleton;
7309 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7311 * Whenever this manager mentiones 'emoticon object', the following data
7312 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7313 * altidentifier and altcomponent
7315 * @see admin_setting_emoticons
7317 * @copyright 2010 David Mudrak
7318 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7320 class emoticon_manager {
7323 * Returns the currently enabled emoticons
7325 * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
7326 * @return array of emoticon objects
7328 public function get_emoticons($selectable = false) {
7329 global $CFG;
7330 $notselectable = ['martin', 'egg'];
7332 if (empty($CFG->emoticons)) {
7333 return array();
7336 $emoticons = $this->decode_stored_config($CFG->emoticons);
7338 if (!is_array($emoticons)) {
7339 // Something is wrong with the format of stored setting.
7340 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7341 return array();
7343 if ($selectable) {
7344 foreach ($emoticons as $index => $emote) {
7345 if (in_array($emote->altidentifier, $notselectable)) {
7346 // Skip this one.
7347 unset($emoticons[$index]);
7352 return $emoticons;
7356 * Converts emoticon object into renderable pix_emoticon object
7358 * @param stdClass $emoticon emoticon object
7359 * @param array $attributes explicit HTML attributes to set
7360 * @return pix_emoticon
7362 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7363 $stringmanager = get_string_manager();
7364 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7365 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7366 } else {
7367 $alt = s($emoticon->text);
7369 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7373 * Encodes the array of emoticon objects into a string storable in config table
7375 * @see self::decode_stored_config()
7376 * @param array $emoticons array of emtocion objects
7377 * @return string
7379 public function encode_stored_config(array $emoticons) {
7380 return json_encode($emoticons);
7384 * Decodes the string into an array of emoticon objects
7386 * @see self::encode_stored_config()
7387 * @param string $encoded
7388 * @return string|null
7390 public function decode_stored_config($encoded) {
7391 $decoded = json_decode($encoded);
7392 if (!is_array($decoded)) {
7393 return null;
7395 return $decoded;
7399 * Returns default set of emoticons supported by Moodle
7401 * @return array of sdtClasses
7403 public function default_emoticons() {
7404 return array(
7405 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7406 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7407 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7408 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7409 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7410 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7411 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7412 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7413 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7414 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7415 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7416 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7417 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7418 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7419 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7420 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7421 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7422 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7423 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7424 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7425 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7426 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7427 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7428 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7429 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7430 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7431 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7432 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7433 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7434 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7439 * Helper method preparing the stdClass with the emoticon properties
7441 * @param string|array $text or array of strings
7442 * @param string $imagename to be used by {@link pix_emoticon}
7443 * @param string $altidentifier alternative string identifier, null for no alt
7444 * @param string $altcomponent where the alternative string is defined
7445 * @param string $imagecomponent to be used by {@link pix_emoticon}
7446 * @return stdClass
7448 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7449 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7450 return (object)array(
7451 'text' => $text,
7452 'imagename' => $imagename,
7453 'imagecomponent' => $imagecomponent,
7454 'altidentifier' => $altidentifier,
7455 'altcomponent' => $altcomponent,
7460 // ENCRYPTION.
7463 * rc4encrypt
7465 * @param string $data Data to encrypt.
7466 * @return string The now encrypted data.
7468 function rc4encrypt($data) {
7469 return endecrypt(get_site_identifier(), $data, '');
7473 * rc4decrypt
7475 * @param string $data Data to decrypt.
7476 * @return string The now decrypted data.
7478 function rc4decrypt($data) {
7479 return endecrypt(get_site_identifier(), $data, 'de');
7483 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7485 * @todo Finish documenting this function
7487 * @param string $pwd The password to use when encrypting or decrypting
7488 * @param string $data The data to be decrypted/encrypted
7489 * @param string $case Either 'de' for decrypt or '' for encrypt
7490 * @return string
7492 function endecrypt ($pwd, $data, $case) {
7494 if ($case == 'de') {
7495 $data = urldecode($data);
7498 $key[] = '';
7499 $box[] = '';
7500 $pwdlength = strlen($pwd);
7502 for ($i = 0; $i <= 255; $i++) {
7503 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7504 $box[$i] = $i;
7507 $x = 0;
7509 for ($i = 0; $i <= 255; $i++) {
7510 $x = ($x + $box[$i] + $key[$i]) % 256;
7511 $tempswap = $box[$i];
7512 $box[$i] = $box[$x];
7513 $box[$x] = $tempswap;
7516 $cipher = '';
7518 $a = 0;
7519 $j = 0;
7521 for ($i = 0; $i < strlen($data); $i++) {
7522 $a = ($a + 1) % 256;
7523 $j = ($j + $box[$a]) % 256;
7524 $temp = $box[$a];
7525 $box[$a] = $box[$j];
7526 $box[$j] = $temp;
7527 $k = $box[(($box[$a] + $box[$j]) % 256)];
7528 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7529 $cipher .= chr($cipherby);
7532 if ($case == 'de') {
7533 $cipher = urldecode(urlencode($cipher));
7534 } else {
7535 $cipher = urlencode($cipher);
7538 return $cipher;
7541 // ENVIRONMENT CHECKING.
7544 * This method validates a plug name. It is much faster than calling clean_param.
7546 * @param string $name a string that might be a plugin name.
7547 * @return bool if this string is a valid plugin name.
7549 function is_valid_plugin_name($name) {
7550 // This does not work for 'mod', bad luck, use any other type.
7551 return core_component::is_valid_plugin_name('tool', $name);
7555 * Get a list of all the plugins of a given type that define a certain API function
7556 * in a certain file. The plugin component names and function names are returned.
7558 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7559 * @param string $function the part of the name of the function after the
7560 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7561 * names like report_courselist_hook.
7562 * @param string $file the name of file within the plugin that defines the
7563 * function. Defaults to lib.php.
7564 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7565 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7567 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7568 global $CFG;
7570 // We don't include here as all plugin types files would be included.
7571 $plugins = get_plugins_with_function($function, $file, false);
7573 if (empty($plugins[$plugintype])) {
7574 return array();
7577 $allplugins = core_component::get_plugin_list($plugintype);
7579 // Reformat the array and include the files.
7580 $pluginfunctions = array();
7581 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7583 // Check that it has not been removed and the file is still available.
7584 if (!empty($allplugins[$pluginname])) {
7586 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7587 if (file_exists($filepath)) {
7588 include_once($filepath);
7589 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7594 return $pluginfunctions;
7598 * Get a list of all the plugins that define a certain API function in a certain file.
7600 * @param string $function the part of the name of the function after the
7601 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7602 * names like report_courselist_hook.
7603 * @param string $file the name of file within the plugin that defines the
7604 * function. Defaults to lib.php.
7605 * @param bool $include Whether to include the files that contain the functions or not.
7606 * @return array with [plugintype][plugin] = functionname
7608 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7609 global $CFG;
7611 if (during_initial_install() || isset($CFG->upgraderunning)) {
7612 // API functions _must not_ be called during an installation or upgrade.
7613 return [];
7616 $cache = \cache::make('core', 'plugin_functions');
7618 // Including both although I doubt that we will find two functions definitions with the same name.
7619 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7620 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7621 $pluginfunctions = $cache->get($key);
7623 // Use the plugin manager to check that plugins are currently installed.
7624 $pluginmanager = \core_plugin_manager::instance();
7626 if ($pluginfunctions !== false) {
7628 // Checking that the files are still available.
7629 foreach ($pluginfunctions as $plugintype => $plugins) {
7631 $allplugins = \core_component::get_plugin_list($plugintype);
7632 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7633 foreach ($plugins as $plugin => $function) {
7634 if (!isset($installedplugins[$plugin])) {
7635 // Plugin code is still present on disk but it is not installed.
7636 unset($pluginfunctions[$plugintype][$plugin]);
7637 continue;
7640 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7641 if (empty($allplugins[$plugin])) {
7642 unset($pluginfunctions[$plugintype][$plugin]);
7643 continue;
7646 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7647 if ($include && $fileexists) {
7648 // Include the files if it was requested.
7649 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7650 } else if (!$fileexists) {
7651 // If the file is not available any more it should not be returned.
7652 unset($pluginfunctions[$plugintype][$plugin]);
7656 return $pluginfunctions;
7659 $pluginfunctions = array();
7661 // To fill the cached. Also, everything should continue working with cache disabled.
7662 $plugintypes = \core_component::get_plugin_types();
7663 foreach ($plugintypes as $plugintype => $unused) {
7665 // We need to include files here.
7666 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7667 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7668 foreach ($pluginswithfile as $plugin => $notused) {
7670 if (!isset($installedplugins[$plugin])) {
7671 continue;
7674 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7676 $pluginfunction = false;
7677 if (function_exists($fullfunction)) {
7678 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7679 $pluginfunction = $fullfunction;
7681 } else if ($plugintype === 'mod') {
7682 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7683 $shortfunction = $plugin . '_' . $function;
7684 if (function_exists($shortfunction)) {
7685 $pluginfunction = $shortfunction;
7689 if ($pluginfunction) {
7690 if (empty($pluginfunctions[$plugintype])) {
7691 $pluginfunctions[$plugintype] = array();
7693 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7698 $cache->set($key, $pluginfunctions);
7700 return $pluginfunctions;
7705 * Lists plugin-like directories within specified directory
7707 * This function was originally used for standard Moodle plugins, please use
7708 * new core_component::get_plugin_list() now.
7710 * This function is used for general directory listing and backwards compatility.
7712 * @param string $directory relative directory from root
7713 * @param string $exclude dir name to exclude from the list (defaults to none)
7714 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7715 * @return array Sorted array of directory names found under the requested parameters
7717 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7718 global $CFG;
7720 $plugins = array();
7722 if (empty($basedir)) {
7723 $basedir = $CFG->dirroot .'/'. $directory;
7725 } else {
7726 $basedir = $basedir .'/'. $directory;
7729 if ($CFG->debugdeveloper and empty($exclude)) {
7730 // Make sure devs do not use this to list normal plugins,
7731 // this is intended for general directories that are not plugins!
7733 $subtypes = core_component::get_plugin_types();
7734 if (in_array($basedir, $subtypes)) {
7735 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7737 unset($subtypes);
7740 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7741 if (!$dirhandle = opendir($basedir)) {
7742 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7743 return array();
7745 while (false !== ($dir = readdir($dirhandle))) {
7746 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7747 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7748 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7749 continue;
7751 if (filetype($basedir .'/'. $dir) != 'dir') {
7752 continue;
7754 $plugins[] = $dir;
7756 closedir($dirhandle);
7758 if ($plugins) {
7759 asort($plugins);
7761 return $plugins;
7765 * Invoke plugin's callback functions
7767 * @param string $type plugin type e.g. 'mod'
7768 * @param string $name plugin name
7769 * @param string $feature feature name
7770 * @param string $action feature's action
7771 * @param array $params parameters of callback function, should be an array
7772 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7773 * @return mixed
7775 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7777 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7778 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7782 * Invoke component's callback functions
7784 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7785 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7786 * @param array $params parameters of callback function
7787 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7788 * @return mixed
7790 function component_callback($component, $function, array $params = array(), $default = null) {
7792 $functionname = component_callback_exists($component, $function);
7794 if ($functionname) {
7795 // Function exists, so just return function result.
7796 $ret = call_user_func_array($functionname, $params);
7797 if (is_null($ret)) {
7798 return $default;
7799 } else {
7800 return $ret;
7803 return $default;
7807 * Determine if a component callback exists and return the function name to call. Note that this
7808 * function will include the required library files so that the functioname returned can be
7809 * called directly.
7811 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7812 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7813 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7814 * @throws coding_exception if invalid component specfied
7816 function component_callback_exists($component, $function) {
7817 global $CFG; // This is needed for the inclusions.
7819 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7820 if (empty($cleancomponent)) {
7821 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7823 $component = $cleancomponent;
7825 list($type, $name) = core_component::normalize_component($component);
7826 $component = $type . '_' . $name;
7828 $oldfunction = $name.'_'.$function;
7829 $function = $component.'_'.$function;
7831 $dir = core_component::get_component_directory($component);
7832 if (empty($dir)) {
7833 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7836 // Load library and look for function.
7837 if (file_exists($dir.'/lib.php')) {
7838 require_once($dir.'/lib.php');
7841 if (!function_exists($function) and function_exists($oldfunction)) {
7842 if ($type !== 'mod' and $type !== 'core') {
7843 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7845 $function = $oldfunction;
7848 if (function_exists($function)) {
7849 return $function;
7851 return false;
7855 * Call the specified callback method on the provided class.
7857 * If the callback returns null, then the default value is returned instead.
7858 * If the class does not exist, then the default value is returned.
7860 * @param string $classname The name of the class to call upon.
7861 * @param string $methodname The name of the staticically defined method on the class.
7862 * @param array $params The arguments to pass into the method.
7863 * @param mixed $default The default value.
7864 * @return mixed The return value.
7866 function component_class_callback($classname, $methodname, array $params, $default = null) {
7867 if (!class_exists($classname)) {
7868 return $default;
7871 if (!method_exists($classname, $methodname)) {
7872 return $default;
7875 $fullfunction = $classname . '::' . $methodname;
7876 $result = call_user_func_array($fullfunction, $params);
7878 if (null === $result) {
7879 return $default;
7880 } else {
7881 return $result;
7886 * Checks whether a plugin supports a specified feature.
7888 * @param string $type Plugin type e.g. 'mod'
7889 * @param string $name Plugin name e.g. 'forum'
7890 * @param string $feature Feature code (FEATURE_xx constant)
7891 * @param mixed $default default value if feature support unknown
7892 * @return mixed Feature result (false if not supported, null if feature is unknown,
7893 * otherwise usually true but may have other feature-specific value such as array)
7894 * @throws coding_exception
7896 function plugin_supports($type, $name, $feature, $default = null) {
7897 global $CFG;
7899 if ($type === 'mod' and $name === 'NEWMODULE') {
7900 // Somebody forgot to rename the module template.
7901 return false;
7904 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7905 if (empty($component)) {
7906 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7909 $function = null;
7911 if ($type === 'mod') {
7912 // We need this special case because we support subplugins in modules,
7913 // otherwise it would end up in infinite loop.
7914 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7915 include_once("$CFG->dirroot/mod/$name/lib.php");
7916 $function = $component.'_supports';
7917 if (!function_exists($function)) {
7918 // Legacy non-frankenstyle function name.
7919 $function = $name.'_supports';
7923 } else {
7924 if (!$path = core_component::get_plugin_directory($type, $name)) {
7925 // Non existent plugin type.
7926 return false;
7928 if (file_exists("$path/lib.php")) {
7929 include_once("$path/lib.php");
7930 $function = $component.'_supports';
7934 if ($function and function_exists($function)) {
7935 $supports = $function($feature);
7936 if (is_null($supports)) {
7937 // Plugin does not know - use default.
7938 return $default;
7939 } else {
7940 return $supports;
7944 // Plugin does not care, so use default.
7945 return $default;
7949 * Returns true if the current version of PHP is greater that the specified one.
7951 * @todo Check PHP version being required here is it too low?
7953 * @param string $version The version of php being tested.
7954 * @return bool
7956 function check_php_version($version='5.2.4') {
7957 return (version_compare(phpversion(), $version) >= 0);
7961 * Determine if moodle installation requires update.
7963 * Checks version numbers of main code and all plugins to see
7964 * if there are any mismatches.
7966 * @return bool
7968 function moodle_needs_upgrading() {
7969 global $CFG;
7971 if (empty($CFG->version)) {
7972 return true;
7975 // There is no need to purge plugininfo caches here because
7976 // these caches are not used during upgrade and they are purged after
7977 // every upgrade.
7979 if (empty($CFG->allversionshash)) {
7980 return true;
7983 $hash = core_component::get_all_versions_hash();
7985 return ($hash !== $CFG->allversionshash);
7989 * Returns the major version of this site
7991 * Moodle version numbers consist of three numbers separated by a dot, for
7992 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7993 * called major version. This function extracts the major version from either
7994 * $CFG->release (default) or eventually from the $release variable defined in
7995 * the main version.php.
7997 * @param bool $fromdisk should the version if source code files be used
7998 * @return string|false the major version like '2.3', false if could not be determined
8000 function moodle_major_version($fromdisk = false) {
8001 global $CFG;
8003 if ($fromdisk) {
8004 $release = null;
8005 require($CFG->dirroot.'/version.php');
8006 if (empty($release)) {
8007 return false;
8010 } else {
8011 if (empty($CFG->release)) {
8012 return false;
8014 $release = $CFG->release;
8017 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8018 return $matches[0];
8019 } else {
8020 return false;
8024 // MISCELLANEOUS.
8027 * Sets the system locale
8029 * @category string
8030 * @param string $locale Can be used to force a locale
8032 function moodle_setlocale($locale='') {
8033 global $CFG;
8035 static $currentlocale = ''; // Last locale caching.
8037 $oldlocale = $currentlocale;
8039 // Fetch the correct locale based on ostype.
8040 if ($CFG->ostype == 'WINDOWS') {
8041 $stringtofetch = 'localewin';
8042 } else {
8043 $stringtofetch = 'locale';
8046 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8047 if (!empty($locale)) {
8048 $currentlocale = $locale;
8049 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
8050 $currentlocale = $CFG->locale;
8051 } else {
8052 $currentlocale = get_string($stringtofetch, 'langconfig');
8055 // Do nothing if locale already set up.
8056 if ($oldlocale == $currentlocale) {
8057 return;
8060 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8061 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8062 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8064 // Get current values.
8065 $monetary= setlocale (LC_MONETARY, 0);
8066 $numeric = setlocale (LC_NUMERIC, 0);
8067 $ctype = setlocale (LC_CTYPE, 0);
8068 if ($CFG->ostype != 'WINDOWS') {
8069 $messages= setlocale (LC_MESSAGES, 0);
8071 // Set locale to all.
8072 $result = setlocale (LC_ALL, $currentlocale);
8073 // If setting of locale fails try the other utf8 or utf-8 variant,
8074 // some operating systems support both (Debian), others just one (OSX).
8075 if ($result === false) {
8076 if (stripos($currentlocale, '.UTF-8') !== false) {
8077 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8078 setlocale (LC_ALL, $newlocale);
8079 } else if (stripos($currentlocale, '.UTF8') !== false) {
8080 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8081 setlocale (LC_ALL, $newlocale);
8084 // Set old values.
8085 setlocale (LC_MONETARY, $monetary);
8086 setlocale (LC_NUMERIC, $numeric);
8087 if ($CFG->ostype != 'WINDOWS') {
8088 setlocale (LC_MESSAGES, $messages);
8090 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8091 // To workaround a well-known PHP problem with Turkish letter Ii.
8092 setlocale (LC_CTYPE, $ctype);
8097 * Count words in a string.
8099 * Words are defined as things between whitespace.
8101 * @category string
8102 * @param string $string The text to be searched for words.
8103 * @return int The count of words in the specified string
8105 function count_words($string) {
8106 $string = strip_tags($string);
8107 // Decode HTML entities.
8108 $string = html_entity_decode($string);
8109 // Replace underscores (which are classed as word characters) with spaces.
8110 $string = preg_replace('/_/u', ' ', $string);
8111 // Remove any characters that shouldn't be treated as word boundaries.
8112 $string = preg_replace('/[\'"’-]/u', '', $string);
8113 // Remove dots and commas from within numbers only.
8114 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
8116 return count(preg_split('/\w\b/u', $string)) - 1;
8120 * Count letters in a string.
8122 * Letters are defined as chars not in tags and different from whitespace.
8124 * @category string
8125 * @param string $string The text to be searched for letters.
8126 * @return int The count of letters in the specified text.
8128 function count_letters($string) {
8129 $string = strip_tags($string); // Tags are out now.
8130 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8132 return core_text::strlen($string);
8136 * Generate and return a random string of the specified length.
8138 * @param int $length The length of the string to be created.
8139 * @return string
8141 function random_string($length=15) {
8142 $randombytes = random_bytes_emulate($length);
8143 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8144 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8145 $pool .= '0123456789';
8146 $poollen = strlen($pool);
8147 $string = '';
8148 for ($i = 0; $i < $length; $i++) {
8149 $rand = ord($randombytes[$i]);
8150 $string .= substr($pool, ($rand%($poollen)), 1);
8152 return $string;
8156 * Generate a complex random string (useful for md5 salts)
8158 * This function is based on the above {@link random_string()} however it uses a
8159 * larger pool of characters and generates a string between 24 and 32 characters
8161 * @param int $length Optional if set generates a string to exactly this length
8162 * @return string
8164 function complex_random_string($length=null) {
8165 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8166 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8167 $poollen = strlen($pool);
8168 if ($length===null) {
8169 $length = floor(rand(24, 32));
8171 $randombytes = random_bytes_emulate($length);
8172 $string = '';
8173 for ($i = 0; $i < $length; $i++) {
8174 $rand = ord($randombytes[$i]);
8175 $string .= $pool[($rand%$poollen)];
8177 return $string;
8181 * Try to generates cryptographically secure pseudo-random bytes.
8183 * Note this is achieved by fallbacking between:
8184 * - PHP 7 random_bytes().
8185 * - OpenSSL openssl_random_pseudo_bytes().
8186 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8188 * @param int $length requested length in bytes
8189 * @return string binary data
8191 function random_bytes_emulate($length) {
8192 global $CFG;
8193 if ($length <= 0) {
8194 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8195 return '';
8197 if (function_exists('random_bytes')) {
8198 // Use PHP 7 goodness.
8199 $hash = @random_bytes($length);
8200 if ($hash !== false) {
8201 return $hash;
8204 if (function_exists('openssl_random_pseudo_bytes')) {
8205 // If you have the openssl extension enabled.
8206 $hash = openssl_random_pseudo_bytes($length);
8207 if ($hash !== false) {
8208 return $hash;
8212 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8213 $staticdata = serialize($CFG) . serialize($_SERVER);
8214 $hash = '';
8215 do {
8216 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8217 } while (strlen($hash) < $length);
8219 return substr($hash, 0, $length);
8223 * Given some text (which may contain HTML) and an ideal length,
8224 * this function truncates the text neatly on a word boundary if possible
8226 * @category string
8227 * @param string $text text to be shortened
8228 * @param int $ideal ideal string length
8229 * @param boolean $exact if false, $text will not be cut mid-word
8230 * @param string $ending The string to append if the passed string is truncated
8231 * @return string $truncate shortened string
8233 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8234 // If the plain text is shorter than the maximum length, return the whole text.
8235 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8236 return $text;
8239 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8240 // and only tag in its 'line'.
8241 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8243 $totallength = core_text::strlen($ending);
8244 $truncate = '';
8246 // This array stores information about open and close tags and their position
8247 // in the truncated string. Each item in the array is an object with fields
8248 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8249 // (byte position in truncated text).
8250 $tagdetails = array();
8252 foreach ($lines as $linematchings) {
8253 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8254 if (!empty($linematchings[1])) {
8255 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8256 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8257 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8258 // Record closing tag.
8259 $tagdetails[] = (object) array(
8260 'open' => false,
8261 'tag' => core_text::strtolower($tagmatchings[1]),
8262 'pos' => core_text::strlen($truncate),
8265 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8266 // Record opening tag.
8267 $tagdetails[] = (object) array(
8268 'open' => true,
8269 'tag' => core_text::strtolower($tagmatchings[1]),
8270 'pos' => core_text::strlen($truncate),
8272 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8273 $tagdetails[] = (object) array(
8274 'open' => true,
8275 'tag' => core_text::strtolower('if'),
8276 'pos' => core_text::strlen($truncate),
8278 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8279 $tagdetails[] = (object) array(
8280 'open' => false,
8281 'tag' => core_text::strtolower('if'),
8282 'pos' => core_text::strlen($truncate),
8286 // Add html-tag to $truncate'd text.
8287 $truncate .= $linematchings[1];
8290 // Calculate the length of the plain text part of the line; handle entities as one character.
8291 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8292 if ($totallength + $contentlength > $ideal) {
8293 // The number of characters which are left.
8294 $left = $ideal - $totallength;
8295 $entitieslength = 0;
8296 // Search for html entities.
8297 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)) {
8298 // Calculate the real length of all entities in the legal range.
8299 foreach ($entities[0] as $entity) {
8300 if ($entity[1]+1-$entitieslength <= $left) {
8301 $left--;
8302 $entitieslength += core_text::strlen($entity[0]);
8303 } else {
8304 // No more characters left.
8305 break;
8309 $breakpos = $left + $entitieslength;
8311 // If the words shouldn't be cut in the middle...
8312 if (!$exact) {
8313 // Search the last occurence of a space.
8314 for (; $breakpos > 0; $breakpos--) {
8315 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8316 if ($char === '.' or $char === ' ') {
8317 $breakpos += 1;
8318 break;
8319 } else if (strlen($char) > 2) {
8320 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8321 $breakpos += 1;
8322 break;
8327 if ($breakpos == 0) {
8328 // This deals with the test_shorten_text_no_spaces case.
8329 $breakpos = $left + $entitieslength;
8330 } else if ($breakpos > $left + $entitieslength) {
8331 // This deals with the previous for loop breaking on the first char.
8332 $breakpos = $left + $entitieslength;
8335 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8336 // Maximum length is reached, so get off the loop.
8337 break;
8338 } else {
8339 $truncate .= $linematchings[2];
8340 $totallength += $contentlength;
8343 // If the maximum length is reached, get off the loop.
8344 if ($totallength >= $ideal) {
8345 break;
8349 // Add the defined ending to the text.
8350 $truncate .= $ending;
8352 // Now calculate the list of open html tags based on the truncate position.
8353 $opentags = array();
8354 foreach ($tagdetails as $taginfo) {
8355 if ($taginfo->open) {
8356 // Add tag to the beginning of $opentags list.
8357 array_unshift($opentags, $taginfo->tag);
8358 } else {
8359 // Can have multiple exact same open tags, close the last one.
8360 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8361 if ($pos !== false) {
8362 unset($opentags[$pos]);
8367 // Close all unclosed html-tags.
8368 foreach ($opentags as $tag) {
8369 if ($tag === 'if') {
8370 $truncate .= '<!--<![endif]-->';
8371 } else {
8372 $truncate .= '</' . $tag . '>';
8376 return $truncate;
8380 * Shortens a given filename by removing characters positioned after the ideal string length.
8381 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8382 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8384 * @param string $filename file name
8385 * @param int $length ideal string length
8386 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8387 * @return string $shortened shortened file name
8389 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8390 $shortened = $filename;
8391 // Extract a part of the filename if it's char size exceeds the ideal string length.
8392 if (core_text::strlen($filename) > $length) {
8393 // Exclude extension if present in filename.
8394 $mimetypes = get_mimetypes_array();
8395 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8396 if ($extension && !empty($mimetypes[$extension])) {
8397 $basename = pathinfo($filename, PATHINFO_FILENAME);
8398 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8399 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8400 $shortened .= '.' . $extension;
8401 } else {
8402 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8403 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8406 return $shortened;
8410 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8412 * @param array $path The paths to reduce the length.
8413 * @param int $length Ideal string length
8414 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8415 * @return array $result Shortened paths in array.
8417 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8418 $result = null;
8420 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8421 $carry[] = shorten_filename($singlepath, $length, $includehash);
8422 return $carry;
8423 }, []);
8425 return $result;
8429 * Given dates in seconds, how many weeks is the date from startdate
8430 * The first week is 1, the second 2 etc ...
8432 * @param int $startdate Timestamp for the start date
8433 * @param int $thedate Timestamp for the end date
8434 * @return string
8436 function getweek ($startdate, $thedate) {
8437 if ($thedate < $startdate) {
8438 return 0;
8441 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8445 * Returns a randomly generated password of length $maxlen. inspired by
8447 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8448 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8450 * @param int $maxlen The maximum size of the password being generated.
8451 * @return string
8453 function generate_password($maxlen=10) {
8454 global $CFG;
8456 if (empty($CFG->passwordpolicy)) {
8457 $fillers = PASSWORD_DIGITS;
8458 $wordlist = file($CFG->wordlist);
8459 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8460 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8461 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8462 $password = $word1 . $filler1 . $word2;
8463 } else {
8464 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8465 $digits = $CFG->minpassworddigits;
8466 $lower = $CFG->minpasswordlower;
8467 $upper = $CFG->minpasswordupper;
8468 $nonalphanum = $CFG->minpasswordnonalphanum;
8469 $total = $lower + $upper + $digits + $nonalphanum;
8470 // Var minlength should be the greater one of the two ( $minlen and $total ).
8471 $minlen = $minlen < $total ? $total : $minlen;
8472 // Var maxlen can never be smaller than minlen.
8473 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8474 $additional = $maxlen - $total;
8476 // Make sure we have enough characters to fulfill
8477 // complexity requirements.
8478 $passworddigits = PASSWORD_DIGITS;
8479 while ($digits > strlen($passworddigits)) {
8480 $passworddigits .= PASSWORD_DIGITS;
8482 $passwordlower = PASSWORD_LOWER;
8483 while ($lower > strlen($passwordlower)) {
8484 $passwordlower .= PASSWORD_LOWER;
8486 $passwordupper = PASSWORD_UPPER;
8487 while ($upper > strlen($passwordupper)) {
8488 $passwordupper .= PASSWORD_UPPER;
8490 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8491 while ($nonalphanum > strlen($passwordnonalphanum)) {
8492 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8495 // Now mix and shuffle it all.
8496 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8497 substr(str_shuffle ($passwordupper), 0, $upper) .
8498 substr(str_shuffle ($passworddigits), 0, $digits) .
8499 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8500 substr(str_shuffle ($passwordlower .
8501 $passwordupper .
8502 $passworddigits .
8503 $passwordnonalphanum), 0 , $additional));
8506 return substr ($password, 0, $maxlen);
8510 * Given a float, prints it nicely.
8511 * Localized floats must not be used in calculations!
8513 * The stripzeros feature is intended for making numbers look nicer in small
8514 * areas where it is not necessary to indicate the degree of accuracy by showing
8515 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8516 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8518 * @param float $float The float to print
8519 * @param int $decimalpoints The number of decimal places to print.
8520 * @param bool $localized use localized decimal separator
8521 * @param bool $stripzeros If true, removes final zeros after decimal point
8522 * @return string locale float
8524 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8525 if (is_null($float)) {
8526 return '';
8528 if ($localized) {
8529 $separator = get_string('decsep', 'langconfig');
8530 } else {
8531 $separator = '.';
8533 $result = number_format($float, $decimalpoints, $separator, '');
8534 if ($stripzeros) {
8535 // Remove zeros and final dot if not needed.
8536 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8538 return $result;
8542 * Converts locale specific floating point/comma number back to standard PHP float value
8543 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8545 * @param string $localefloat locale aware float representation
8546 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8547 * @return mixed float|bool - false or the parsed float.
8549 function unformat_float($localefloat, $strict = false) {
8550 $localefloat = trim($localefloat);
8552 if ($localefloat == '') {
8553 return null;
8556 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8557 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8559 if ($strict && !is_numeric($localefloat)) {
8560 return false;
8563 return (float)$localefloat;
8567 * Given a simple array, this shuffles it up just like shuffle()
8568 * Unlike PHP's shuffle() this function works on any machine.
8570 * @param array $array The array to be rearranged
8571 * @return array
8573 function swapshuffle($array) {
8575 $last = count($array) - 1;
8576 for ($i = 0; $i <= $last; $i++) {
8577 $from = rand(0, $last);
8578 $curr = $array[$i];
8579 $array[$i] = $array[$from];
8580 $array[$from] = $curr;
8582 return $array;
8586 * Like {@link swapshuffle()}, but works on associative arrays
8588 * @param array $array The associative array to be rearranged
8589 * @return array
8591 function swapshuffle_assoc($array) {
8593 $newarray = array();
8594 $newkeys = swapshuffle(array_keys($array));
8596 foreach ($newkeys as $newkey) {
8597 $newarray[$newkey] = $array[$newkey];
8599 return $newarray;
8603 * Given an arbitrary array, and a number of draws,
8604 * this function returns an array with that amount
8605 * of items. The indexes are retained.
8607 * @todo Finish documenting this function
8609 * @param array $array
8610 * @param int $draws
8611 * @return array
8613 function draw_rand_array($array, $draws) {
8615 $return = array();
8617 $last = count($array);
8619 if ($draws > $last) {
8620 $draws = $last;
8623 while ($draws > 0) {
8624 $last--;
8626 $keys = array_keys($array);
8627 $rand = rand(0, $last);
8629 $return[$keys[$rand]] = $array[$keys[$rand]];
8630 unset($array[$keys[$rand]]);
8632 $draws--;
8635 return $return;
8639 * Calculate the difference between two microtimes
8641 * @param string $a The first Microtime
8642 * @param string $b The second Microtime
8643 * @return string
8645 function microtime_diff($a, $b) {
8646 list($adec, $asec) = explode(' ', $a);
8647 list($bdec, $bsec) = explode(' ', $b);
8648 return $bsec - $asec + $bdec - $adec;
8652 * Given a list (eg a,b,c,d,e) this function returns
8653 * an array of 1->a, 2->b, 3->c etc
8655 * @param string $list The string to explode into array bits
8656 * @param string $separator The separator used within the list string
8657 * @return array The now assembled array
8659 function make_menu_from_list($list, $separator=',') {
8661 $array = array_reverse(explode($separator, $list), true);
8662 foreach ($array as $key => $item) {
8663 $outarray[$key+1] = trim($item);
8665 return $outarray;
8669 * Creates an array that represents all the current grades that
8670 * can be chosen using the given grading type.
8672 * Negative numbers
8673 * are scales, zero is no grade, and positive numbers are maximum
8674 * grades.
8676 * @todo Finish documenting this function or better deprecated this completely!
8678 * @param int $gradingtype
8679 * @return array
8681 function make_grades_menu($gradingtype) {
8682 global $DB;
8684 $grades = array();
8685 if ($gradingtype < 0) {
8686 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8687 return make_menu_from_list($scale->scale);
8689 } else if ($gradingtype > 0) {
8690 for ($i=$gradingtype; $i>=0; $i--) {
8691 $grades[$i] = $i .' / '. $gradingtype;
8693 return $grades;
8695 return $grades;
8699 * make_unique_id_code
8701 * @todo Finish documenting this function
8703 * @uses $_SERVER
8704 * @param string $extra Extra string to append to the end of the code
8705 * @return string
8707 function make_unique_id_code($extra = '') {
8709 $hostname = 'unknownhost';
8710 if (!empty($_SERVER['HTTP_HOST'])) {
8711 $hostname = $_SERVER['HTTP_HOST'];
8712 } else if (!empty($_ENV['HTTP_HOST'])) {
8713 $hostname = $_ENV['HTTP_HOST'];
8714 } else if (!empty($_SERVER['SERVER_NAME'])) {
8715 $hostname = $_SERVER['SERVER_NAME'];
8716 } else if (!empty($_ENV['SERVER_NAME'])) {
8717 $hostname = $_ENV['SERVER_NAME'];
8720 $date = gmdate("ymdHis");
8722 $random = random_string(6);
8724 if ($extra) {
8725 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8726 } else {
8727 return $hostname .'+'. $date .'+'. $random;
8733 * Function to check the passed address is within the passed subnet
8735 * The parameter is a comma separated string of subnet definitions.
8736 * Subnet strings can be in one of three formats:
8737 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8738 * 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)
8739 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8740 * Code for type 1 modified from user posted comments by mediator at
8741 * {@link http://au.php.net/manual/en/function.ip2long.php}
8743 * @param string $addr The address you are checking
8744 * @param string $subnetstr The string of subnet addresses
8745 * @return bool
8747 function address_in_subnet($addr, $subnetstr) {
8749 if ($addr == '0.0.0.0') {
8750 return false;
8752 $subnets = explode(',', $subnetstr);
8753 $found = false;
8754 $addr = trim($addr);
8755 $addr = cleanremoteaddr($addr, false); // Normalise.
8756 if ($addr === null) {
8757 return false;
8759 $addrparts = explode(':', $addr);
8761 $ipv6 = strpos($addr, ':');
8763 foreach ($subnets as $subnet) {
8764 $subnet = trim($subnet);
8765 if ($subnet === '') {
8766 continue;
8769 if (strpos($subnet, '/') !== false) {
8770 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8771 list($ip, $mask) = explode('/', $subnet);
8772 $mask = trim($mask);
8773 if (!is_number($mask)) {
8774 continue; // Incorect mask number, eh?
8776 $ip = cleanremoteaddr($ip, false); // Normalise.
8777 if ($ip === null) {
8778 continue;
8780 if (strpos($ip, ':') !== false) {
8781 // IPv6.
8782 if (!$ipv6) {
8783 continue;
8785 if ($mask > 128 or $mask < 0) {
8786 continue; // Nonsense.
8788 if ($mask == 0) {
8789 return true; // Any address.
8791 if ($mask == 128) {
8792 if ($ip === $addr) {
8793 return true;
8795 continue;
8797 $ipparts = explode(':', $ip);
8798 $modulo = $mask % 16;
8799 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8800 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8801 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8802 if ($modulo == 0) {
8803 return true;
8805 $pos = ($mask-$modulo)/16;
8806 $ipnet = hexdec($ipparts[$pos]);
8807 $addrnet = hexdec($addrparts[$pos]);
8808 $mask = 0xffff << (16 - $modulo);
8809 if (($addrnet & $mask) == ($ipnet & $mask)) {
8810 return true;
8814 } else {
8815 // IPv4.
8816 if ($ipv6) {
8817 continue;
8819 if ($mask > 32 or $mask < 0) {
8820 continue; // Nonsense.
8822 if ($mask == 0) {
8823 return true;
8825 if ($mask == 32) {
8826 if ($ip === $addr) {
8827 return true;
8829 continue;
8831 $mask = 0xffffffff << (32 - $mask);
8832 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8833 return true;
8837 } else if (strpos($subnet, '-') !== false) {
8838 // 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.
8839 $parts = explode('-', $subnet);
8840 if (count($parts) != 2) {
8841 continue;
8844 if (strpos($subnet, ':') !== false) {
8845 // IPv6.
8846 if (!$ipv6) {
8847 continue;
8849 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8850 if ($ipstart === null) {
8851 continue;
8853 $ipparts = explode(':', $ipstart);
8854 $start = hexdec(array_pop($ipparts));
8855 $ipparts[] = trim($parts[1]);
8856 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8857 if ($ipend === null) {
8858 continue;
8860 $ipparts[7] = '';
8861 $ipnet = implode(':', $ipparts);
8862 if (strpos($addr, $ipnet) !== 0) {
8863 continue;
8865 $ipparts = explode(':', $ipend);
8866 $end = hexdec($ipparts[7]);
8868 $addrend = hexdec($addrparts[7]);
8870 if (($addrend >= $start) and ($addrend <= $end)) {
8871 return true;
8874 } else {
8875 // IPv4.
8876 if ($ipv6) {
8877 continue;
8879 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8880 if ($ipstart === null) {
8881 continue;
8883 $ipparts = explode('.', $ipstart);
8884 $ipparts[3] = trim($parts[1]);
8885 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8886 if ($ipend === null) {
8887 continue;
8890 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8891 return true;
8895 } else {
8896 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8897 if (strpos($subnet, ':') !== false) {
8898 // IPv6.
8899 if (!$ipv6) {
8900 continue;
8902 $parts = explode(':', $subnet);
8903 $count = count($parts);
8904 if ($parts[$count-1] === '') {
8905 unset($parts[$count-1]); // Trim trailing :'s.
8906 $count--;
8907 $subnet = implode('.', $parts);
8909 $isip = cleanremoteaddr($subnet, false); // Normalise.
8910 if ($isip !== null) {
8911 if ($isip === $addr) {
8912 return true;
8914 continue;
8915 } else if ($count > 8) {
8916 continue;
8918 $zeros = array_fill(0, 8-$count, '0');
8919 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8920 if (address_in_subnet($addr, $subnet)) {
8921 return true;
8924 } else {
8925 // IPv4.
8926 if ($ipv6) {
8927 continue;
8929 $parts = explode('.', $subnet);
8930 $count = count($parts);
8931 if ($parts[$count-1] === '') {
8932 unset($parts[$count-1]); // Trim trailing .
8933 $count--;
8934 $subnet = implode('.', $parts);
8936 if ($count == 4) {
8937 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8938 if ($subnet === $addr) {
8939 return true;
8941 continue;
8942 } else if ($count > 4) {
8943 continue;
8945 $zeros = array_fill(0, 4-$count, '0');
8946 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8947 if (address_in_subnet($addr, $subnet)) {
8948 return true;
8954 return false;
8958 * For outputting debugging info
8960 * @param string $string The string to write
8961 * @param string $eol The end of line char(s) to use
8962 * @param string $sleep Period to make the application sleep
8963 * This ensures any messages have time to display before redirect
8965 function mtrace($string, $eol="\n", $sleep=0) {
8966 global $CFG;
8968 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
8969 $fn = $CFG->mtrace_wrapper;
8970 $fn($string, $eol);
8971 return;
8972 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
8973 fwrite(STDOUT, $string.$eol);
8974 } else {
8975 echo $string . $eol;
8978 flush();
8980 // Delay to keep message on user's screen in case of subsequent redirect.
8981 if ($sleep) {
8982 sleep($sleep);
8987 * Replace 1 or more slashes or backslashes to 1 slash
8989 * @param string $path The path to strip
8990 * @return string the path with double slashes removed
8992 function cleardoubleslashes ($path) {
8993 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8997 * Is current ip in give list?
8999 * @param string $list
9000 * @return bool
9002 function remoteip_in_list($list) {
9003 $clientip = getremoteaddr(null);
9005 if (!$clientip) {
9006 // Ensure access on cli.
9007 return true;
9009 return \core\ip_utils::is_ip_in_subnet_list($clientip, $list);
9013 * Returns most reliable client address
9015 * @param string $default If an address can't be determined, then return this
9016 * @return string The remote IP address
9018 function getremoteaddr($default='0.0.0.0') {
9019 global $CFG;
9021 if (empty($CFG->getremoteaddrconf)) {
9022 // This will happen, for example, before just after the upgrade, as the
9023 // user is redirected to the admin screen.
9024 $variablestoskip = GETREMOTEADDR_SKIP_DEFAULT;
9025 } else {
9026 $variablestoskip = $CFG->getremoteaddrconf;
9028 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
9029 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9030 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9031 return $address ? $address : $default;
9034 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
9035 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9036 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9038 $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
9039 global $CFG;
9040 return !\core\ip_utils::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore ?? '', ',');
9043 // Multiple proxies can append values to this header including an
9044 // untrusted original request header so we must only trust the last ip.
9045 $address = end($forwardedaddresses);
9047 if (substr_count($address, ":") > 1) {
9048 // Remove port and brackets from IPv6.
9049 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9050 $address = $matches[1];
9052 } else {
9053 // Remove port from IPv4.
9054 if (substr_count($address, ":") == 1) {
9055 $parts = explode(":", $address);
9056 $address = $parts[0];
9060 $address = cleanremoteaddr($address);
9061 return $address ? $address : $default;
9064 if (!empty($_SERVER['REMOTE_ADDR'])) {
9065 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9066 return $address ? $address : $default;
9067 } else {
9068 return $default;
9073 * Cleans an ip address. Internal addresses are now allowed.
9074 * (Originally local addresses were not allowed.)
9076 * @param string $addr IPv4 or IPv6 address
9077 * @param bool $compress use IPv6 address compression
9078 * @return string normalised ip address string, null if error
9080 function cleanremoteaddr($addr, $compress=false) {
9081 $addr = trim($addr);
9083 if (strpos($addr, ':') !== false) {
9084 // Can be only IPv6.
9085 $parts = explode(':', $addr);
9086 $count = count($parts);
9088 if (strpos($parts[$count-1], '.') !== false) {
9089 // Legacy ipv4 notation.
9090 $last = array_pop($parts);
9091 $ipv4 = cleanremoteaddr($last, true);
9092 if ($ipv4 === null) {
9093 return null;
9095 $bits = explode('.', $ipv4);
9096 $parts[] = dechex($bits[0]).dechex($bits[1]);
9097 $parts[] = dechex($bits[2]).dechex($bits[3]);
9098 $count = count($parts);
9099 $addr = implode(':', $parts);
9102 if ($count < 3 or $count > 8) {
9103 return null; // Severly malformed.
9106 if ($count != 8) {
9107 if (strpos($addr, '::') === false) {
9108 return null; // Malformed.
9110 // Uncompress.
9111 $insertat = array_search('', $parts, true);
9112 $missing = array_fill(0, 1 + 8 - $count, '0');
9113 array_splice($parts, $insertat, 1, $missing);
9114 foreach ($parts as $key => $part) {
9115 if ($part === '') {
9116 $parts[$key] = '0';
9121 $adr = implode(':', $parts);
9122 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9123 return null; // Incorrect format - sorry.
9126 // Normalise 0s and case.
9127 $parts = array_map('hexdec', $parts);
9128 $parts = array_map('dechex', $parts);
9130 $result = implode(':', $parts);
9132 if (!$compress) {
9133 return $result;
9136 if ($result === '0:0:0:0:0:0:0:0') {
9137 return '::'; // All addresses.
9140 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9141 if ($compressed !== $result) {
9142 return $compressed;
9145 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9146 if ($compressed !== $result) {
9147 return $compressed;
9150 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9151 if ($compressed !== $result) {
9152 return $compressed;
9155 return $result;
9158 // First get all things that look like IPv4 addresses.
9159 $parts = array();
9160 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9161 return null;
9163 unset($parts[0]);
9165 foreach ($parts as $key => $match) {
9166 if ($match > 255) {
9167 return null;
9169 $parts[$key] = (int)$match; // Normalise 0s.
9172 return implode('.', $parts);
9177 * Is IP address a public address?
9179 * @param string $ip The ip to check
9180 * @return bool true if the ip is public
9182 function ip_is_public($ip) {
9183 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9187 * This function will make a complete copy of anything it's given,
9188 * regardless of whether it's an object or not.
9190 * @param mixed $thing Something you want cloned
9191 * @return mixed What ever it is you passed it
9193 function fullclone($thing) {
9194 return unserialize(serialize($thing));
9198 * Used to make sure that $min <= $value <= $max
9200 * Make sure that value is between min, and max
9202 * @param int $min The minimum value
9203 * @param int $value The value to check
9204 * @param int $max The maximum value
9205 * @return int
9207 function bounded_number($min, $value, $max) {
9208 if ($value < $min) {
9209 return $min;
9211 if ($value > $max) {
9212 return $max;
9214 return $value;
9218 * Check if there is a nested array within the passed array
9220 * @param array $array
9221 * @return bool true if there is a nested array false otherwise
9223 function array_is_nested($array) {
9224 foreach ($array as $value) {
9225 if (is_array($value)) {
9226 return true;
9229 return false;
9233 * get_performance_info() pairs up with init_performance_info()
9234 * loaded in setup.php. Returns an array with 'html' and 'txt'
9235 * values ready for use, and each of the individual stats provided
9236 * separately as well.
9238 * @return array
9240 function get_performance_info() {
9241 global $CFG, $PERF, $DB, $PAGE;
9243 $info = array();
9244 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9246 $info['html'] = '';
9247 if (!empty($CFG->themedesignermode)) {
9248 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9249 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9251 $info['html'] .= '<ul class="list-unstyled m-l-1 row">'; // Holds userfriendly HTML representation.
9253 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9255 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9256 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9258 if (function_exists('memory_get_usage')) {
9259 $info['memory_total'] = memory_get_usage();
9260 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9261 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9262 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9263 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9266 if (function_exists('memory_get_peak_usage')) {
9267 $info['memory_peak'] = memory_get_peak_usage();
9268 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9269 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9272 $info['html'] .= '</ul><ul class="list-unstyled m-l-1 row">';
9273 $inc = get_included_files();
9274 $info['includecount'] = count($inc);
9275 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9276 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9278 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9279 // We can not track more performance before installation or before PAGE init, sorry.
9280 return $info;
9283 $filtermanager = filter_manager::instance();
9284 if (method_exists($filtermanager, 'get_performance_summary')) {
9285 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9286 $info = array_merge($filterinfo, $info);
9287 foreach ($filterinfo as $key => $value) {
9288 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9289 $info['txt'] .= "$key: $value ";
9293 $stringmanager = get_string_manager();
9294 if (method_exists($stringmanager, 'get_performance_summary')) {
9295 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9296 $info = array_merge($filterinfo, $info);
9297 foreach ($filterinfo as $key => $value) {
9298 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9299 $info['txt'] .= "$key: $value ";
9303 if (!empty($PERF->logwrites)) {
9304 $info['logwrites'] = $PERF->logwrites;
9305 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9306 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9309 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9310 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9311 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9313 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9314 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9315 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9317 if (function_exists('posix_times')) {
9318 $ptimes = posix_times();
9319 if (is_array($ptimes)) {
9320 foreach ($ptimes as $key => $val) {
9321 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9323 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9324 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9325 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9329 // Grab the load average for the last minute.
9330 // /proc will only work under some linux configurations
9331 // while uptime is there under MacOSX/Darwin and other unices.
9332 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9333 list($serverload) = explode(' ', $loadavg[0]);
9334 unset($loadavg);
9335 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9336 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9337 $serverload = $matches[1];
9338 } else {
9339 trigger_error('Could not parse uptime output!');
9342 if (!empty($serverload)) {
9343 $info['serverload'] = $serverload;
9344 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9345 $info['txt'] .= "serverload: {$info['serverload']} ";
9348 // Display size of session if session started.
9349 if ($si = \core\session\manager::get_performance_info()) {
9350 $info['sessionsize'] = $si['size'];
9351 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9352 $info['txt'] .= $si['txt'];
9355 $info['html'] .= '</ul>';
9356 if ($stats = cache_helper::get_stats()) {
9357 $html = '<ul class="cachesused list-unstyled m-l-1 row">';
9358 $html .= '<li class="cache-stats-heading font-weight-bold">Caches used (hits/misses/sets)</li>';
9359 $html .= '</ul><ul class="cachesused list-unstyled m-l-1">';
9360 $text = 'Caches used (hits/misses/sets): ';
9361 $hits = 0;
9362 $misses = 0;
9363 $sets = 0;
9364 foreach ($stats as $definition => $details) {
9365 switch ($details['mode']) {
9366 case cache_store::MODE_APPLICATION:
9367 $modeclass = 'application';
9368 $mode = ' <span title="application cache">[a]</span>';
9369 break;
9370 case cache_store::MODE_SESSION:
9371 $modeclass = 'session';
9372 $mode = ' <span title="session cache">[s]</span>';
9373 break;
9374 case cache_store::MODE_REQUEST:
9375 $modeclass = 'request';
9376 $mode = ' <span title="request cache">[r]</span>';
9377 break;
9379 $html .= '<ul class="cache-definition-stats list-unstyled m-l-1 m-b-1 cache-mode-'.$modeclass.' card d-inline-block">';
9380 $html .= '<li class="cache-definition-stats-heading p-t-1 card-header bg-dark bg-inverse font-weight-bold">' .
9381 $definition . $mode.'</li>';
9382 $text .= "$definition {";
9383 foreach ($details['stores'] as $store => $data) {
9384 $hits += $data['hits'];
9385 $misses += $data['misses'];
9386 $sets += $data['sets'];
9387 if ($data['hits'] == 0 and $data['misses'] > 0) {
9388 $cachestoreclass = 'nohits text-danger';
9389 } else if ($data['hits'] < $data['misses']) {
9390 $cachestoreclass = 'lowhits text-warning';
9391 } else {
9392 $cachestoreclass = 'hihits text-success';
9394 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9395 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">" .
9396 "$store: $data[hits] / $data[misses] / $data[sets]</li>";
9397 // This makes boxes of same sizes.
9398 if (count($details['stores']) == 1) {
9399 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">&nbsp;</li>";
9402 $html .= '</ul>';
9403 $text .= '} ';
9405 $html .= '</ul> ';
9406 $html .= "<div class='cache-total-stats row'>Total: $hits / $misses / $sets</div>";
9407 $info['cachesused'] = "$hits / $misses / $sets";
9408 $info['html'] .= $html;
9409 $info['txt'] .= $text.'. ';
9410 } else {
9411 $info['cachesused'] = '0 / 0 / 0';
9412 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9413 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9416 $info['html'] = '<div class="performanceinfo siteinfo container-fluid">'.$info['html'].'</div>';
9417 return $info;
9421 * Delete directory or only its content
9423 * @param string $dir directory path
9424 * @param bool $contentonly
9425 * @return bool success, true also if dir does not exist
9427 function remove_dir($dir, $contentonly=false) {
9428 if (!file_exists($dir)) {
9429 // Nothing to do.
9430 return true;
9432 if (!$handle = opendir($dir)) {
9433 return false;
9435 $result = true;
9436 while (false!==($item = readdir($handle))) {
9437 if ($item != '.' && $item != '..') {
9438 if (is_dir($dir.'/'.$item)) {
9439 $result = remove_dir($dir.'/'.$item) && $result;
9440 } else {
9441 $result = unlink($dir.'/'.$item) && $result;
9445 closedir($handle);
9446 if ($contentonly) {
9447 clearstatcache(); // Make sure file stat cache is properly invalidated.
9448 return $result;
9450 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9451 clearstatcache(); // Make sure file stat cache is properly invalidated.
9452 return $result;
9456 * Detect if an object or a class contains a given property
9457 * will take an actual object or the name of a class
9459 * @param mix $obj Name of class or real object to test
9460 * @param string $property name of property to find
9461 * @return bool true if property exists
9463 function object_property_exists( $obj, $property ) {
9464 if (is_string( $obj )) {
9465 $properties = get_class_vars( $obj );
9466 } else {
9467 $properties = get_object_vars( $obj );
9469 return array_key_exists( $property, $properties );
9473 * Converts an object into an associative array
9475 * This function converts an object into an associative array by iterating
9476 * over its public properties. Because this function uses the foreach
9477 * construct, Iterators are respected. It works recursively on arrays of objects.
9478 * Arrays and simple values are returned as is.
9480 * If class has magic properties, it can implement IteratorAggregate
9481 * and return all available properties in getIterator()
9483 * @param mixed $var
9484 * @return array
9486 function convert_to_array($var) {
9487 $result = array();
9489 // Loop over elements/properties.
9490 foreach ($var as $key => $value) {
9491 // Recursively convert objects.
9492 if (is_object($value) || is_array($value)) {
9493 $result[$key] = convert_to_array($value);
9494 } else {
9495 // Simple values are untouched.
9496 $result[$key] = $value;
9499 return $result;
9503 * Detect a custom script replacement in the data directory that will
9504 * replace an existing moodle script
9506 * @return string|bool full path name if a custom script exists, false if no custom script exists
9508 function custom_script_path() {
9509 global $CFG, $SCRIPT;
9511 if ($SCRIPT === null) {
9512 // Probably some weird external script.
9513 return false;
9516 $scriptpath = $CFG->customscripts . $SCRIPT;
9518 // Check the custom script exists.
9519 if (file_exists($scriptpath) and is_file($scriptpath)) {
9520 return $scriptpath;
9521 } else {
9522 return false;
9527 * Returns whether or not the user object is a remote MNET user. This function
9528 * is in moodlelib because it does not rely on loading any of the MNET code.
9530 * @param object $user A valid user object
9531 * @return bool True if the user is from a remote Moodle.
9533 function is_mnet_remote_user($user) {
9534 global $CFG;
9536 if (!isset($CFG->mnet_localhost_id)) {
9537 include_once($CFG->dirroot . '/mnet/lib.php');
9538 $env = new mnet_environment();
9539 $env->init();
9540 unset($env);
9543 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9547 * This function will search for browser prefereed languages, setting Moodle
9548 * to use the best one available if $SESSION->lang is undefined
9550 function setup_lang_from_browser() {
9551 global $CFG, $SESSION, $USER;
9553 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9554 // Lang is defined in session or user profile, nothing to do.
9555 return;
9558 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9559 return;
9562 // Extract and clean langs from headers.
9563 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9564 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9565 $rawlangs = explode(',', $rawlangs); // Convert to array.
9566 $langs = array();
9568 $order = 1.0;
9569 foreach ($rawlangs as $lang) {
9570 if (strpos($lang, ';') === false) {
9571 $langs[(string)$order] = $lang;
9572 $order = $order-0.01;
9573 } else {
9574 $parts = explode(';', $lang);
9575 $pos = strpos($parts[1], '=');
9576 $langs[substr($parts[1], $pos+1)] = $parts[0];
9579 krsort($langs, SORT_NUMERIC);
9581 // Look for such langs under standard locations.
9582 foreach ($langs as $lang) {
9583 // Clean it properly for include.
9584 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9585 if (get_string_manager()->translation_exists($lang, false)) {
9586 // Lang exists, set it in session.
9587 $SESSION->lang = $lang;
9588 // We have finished. Go out.
9589 break;
9592 return;
9596 * Check if $url matches anything in proxybypass list
9598 * Any errors just result in the proxy being used (least bad)
9600 * @param string $url url to check
9601 * @return boolean true if we should bypass the proxy
9603 function is_proxybypass( $url ) {
9604 global $CFG;
9606 // Sanity check.
9607 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9608 return false;
9611 // Get the host part out of the url.
9612 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9613 return false;
9616 // Get the possible bypass hosts into an array.
9617 $matches = explode( ',', $CFG->proxybypass );
9619 // Check for a match.
9620 // (IPs need to match the left hand side and hosts the right of the url,
9621 // but we can recklessly check both as there can't be a false +ve).
9622 foreach ($matches as $match) {
9623 $match = trim($match);
9625 // Try for IP match (Left side).
9626 $lhs = substr($host, 0, strlen($match));
9627 if (strcasecmp($match, $lhs)==0) {
9628 return true;
9631 // Try for host match (Right side).
9632 $rhs = substr($host, -strlen($match));
9633 if (strcasecmp($match, $rhs)==0) {
9634 return true;
9638 // Nothing matched.
9639 return false;
9643 * Check if the passed navigation is of the new style
9645 * @param mixed $navigation
9646 * @return bool true for yes false for no
9648 function is_newnav($navigation) {
9649 if (is_array($navigation) && !empty($navigation['newnav'])) {
9650 return true;
9651 } else {
9652 return false;
9657 * Checks whether the given variable name is defined as a variable within the given object.
9659 * This will NOT work with stdClass objects, which have no class variables.
9661 * @param string $var The variable name
9662 * @param object $object The object to check
9663 * @return boolean
9665 function in_object_vars($var, $object) {
9666 $classvars = get_class_vars(get_class($object));
9667 $classvars = array_keys($classvars);
9668 return in_array($var, $classvars);
9672 * Returns an array without repeated objects.
9673 * This function is similar to array_unique, but for arrays that have objects as values
9675 * @param array $array
9676 * @param bool $keepkeyassoc
9677 * @return array
9679 function object_array_unique($array, $keepkeyassoc = true) {
9680 $duplicatekeys = array();
9681 $tmp = array();
9683 foreach ($array as $key => $val) {
9684 // Convert objects to arrays, in_array() does not support objects.
9685 if (is_object($val)) {
9686 $val = (array)$val;
9689 if (!in_array($val, $tmp)) {
9690 $tmp[] = $val;
9691 } else {
9692 $duplicatekeys[] = $key;
9696 foreach ($duplicatekeys as $key) {
9697 unset($array[$key]);
9700 return $keepkeyassoc ? $array : array_values($array);
9704 * Is a userid the primary administrator?
9706 * @param int $userid int id of user to check
9707 * @return boolean
9709 function is_primary_admin($userid) {
9710 $primaryadmin = get_admin();
9712 if ($userid == $primaryadmin->id) {
9713 return true;
9714 } else {
9715 return false;
9720 * Returns the site identifier
9722 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9724 function get_site_identifier() {
9725 global $CFG;
9726 // Check to see if it is missing. If so, initialise it.
9727 if (empty($CFG->siteidentifier)) {
9728 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9730 // Return it.
9731 return $CFG->siteidentifier;
9735 * Check whether the given password has no more than the specified
9736 * number of consecutive identical characters.
9738 * @param string $password password to be checked against the password policy
9739 * @param integer $maxchars maximum number of consecutive identical characters
9740 * @return bool
9742 function check_consecutive_identical_characters($password, $maxchars) {
9744 if ($maxchars < 1) {
9745 return true; // Zero 0 is to disable this check.
9747 if (strlen($password) <= $maxchars) {
9748 return true; // Too short to fail this test.
9751 $previouschar = '';
9752 $consecutivecount = 1;
9753 foreach (str_split($password) as $char) {
9754 if ($char != $previouschar) {
9755 $consecutivecount = 1;
9756 } else {
9757 $consecutivecount++;
9758 if ($consecutivecount > $maxchars) {
9759 return false; // Check failed already.
9763 $previouschar = $char;
9766 return true;
9770 * Helper function to do partial function binding.
9771 * so we can use it for preg_replace_callback, for example
9772 * this works with php functions, user functions, static methods and class methods
9773 * it returns you a callback that you can pass on like so:
9775 * $callback = partial('somefunction', $arg1, $arg2);
9776 * or
9777 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9778 * or even
9779 * $obj = new someclass();
9780 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9782 * and then the arguments that are passed through at calltime are appended to the argument list.
9784 * @param mixed $function a php callback
9785 * @param mixed $arg1,... $argv arguments to partially bind with
9786 * @return array Array callback
9788 function partial() {
9789 if (!class_exists('partial')) {
9791 * Used to manage function binding.
9792 * @copyright 2009 Penny Leach
9793 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9795 class partial{
9796 /** @var array */
9797 public $values = array();
9798 /** @var string The function to call as a callback. */
9799 public $func;
9801 * Constructor
9802 * @param string $func
9803 * @param array $args
9805 public function __construct($func, $args) {
9806 $this->values = $args;
9807 $this->func = $func;
9810 * Calls the callback function.
9811 * @return mixed
9813 public function method() {
9814 $args = func_get_args();
9815 return call_user_func_array($this->func, array_merge($this->values, $args));
9819 $args = func_get_args();
9820 $func = array_shift($args);
9821 $p = new partial($func, $args);
9822 return array($p, 'method');
9826 * helper function to load up and initialise the mnet environment
9827 * this must be called before you use mnet functions.
9829 * @return mnet_environment the equivalent of old $MNET global
9831 function get_mnet_environment() {
9832 global $CFG;
9833 require_once($CFG->dirroot . '/mnet/lib.php');
9834 static $instance = null;
9835 if (empty($instance)) {
9836 $instance = new mnet_environment();
9837 $instance->init();
9839 return $instance;
9843 * during xmlrpc server code execution, any code wishing to access
9844 * information about the remote peer must use this to get it.
9846 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9848 function get_mnet_remote_client() {
9849 if (!defined('MNET_SERVER')) {
9850 debugging(get_string('notinxmlrpcserver', 'mnet'));
9851 return false;
9853 global $MNET_REMOTE_CLIENT;
9854 if (isset($MNET_REMOTE_CLIENT)) {
9855 return $MNET_REMOTE_CLIENT;
9857 return false;
9861 * during the xmlrpc server code execution, this will be called
9862 * to setup the object returned by {@link get_mnet_remote_client}
9864 * @param mnet_remote_client $client the client to set up
9865 * @throws moodle_exception
9867 function set_mnet_remote_client($client) {
9868 if (!defined('MNET_SERVER')) {
9869 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9871 global $MNET_REMOTE_CLIENT;
9872 $MNET_REMOTE_CLIENT = $client;
9876 * return the jump url for a given remote user
9877 * this is used for rewriting forum post links in emails, etc
9879 * @param stdclass $user the user to get the idp url for
9881 function mnet_get_idp_jump_url($user) {
9882 global $CFG;
9884 static $mnetjumps = array();
9885 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9886 $idp = mnet_get_peer_host($user->mnethostid);
9887 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9888 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9890 return $mnetjumps[$user->mnethostid];
9894 * Gets the homepage to use for the current user
9896 * @return int One of HOMEPAGE_*
9898 function get_home_page() {
9899 global $CFG;
9901 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9902 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9903 return HOMEPAGE_MY;
9904 } else {
9905 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9908 return HOMEPAGE_SITE;
9912 * Gets the name of a course to be displayed when showing a list of courses.
9913 * By default this is just $course->fullname but user can configure it. The
9914 * result of this function should be passed through print_string.
9915 * @param stdClass|course_in_list $course Moodle course object
9916 * @return string Display name of course (either fullname or short + fullname)
9918 function get_course_display_name_for_list($course) {
9919 global $CFG;
9920 if (!empty($CFG->courselistshortnames)) {
9921 if (!($course instanceof stdClass)) {
9922 $course = (object)convert_to_array($course);
9924 return get_string('courseextendednamedisplay', '', $course);
9925 } else {
9926 return $course->fullname;
9931 * Safe analogue of unserialize() that can only parse arrays
9933 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
9934 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
9935 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
9937 * @param string $expression
9938 * @return array|bool either parsed array or false if parsing was impossible.
9940 function unserialize_array($expression) {
9941 $subs = [];
9942 // Find nested arrays, parse them and store in $subs , substitute with special string.
9943 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
9944 $key = '--SUB' . count($subs) . '--';
9945 $subs[$key] = unserialize_array($matches[2]);
9946 if ($subs[$key] === false) {
9947 return false;
9949 $expression = str_replace($matches[2], $key . ';', $expression);
9952 // Check the expression is an array.
9953 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
9954 return false;
9956 // Get the size and elements of an array (key;value;key;value;....).
9957 $parts = explode(';', $matches1[2]);
9958 $size = intval($matches1[1]);
9959 if (count($parts) < $size * 2 + 1) {
9960 return false;
9962 // Analyze each part and make sure it is an integer or string or a substitute.
9963 $value = [];
9964 for ($i = 0; $i < $size * 2; $i++) {
9965 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
9966 $parts[$i] = (int)$matches2[1];
9967 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
9968 $parts[$i] = $matches3[2];
9969 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
9970 $parts[$i] = $subs[$parts[$i]];
9971 } else {
9972 return false;
9975 // Combine keys and values.
9976 for ($i = 0; $i < $size * 2; $i += 2) {
9977 $value[$parts[$i]] = $parts[$i+1];
9979 return $value;
9983 * The lang_string class
9985 * This special class is used to create an object representation of a string request.
9986 * It is special because processing doesn't occur until the object is first used.
9987 * The class was created especially to aid performance in areas where strings were
9988 * required to be generated but were not necessarily used.
9989 * As an example the admin tree when generated uses over 1500 strings, of which
9990 * normally only 1/3 are ever actually printed at any time.
9991 * The performance advantage is achieved by not actually processing strings that
9992 * arn't being used, as such reducing the processing required for the page.
9994 * How to use the lang_string class?
9995 * There are two methods of using the lang_string class, first through the
9996 * forth argument of the get_string function, and secondly directly.
9997 * The following are examples of both.
9998 * 1. Through get_string calls e.g.
9999 * $string = get_string($identifier, $component, $a, true);
10000 * $string = get_string('yes', 'moodle', null, true);
10001 * 2. Direct instantiation
10002 * $string = new lang_string($identifier, $component, $a, $lang);
10003 * $string = new lang_string('yes');
10005 * How do I use a lang_string object?
10006 * The lang_string object makes use of a magic __toString method so that you
10007 * are able to use the object exactly as you would use a string in most cases.
10008 * This means you are able to collect it into a variable and then directly
10009 * echo it, or concatenate it into another string, or similar.
10010 * The other thing you can do is manually get the string by calling the
10011 * lang_strings out method e.g.
10012 * $string = new lang_string('yes');
10013 * $string->out();
10014 * Also worth noting is that the out method can take one argument, $lang which
10015 * allows the developer to change the language on the fly.
10017 * When should I use a lang_string object?
10018 * The lang_string object is designed to be used in any situation where a
10019 * string may not be needed, but needs to be generated.
10020 * The admin tree is a good example of where lang_string objects should be
10021 * used.
10022 * A more practical example would be any class that requries strings that may
10023 * not be printed (after all classes get renderer by renderers and who knows
10024 * what they will do ;))
10026 * When should I not use a lang_string object?
10027 * Don't use lang_strings when you are going to use a string immediately.
10028 * There is no need as it will be processed immediately and there will be no
10029 * advantage, and in fact perhaps a negative hit as a class has to be
10030 * instantiated for a lang_string object, however get_string won't require
10031 * that.
10033 * Limitations:
10034 * 1. You cannot use a lang_string object as an array offset. Doing so will
10035 * result in PHP throwing an error. (You can use it as an object property!)
10037 * @package core
10038 * @category string
10039 * @copyright 2011 Sam Hemelryk
10040 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10042 class lang_string {
10044 /** @var string The strings identifier */
10045 protected $identifier;
10046 /** @var string The strings component. Default '' */
10047 protected $component = '';
10048 /** @var array|stdClass Any arguments required for the string. Default null */
10049 protected $a = null;
10050 /** @var string The language to use when processing the string. Default null */
10051 protected $lang = null;
10053 /** @var string The processed string (once processed) */
10054 protected $string = null;
10057 * A special boolean. If set to true then the object has been woken up and
10058 * cannot be regenerated. If this is set then $this->string MUST be used.
10059 * @var bool
10061 protected $forcedstring = false;
10064 * Constructs a lang_string object
10066 * This function should do as little processing as possible to ensure the best
10067 * performance for strings that won't be used.
10069 * @param string $identifier The strings identifier
10070 * @param string $component The strings component
10071 * @param stdClass|array $a Any arguments the string requires
10072 * @param string $lang The language to use when processing the string.
10073 * @throws coding_exception
10075 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10076 if (empty($component)) {
10077 $component = 'moodle';
10080 $this->identifier = $identifier;
10081 $this->component = $component;
10082 $this->lang = $lang;
10084 // We MUST duplicate $a to ensure that it if it changes by reference those
10085 // changes are not carried across.
10086 // To do this we always ensure $a or its properties/values are strings
10087 // and that any properties/values that arn't convertable are forgotten.
10088 if (!empty($a)) {
10089 if (is_scalar($a)) {
10090 $this->a = $a;
10091 } else if ($a instanceof lang_string) {
10092 $this->a = $a->out();
10093 } else if (is_object($a) or is_array($a)) {
10094 $a = (array)$a;
10095 $this->a = array();
10096 foreach ($a as $key => $value) {
10097 // Make sure conversion errors don't get displayed (results in '').
10098 if (is_array($value)) {
10099 $this->a[$key] = '';
10100 } else if (is_object($value)) {
10101 if (method_exists($value, '__toString')) {
10102 $this->a[$key] = $value->__toString();
10103 } else {
10104 $this->a[$key] = '';
10106 } else {
10107 $this->a[$key] = (string)$value;
10113 if (debugging(false, DEBUG_DEVELOPER)) {
10114 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10115 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10117 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10118 throw new coding_exception('Invalid string compontent. Please check your string definition');
10120 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10121 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10127 * Processes the string.
10129 * This function actually processes the string, stores it in the string property
10130 * and then returns it.
10131 * You will notice that this function is VERY similar to the get_string method.
10132 * That is because it is pretty much doing the same thing.
10133 * However as this function is an upgrade it isn't as tolerant to backwards
10134 * compatibility.
10136 * @return string
10137 * @throws coding_exception
10139 protected function get_string() {
10140 global $CFG;
10142 // Check if we need to process the string.
10143 if ($this->string === null) {
10144 // Check the quality of the identifier.
10145 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10146 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);
10149 // Process the string.
10150 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10151 // Debugging feature lets you display string identifier and component.
10152 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10153 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10156 // Return the string.
10157 return $this->string;
10161 * Returns the string
10163 * @param string $lang The langauge to use when processing the string
10164 * @return string
10166 public function out($lang = null) {
10167 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10168 if ($this->forcedstring) {
10169 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10170 return $this->get_string();
10172 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10173 return $translatedstring->out();
10175 return $this->get_string();
10179 * Magic __toString method for printing a string
10181 * @return string
10183 public function __toString() {
10184 return $this->get_string();
10188 * Magic __set_state method used for var_export
10190 * @return string
10192 public function __set_state() {
10193 return $this->get_string();
10197 * Prepares the lang_string for sleep and stores only the forcedstring and
10198 * string properties... the string cannot be regenerated so we need to ensure
10199 * it is generated for this.
10201 * @return string
10203 public function __sleep() {
10204 $this->get_string();
10205 $this->forcedstring = true;
10206 return array('forcedstring', 'string', 'lang');
10210 * Returns the identifier.
10212 * @return string
10214 public function get_identifier() {
10215 return $this->identifier;
10219 * Returns the component.
10221 * @return string
10223 public function get_component() {
10224 return $this->component;
10229 * Get human readable name describing the given callable.
10231 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10232 * It does not check if the callable actually exists.
10234 * @param callable|string|array $callable
10235 * @return string|bool Human readable name of callable, or false if not a valid callable.
10237 function get_callable_name($callable) {
10239 if (!is_callable($callable, true, $name)) {
10240 return false;
10242 } else {
10243 return $name;
10248 * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10249 * Never put your faith on this function and rely on its accuracy as there might be false positives.
10250 * It just performs some simple checks, and mainly is used for places where we want to hide some options
10251 * such as site registration when $CFG->wwwroot is not publicly accessible.
10252 * Good thing is there is no false negative.
10254 * @return bool
10256 function site_is_public() {
10257 global $CFG;
10259 $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
10261 if ($host === 'localhost' || preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10262 $ispublic = false;
10263 } else if (\core\ip_utils::is_ip_address($host) && !ip_is_public($host)) {
10264 $ispublic = false;
10265 } else {
10266 $ispublic = true;
10269 return $ispublic;