MDL-64324 core_form: randomly generate id attribute on forms
[moodle.git] / lib / moodlelib.php
blob18e7a74cef53451ebf2d399e21a334e6d941a68b
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 // Blog access level constant declaration.
367 define ('BLOG_USER_LEVEL', 1);
368 define ('BLOG_GROUP_LEVEL', 2);
369 define ('BLOG_COURSE_LEVEL', 3);
370 define ('BLOG_SITE_LEVEL', 4);
371 define ('BLOG_GLOBAL_LEVEL', 5);
374 // Tag constants.
376 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
377 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
380 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
382 define('TAG_MAX_LENGTH', 50);
384 // Password policy constants.
385 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387 define ('PASSWORD_DIGITS', '0123456789');
388 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
390 // Feature constants.
391 // Used for plugin_supports() to report features that are, or are not, supported by a module.
393 /** True if module can provide a grade */
394 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
395 /** True if module supports outcomes */
396 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
397 /** True if module supports advanced grading methods */
398 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
399 /** True if module controls the grade visibility over the gradebook */
400 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
401 /** True if module supports plagiarism plugins */
402 define('FEATURE_PLAGIARISM', 'plagiarism');
404 /** True if module has code to track whether somebody viewed it */
405 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
406 /** True if module has custom completion rules */
407 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
409 /** True if module has no 'view' page (like label) */
410 define('FEATURE_NO_VIEW_LINK', 'viewlink');
411 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
418 * True if module supports groupmembersonly (which no longer exists)
419 * @deprecated Since Moodle 2.8
421 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
423 /** Type of module */
424 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
425 /** True if module supports intro editor */
426 define('FEATURE_MOD_INTRO', 'mod_intro');
427 /** True if module has default completion */
428 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
430 define('FEATURE_COMMENT', 'comment');
432 define('FEATURE_RATE', 'rate');
433 /** True if module supports backup/restore of moodle2 format */
434 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
436 /** True if module can show description on course main page */
437 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
439 /** True if module uses the question bank */
440 define('FEATURE_USES_QUESTIONS', 'usesquestions');
443 * Maximum filename char size
445 define('MAX_FILENAME_SIZE', 100);
447 /** Unspecified module archetype */
448 define('MOD_ARCHETYPE_OTHER', 0);
449 /** Resource-like type module */
450 define('MOD_ARCHETYPE_RESOURCE', 1);
451 /** Assignment module archetype */
452 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
453 /** System (not user-addable) module archetype */
454 define('MOD_ARCHETYPE_SYSTEM', 3);
457 * Security token used for allowing access
458 * from external application such as web services.
459 * Scripts do not use any session, performance is relatively
460 * low because we need to load access info in each request.
461 * Scripts are executed in parallel.
463 define('EXTERNAL_TOKEN_PERMANENT', 0);
466 * Security token used for allowing access
467 * of embedded applications, the code is executed in the
468 * active user session. Token is invalidated after user logs out.
469 * Scripts are executed serially - normal session locking is used.
471 define('EXTERNAL_TOKEN_EMBEDDED', 1);
474 * The home page should be the site home
476 define('HOMEPAGE_SITE', 0);
478 * The home page should be the users my page
480 define('HOMEPAGE_MY', 1);
482 * The home page can be chosen by the user
484 define('HOMEPAGE_USER', 2);
487 * Hub directory url (should be moodle.org)
489 define('HUB_HUBDIRECTORYURL', "https://hubdirectory.moodle.org");
493 * Moodle.net url (should be moodle.net)
495 define('HUB_MOODLEORGHUBURL', "https://moodle.net");
496 define('HUB_OLDMOODLEORGHUBURL', "http://hub.moodle.org");
499 * Moodle mobile app service name
501 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
504 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
506 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
509 * Course display settings: display all sections on one page.
511 define('COURSE_DISPLAY_SINGLEPAGE', 0);
513 * Course display settings: split pages into a page per section.
515 define('COURSE_DISPLAY_MULTIPAGE', 1);
518 * Authentication constant: String used in password field when password is not stored.
520 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
523 * Email from header to never include via information.
525 define('EMAIL_VIA_NEVER', 0);
528 * Email from header to always include via information.
530 define('EMAIL_VIA_ALWAYS', 1);
533 * Email from header to only include via information if the address is no-reply.
535 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
537 // PARAMETER HANDLING.
540 * Returns a particular value for the named variable, taken from
541 * POST or GET. If the parameter doesn't exist then an error is
542 * thrown because we require this variable.
544 * This function should be used to initialise all required values
545 * in a script that are based on parameters. Usually it will be
546 * used like this:
547 * $id = required_param('id', PARAM_INT);
549 * Please note the $type parameter is now required and the value can not be array.
551 * @param string $parname the name of the page parameter we want
552 * @param string $type expected type of parameter
553 * @return mixed
554 * @throws coding_exception
556 function required_param($parname, $type) {
557 if (func_num_args() != 2 or empty($parname) or empty($type)) {
558 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
560 // POST has precedence.
561 if (isset($_POST[$parname])) {
562 $param = $_POST[$parname];
563 } else if (isset($_GET[$parname])) {
564 $param = $_GET[$parname];
565 } else {
566 print_error('missingparam', '', '', $parname);
569 if (is_array($param)) {
570 debugging('Invalid array parameter detected in required_param(): '.$parname);
571 // TODO: switch to fatal error in Moodle 2.3.
572 return required_param_array($parname, $type);
575 return clean_param($param, $type);
579 * Returns a particular array value for the named variable, taken from
580 * POST or GET. If the parameter doesn't exist then an error is
581 * thrown because we require this variable.
583 * This function should be used to initialise all required values
584 * in a script that are based on parameters. Usually it will be
585 * used like this:
586 * $ids = required_param_array('ids', PARAM_INT);
588 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
590 * @param string $parname the name of the page parameter we want
591 * @param string $type expected type of parameter
592 * @return array
593 * @throws coding_exception
595 function required_param_array($parname, $type) {
596 if (func_num_args() != 2 or empty($parname) or empty($type)) {
597 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
599 // POST has precedence.
600 if (isset($_POST[$parname])) {
601 $param = $_POST[$parname];
602 } else if (isset($_GET[$parname])) {
603 $param = $_GET[$parname];
604 } else {
605 print_error('missingparam', '', '', $parname);
607 if (!is_array($param)) {
608 print_error('missingparam', '', '', $parname);
611 $result = array();
612 foreach ($param as $key => $value) {
613 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
614 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
615 continue;
617 $result[$key] = clean_param($value, $type);
620 return $result;
624 * Returns a particular value for the named variable, taken from
625 * POST or GET, otherwise returning a given default.
627 * This function should be used to initialise all optional values
628 * in a script that are based on parameters. Usually it will be
629 * used like this:
630 * $name = optional_param('name', 'Fred', PARAM_TEXT);
632 * Please note the $type parameter is now required and the value can not be array.
634 * @param string $parname the name of the page parameter we want
635 * @param mixed $default the default value to return if nothing is found
636 * @param string $type expected type of parameter
637 * @return mixed
638 * @throws coding_exception
640 function optional_param($parname, $default, $type) {
641 if (func_num_args() != 3 or empty($parname) or empty($type)) {
642 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
645 // POST has precedence.
646 if (isset($_POST[$parname])) {
647 $param = $_POST[$parname];
648 } else if (isset($_GET[$parname])) {
649 $param = $_GET[$parname];
650 } else {
651 return $default;
654 if (is_array($param)) {
655 debugging('Invalid array parameter detected in required_param(): '.$parname);
656 // TODO: switch to $default in Moodle 2.3.
657 return optional_param_array($parname, $default, $type);
660 return clean_param($param, $type);
664 * Returns a particular array value for the named variable, taken from
665 * POST or GET, otherwise returning a given default.
667 * This function should be used to initialise all optional values
668 * in a script that are based on parameters. Usually it will be
669 * used like this:
670 * $ids = optional_param('id', array(), PARAM_INT);
672 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
674 * @param string $parname the name of the page parameter we want
675 * @param mixed $default the default value to return if nothing is found
676 * @param string $type expected type of parameter
677 * @return array
678 * @throws coding_exception
680 function optional_param_array($parname, $default, $type) {
681 if (func_num_args() != 3 or empty($parname) or empty($type)) {
682 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
685 // POST has precedence.
686 if (isset($_POST[$parname])) {
687 $param = $_POST[$parname];
688 } else if (isset($_GET[$parname])) {
689 $param = $_GET[$parname];
690 } else {
691 return $default;
693 if (!is_array($param)) {
694 debugging('optional_param_array() expects array parameters only: '.$parname);
695 return $default;
698 $result = array();
699 foreach ($param as $key => $value) {
700 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
701 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
702 continue;
704 $result[$key] = clean_param($value, $type);
707 return $result;
711 * Strict validation of parameter values, the values are only converted
712 * to requested PHP type. Internally it is using clean_param, the values
713 * before and after cleaning must be equal - otherwise
714 * an invalid_parameter_exception is thrown.
715 * Objects and classes are not accepted.
717 * @param mixed $param
718 * @param string $type PARAM_ constant
719 * @param bool $allownull are nulls valid value?
720 * @param string $debuginfo optional debug information
721 * @return mixed the $param value converted to PHP type
722 * @throws invalid_parameter_exception if $param is not of given type
724 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
725 if (is_null($param)) {
726 if ($allownull == NULL_ALLOWED) {
727 return null;
728 } else {
729 throw new invalid_parameter_exception($debuginfo);
732 if (is_array($param) or is_object($param)) {
733 throw new invalid_parameter_exception($debuginfo);
736 $cleaned = clean_param($param, $type);
738 if ($type == PARAM_FLOAT) {
739 // Do not detect precision loss here.
740 if (is_float($param) or is_int($param)) {
741 // These always fit.
742 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
743 throw new invalid_parameter_exception($debuginfo);
745 } else if ((string)$param !== (string)$cleaned) {
746 // Conversion to string is usually lossless.
747 throw new invalid_parameter_exception($debuginfo);
750 return $cleaned;
754 * Makes sure array contains only the allowed types, this function does not validate array key names!
756 * <code>
757 * $options = clean_param($options, PARAM_INT);
758 * </code>
760 * @param array $param the variable array we are cleaning
761 * @param string $type expected format of param after cleaning.
762 * @param bool $recursive clean recursive arrays
763 * @return array
764 * @throws coding_exception
766 function clean_param_array(array $param = null, $type, $recursive = false) {
767 // Convert null to empty array.
768 $param = (array)$param;
769 foreach ($param as $key => $value) {
770 if (is_array($value)) {
771 if ($recursive) {
772 $param[$key] = clean_param_array($value, $type, true);
773 } else {
774 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
776 } else {
777 $param[$key] = clean_param($value, $type);
780 return $param;
784 * Used by {@link optional_param()} and {@link required_param()} to
785 * clean the variables and/or cast to specific types, based on
786 * an options field.
787 * <code>
788 * $course->format = clean_param($course->format, PARAM_ALPHA);
789 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
790 * </code>
792 * @param mixed $param the variable we are cleaning
793 * @param string $type expected format of param after cleaning.
794 * @return mixed
795 * @throws coding_exception
797 function clean_param($param, $type) {
798 global $CFG;
800 if (is_array($param)) {
801 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
802 } else if (is_object($param)) {
803 if (method_exists($param, '__toString')) {
804 $param = $param->__toString();
805 } else {
806 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
810 switch ($type) {
811 case PARAM_RAW:
812 // No cleaning at all.
813 $param = fix_utf8($param);
814 return $param;
816 case PARAM_RAW_TRIMMED:
817 // No cleaning, but strip leading and trailing whitespace.
818 $param = fix_utf8($param);
819 return trim($param);
821 case PARAM_CLEAN:
822 // General HTML cleaning, try to use more specific type if possible this is deprecated!
823 // Please use more specific type instead.
824 if (is_numeric($param)) {
825 return $param;
827 $param = fix_utf8($param);
828 // Sweep for scripts, etc.
829 return clean_text($param);
831 case PARAM_CLEANHTML:
832 // Clean html fragment.
833 $param = fix_utf8($param);
834 // Sweep for scripts, etc.
835 $param = clean_text($param, FORMAT_HTML);
836 return trim($param);
838 case PARAM_INT:
839 // Convert to integer.
840 return (int)$param;
842 case PARAM_FLOAT:
843 // Convert to float.
844 return (float)$param;
846 case PARAM_ALPHA:
847 // Remove everything not `a-z`.
848 return preg_replace('/[^a-zA-Z]/i', '', $param);
850 case PARAM_ALPHAEXT:
851 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
852 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
854 case PARAM_ALPHANUM:
855 // Remove everything not `a-zA-Z0-9`.
856 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
858 case PARAM_ALPHANUMEXT:
859 // Remove everything not `a-zA-Z0-9_-`.
860 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
862 case PARAM_SEQUENCE:
863 // Remove everything not `0-9,`.
864 return preg_replace('/[^0-9,]/i', '', $param);
866 case PARAM_BOOL:
867 // Convert to 1 or 0.
868 $tempstr = strtolower($param);
869 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
870 $param = 1;
871 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
872 $param = 0;
873 } else {
874 $param = empty($param) ? 0 : 1;
876 return $param;
878 case PARAM_NOTAGS:
879 // Strip all tags.
880 $param = fix_utf8($param);
881 return strip_tags($param);
883 case PARAM_TEXT:
884 // Leave only tags needed for multilang.
885 $param = fix_utf8($param);
886 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
887 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
888 do {
889 if (strpos($param, '</lang>') !== false) {
890 // Old and future mutilang syntax.
891 $param = strip_tags($param, '<lang>');
892 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
893 break;
895 $open = false;
896 foreach ($matches[0] as $match) {
897 if ($match === '</lang>') {
898 if ($open) {
899 $open = false;
900 continue;
901 } else {
902 break 2;
905 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
906 break 2;
907 } else {
908 $open = true;
911 if ($open) {
912 break;
914 return $param;
916 } else if (strpos($param, '</span>') !== false) {
917 // Current problematic multilang syntax.
918 $param = strip_tags($param, '<span>');
919 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
920 break;
922 $open = false;
923 foreach ($matches[0] as $match) {
924 if ($match === '</span>') {
925 if ($open) {
926 $open = false;
927 continue;
928 } else {
929 break 2;
932 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
933 break 2;
934 } else {
935 $open = true;
938 if ($open) {
939 break;
941 return $param;
943 } while (false);
944 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
945 return strip_tags($param);
947 case PARAM_COMPONENT:
948 // We do not want any guessing here, either the name is correct or not
949 // please note only normalised component names are accepted.
950 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
951 return '';
953 if (strpos($param, '__') !== false) {
954 return '';
956 if (strpos($param, 'mod_') === 0) {
957 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
958 if (substr_count($param, '_') != 1) {
959 return '';
962 return $param;
964 case PARAM_PLUGIN:
965 case PARAM_AREA:
966 // We do not want any guessing here, either the name is correct or not.
967 if (!is_valid_plugin_name($param)) {
968 return '';
970 return $param;
972 case PARAM_SAFEDIR:
973 // Remove everything not a-zA-Z0-9_- .
974 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
976 case PARAM_SAFEPATH:
977 // Remove everything not a-zA-Z0-9/_- .
978 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
980 case PARAM_FILE:
981 // Strip all suspicious characters from filename.
982 $param = fix_utf8($param);
983 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
984 if ($param === '.' || $param === '..') {
985 $param = '';
987 return $param;
989 case PARAM_PATH:
990 // Strip all suspicious characters from file path.
991 $param = fix_utf8($param);
992 $param = str_replace('\\', '/', $param);
994 // Explode the path and clean each element using the PARAM_FILE rules.
995 $breadcrumb = explode('/', $param);
996 foreach ($breadcrumb as $key => $crumb) {
997 if ($crumb === '.' && $key === 0) {
998 // Special condition to allow for relative current path such as ./currentdirfile.txt.
999 } else {
1000 $crumb = clean_param($crumb, PARAM_FILE);
1002 $breadcrumb[$key] = $crumb;
1004 $param = implode('/', $breadcrumb);
1006 // Remove multiple current path (./././) and multiple slashes (///).
1007 $param = preg_replace('~//+~', '/', $param);
1008 $param = preg_replace('~/(\./)+~', '/', $param);
1009 return $param;
1011 case PARAM_HOST:
1012 // Allow FQDN or IPv4 dotted quad.
1013 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1014 // Match ipv4 dotted quad.
1015 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1016 // Confirm values are ok.
1017 if ( $match[0] > 255
1018 || $match[1] > 255
1019 || $match[3] > 255
1020 || $match[4] > 255 ) {
1021 // Hmmm, what kind of dotted quad is this?
1022 $param = '';
1024 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1025 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1026 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1028 // All is ok - $param is respected.
1029 } else {
1030 // All is not ok...
1031 $param='';
1033 return $param;
1035 case PARAM_URL:
1036 // Allow safe urls.
1037 $param = fix_utf8($param);
1038 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1039 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1040 // All is ok, param is respected.
1041 } else {
1042 // Not really ok.
1043 $param ='';
1045 return $param;
1047 case PARAM_LOCALURL:
1048 // Allow http absolute, root relative and relative URLs within wwwroot.
1049 $param = clean_param($param, PARAM_URL);
1050 if (!empty($param)) {
1052 if ($param === $CFG->wwwroot) {
1053 // Exact match;
1054 } else if (preg_match(':^/:', $param)) {
1055 // Root-relative, ok!
1056 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1057 // Absolute, and matches our wwwroot.
1058 } else {
1059 // Relative - let's make sure there are no tricks.
1060 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1061 // Looks ok.
1062 } else {
1063 $param = '';
1067 return $param;
1069 case PARAM_PEM:
1070 $param = trim($param);
1071 // PEM formatted strings may contain letters/numbers and the symbols:
1072 // forward slash: /
1073 // plus sign: +
1074 // equal sign: =
1075 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1076 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1077 list($wholething, $body) = $matches;
1078 unset($wholething, $matches);
1079 $b64 = clean_param($body, PARAM_BASE64);
1080 if (!empty($b64)) {
1081 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1082 } else {
1083 return '';
1086 return '';
1088 case PARAM_BASE64:
1089 if (!empty($param)) {
1090 // PEM formatted strings may contain letters/numbers and the symbols
1091 // forward slash: /
1092 // plus sign: +
1093 // equal sign: =.
1094 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1095 return '';
1097 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1098 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1099 // than (or equal to) 64 characters long.
1100 for ($i=0, $j=count($lines); $i < $j; $i++) {
1101 if ($i + 1 == $j) {
1102 if (64 < strlen($lines[$i])) {
1103 return '';
1105 continue;
1108 if (64 != strlen($lines[$i])) {
1109 return '';
1112 return implode("\n", $lines);
1113 } else {
1114 return '';
1117 case PARAM_TAG:
1118 $param = fix_utf8($param);
1119 // Please note it is not safe to use the tag name directly anywhere,
1120 // it must be processed with s(), urlencode() before embedding anywhere.
1121 // Remove some nasties.
1122 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1123 // Convert many whitespace chars into one.
1124 $param = preg_replace('/\s+/u', ' ', $param);
1125 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1126 return $param;
1128 case PARAM_TAGLIST:
1129 $param = fix_utf8($param);
1130 $tags = explode(',', $param);
1131 $result = array();
1132 foreach ($tags as $tag) {
1133 $res = clean_param($tag, PARAM_TAG);
1134 if ($res !== '') {
1135 $result[] = $res;
1138 if ($result) {
1139 return implode(',', $result);
1140 } else {
1141 return '';
1144 case PARAM_CAPABILITY:
1145 if (get_capability_info($param)) {
1146 return $param;
1147 } else {
1148 return '';
1151 case PARAM_PERMISSION:
1152 $param = (int)$param;
1153 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1154 return $param;
1155 } else {
1156 return CAP_INHERIT;
1159 case PARAM_AUTH:
1160 $param = clean_param($param, PARAM_PLUGIN);
1161 if (empty($param)) {
1162 return '';
1163 } else if (exists_auth_plugin($param)) {
1164 return $param;
1165 } else {
1166 return '';
1169 case PARAM_LANG:
1170 $param = clean_param($param, PARAM_SAFEDIR);
1171 if (get_string_manager()->translation_exists($param)) {
1172 return $param;
1173 } else {
1174 // Specified language is not installed or param malformed.
1175 return '';
1178 case PARAM_THEME:
1179 $param = clean_param($param, PARAM_PLUGIN);
1180 if (empty($param)) {
1181 return '';
1182 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1183 return $param;
1184 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1185 return $param;
1186 } else {
1187 // Specified theme is not installed.
1188 return '';
1191 case PARAM_USERNAME:
1192 $param = fix_utf8($param);
1193 $param = trim($param);
1194 // Convert uppercase to lowercase MDL-16919.
1195 $param = core_text::strtolower($param);
1196 if (empty($CFG->extendedusernamechars)) {
1197 $param = str_replace(" " , "", $param);
1198 // Regular expression, eliminate all chars EXCEPT:
1199 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1200 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1202 return $param;
1204 case PARAM_EMAIL:
1205 $param = fix_utf8($param);
1206 if (validate_email($param)) {
1207 return $param;
1208 } else {
1209 return '';
1212 case PARAM_STRINGID:
1213 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1214 return $param;
1215 } else {
1216 return '';
1219 case PARAM_TIMEZONE:
1220 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1221 $param = fix_utf8($param);
1222 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1223 if (preg_match($timezonepattern, $param)) {
1224 return $param;
1225 } else {
1226 return '';
1229 default:
1230 // Doh! throw error, switched parameters in optional_param or another serious problem.
1231 print_error("unknownparamtype", '', '', $type);
1236 * Whether the PARAM_* type is compatible in RTL.
1238 * Being compatible with RTL means that the data they contain can flow
1239 * from right-to-left or left-to-right without compromising the user experience.
1241 * Take URLs for example, they are not RTL compatible as they should always
1242 * flow from the left to the right. This also applies to numbers, email addresses,
1243 * configuration snippets, base64 strings, etc...
1245 * This function tries to best guess which parameters can contain localised strings.
1247 * @param string $paramtype Constant PARAM_*.
1248 * @return bool
1250 function is_rtl_compatible($paramtype) {
1251 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1255 * Makes sure the data is using valid utf8, invalid characters are discarded.
1257 * Note: this function is not intended for full objects with methods and private properties.
1259 * @param mixed $value
1260 * @return mixed with proper utf-8 encoding
1262 function fix_utf8($value) {
1263 if (is_null($value) or $value === '') {
1264 return $value;
1266 } else if (is_string($value)) {
1267 if ((string)(int)$value === $value) {
1268 // Shortcut.
1269 return $value;
1271 // No null bytes expected in our data, so let's remove it.
1272 $value = str_replace("\0", '', $value);
1274 // Note: this duplicates min_fix_utf8() intentionally.
1275 static $buggyiconv = null;
1276 if ($buggyiconv === null) {
1277 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1280 if ($buggyiconv) {
1281 if (function_exists('mb_convert_encoding')) {
1282 $subst = mb_substitute_character();
1283 mb_substitute_character('');
1284 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1285 mb_substitute_character($subst);
1287 } else {
1288 // Warn admins on admin/index.php page.
1289 $result = $value;
1292 } else {
1293 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1296 return $result;
1298 } else if (is_array($value)) {
1299 foreach ($value as $k => $v) {
1300 $value[$k] = fix_utf8($v);
1302 return $value;
1304 } else if (is_object($value)) {
1305 // Do not modify original.
1306 $value = clone($value);
1307 foreach ($value as $k => $v) {
1308 $value->$k = fix_utf8($v);
1310 return $value;
1312 } else {
1313 // This is some other type, no utf-8 here.
1314 return $value;
1319 * Return true if given value is integer or string with integer value
1321 * @param mixed $value String or Int
1322 * @return bool true if number, false if not
1324 function is_number($value) {
1325 if (is_int($value)) {
1326 return true;
1327 } else if (is_string($value)) {
1328 return ((string)(int)$value) === $value;
1329 } else {
1330 return false;
1335 * Returns host part from url.
1337 * @param string $url full url
1338 * @return string host, null if not found
1340 function get_host_from_url($url) {
1341 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1342 if ($matches) {
1343 return $matches[1];
1345 return null;
1349 * Tests whether anything was returned by text editor
1351 * This function is useful for testing whether something you got back from
1352 * the HTML editor actually contains anything. Sometimes the HTML editor
1353 * appear to be empty, but actually you get back a <br> tag or something.
1355 * @param string $string a string containing HTML.
1356 * @return boolean does the string contain any actual content - that is text,
1357 * images, objects, etc.
1359 function html_is_blank($string) {
1360 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1364 * Set a key in global configuration
1366 * Set a key/value pair in both this session's {@link $CFG} global variable
1367 * and in the 'config' database table for future sessions.
1369 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1370 * In that case it doesn't affect $CFG.
1372 * A NULL value will delete the entry.
1374 * NOTE: this function is called from lib/db/upgrade.php
1376 * @param string $name the key to set
1377 * @param string $value the value to set (without magic quotes)
1378 * @param string $plugin (optional) the plugin scope, default null
1379 * @return bool true or exception
1381 function set_config($name, $value, $plugin=null) {
1382 global $CFG, $DB;
1384 if (empty($plugin)) {
1385 if (!array_key_exists($name, $CFG->config_php_settings)) {
1386 // So it's defined for this invocation at least.
1387 if (is_null($value)) {
1388 unset($CFG->$name);
1389 } else {
1390 // Settings from db are always strings.
1391 $CFG->$name = (string)$value;
1395 if ($DB->get_field('config', 'name', array('name' => $name))) {
1396 if ($value === null) {
1397 $DB->delete_records('config', array('name' => $name));
1398 } else {
1399 $DB->set_field('config', 'value', $value, array('name' => $name));
1401 } else {
1402 if ($value !== null) {
1403 $config = new stdClass();
1404 $config->name = $name;
1405 $config->value = $value;
1406 $DB->insert_record('config', $config, false);
1409 if ($name === 'siteidentifier') {
1410 cache_helper::update_site_identifier($value);
1412 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1413 } else {
1414 // Plugin scope.
1415 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1416 if ($value===null) {
1417 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1418 } else {
1419 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1421 } else {
1422 if ($value !== null) {
1423 $config = new stdClass();
1424 $config->plugin = $plugin;
1425 $config->name = $name;
1426 $config->value = $value;
1427 $DB->insert_record('config_plugins', $config, false);
1430 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1433 return true;
1437 * Get configuration values from the global config table
1438 * or the config_plugins table.
1440 * If called with one parameter, it will load all the config
1441 * variables for one plugin, and return them as an object.
1443 * If called with 2 parameters it will return a string single
1444 * value or false if the value is not found.
1446 * NOTE: this function is called from lib/db/upgrade.php
1448 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1449 * that we need only fetch it once per request.
1450 * @param string $plugin full component name
1451 * @param string $name default null
1452 * @return mixed hash-like object or single value, return false no config found
1453 * @throws dml_exception
1455 function get_config($plugin, $name = null) {
1456 global $CFG, $DB;
1458 static $siteidentifier = null;
1460 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1461 $forced =& $CFG->config_php_settings;
1462 $iscore = true;
1463 $plugin = 'core';
1464 } else {
1465 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1466 $forced =& $CFG->forced_plugin_settings[$plugin];
1467 } else {
1468 $forced = array();
1470 $iscore = false;
1473 if ($siteidentifier === null) {
1474 try {
1475 // This may fail during installation.
1476 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1477 // install the database.
1478 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1479 } catch (dml_exception $ex) {
1480 // Set siteidentifier to false. We don't want to trip this continually.
1481 $siteidentifier = false;
1482 throw $ex;
1486 if (!empty($name)) {
1487 if (array_key_exists($name, $forced)) {
1488 return (string)$forced[$name];
1489 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1490 return $siteidentifier;
1494 $cache = cache::make('core', 'config');
1495 $result = $cache->get($plugin);
1496 if ($result === false) {
1497 // The user is after a recordset.
1498 if (!$iscore) {
1499 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1500 } else {
1501 // This part is not really used any more, but anyway...
1502 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1504 $cache->set($plugin, $result);
1507 if (!empty($name)) {
1508 if (array_key_exists($name, $result)) {
1509 return $result[$name];
1511 return false;
1514 if ($plugin === 'core') {
1515 $result['siteidentifier'] = $siteidentifier;
1518 foreach ($forced as $key => $value) {
1519 if (is_null($value) or is_array($value) or is_object($value)) {
1520 // We do not want any extra mess here, just real settings that could be saved in db.
1521 unset($result[$key]);
1522 } else {
1523 // Convert to string as if it went through the DB.
1524 $result[$key] = (string)$value;
1528 return (object)$result;
1532 * Removes a key from global configuration.
1534 * NOTE: this function is called from lib/db/upgrade.php
1536 * @param string $name the key to set
1537 * @param string $plugin (optional) the plugin scope
1538 * @return boolean whether the operation succeeded.
1540 function unset_config($name, $plugin=null) {
1541 global $CFG, $DB;
1543 if (empty($plugin)) {
1544 unset($CFG->$name);
1545 $DB->delete_records('config', array('name' => $name));
1546 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1547 } else {
1548 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1549 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1552 return true;
1556 * Remove all the config variables for a given plugin.
1558 * NOTE: this function is called from lib/db/upgrade.php
1560 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1561 * @return boolean whether the operation succeeded.
1563 function unset_all_config_for_plugin($plugin) {
1564 global $DB;
1565 // Delete from the obvious config_plugins first.
1566 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1567 // Next delete any suspect settings from config.
1568 $like = $DB->sql_like('name', '?', true, true, false, '|');
1569 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1570 $DB->delete_records_select('config', $like, $params);
1571 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1572 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1574 return true;
1578 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1580 * All users are verified if they still have the necessary capability.
1582 * @param string $value the value of the config setting.
1583 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1584 * @param bool $includeadmins include administrators.
1585 * @return array of user objects.
1587 function get_users_from_config($value, $capability, $includeadmins = true) {
1588 if (empty($value) or $value === '$@NONE@$') {
1589 return array();
1592 // We have to make sure that users still have the necessary capability,
1593 // it should be faster to fetch them all first and then test if they are present
1594 // instead of validating them one-by-one.
1595 $users = get_users_by_capability(context_system::instance(), $capability);
1596 if ($includeadmins) {
1597 $admins = get_admins();
1598 foreach ($admins as $admin) {
1599 $users[$admin->id] = $admin;
1603 if ($value === '$@ALL@$') {
1604 return $users;
1607 $result = array(); // Result in correct order.
1608 $allowed = explode(',', $value);
1609 foreach ($allowed as $uid) {
1610 if (isset($users[$uid])) {
1611 $user = $users[$uid];
1612 $result[$user->id] = $user;
1616 return $result;
1621 * Invalidates browser caches and cached data in temp.
1623 * @return void
1625 function purge_all_caches() {
1626 purge_caches();
1630 * Selectively invalidate different types of cache.
1632 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1633 * areas alone or in combination.
1635 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1636 * 'muc' Purge MUC caches?
1637 * 'theme' Purge theme cache?
1638 * 'lang' Purge language string cache?
1639 * 'js' Purge javascript cache?
1640 * 'filter' Purge text filter cache?
1641 * 'other' Purge all other caches?
1643 function purge_caches($options = []) {
1644 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'filter', 'other'], false);
1645 if (empty(array_filter($options))) {
1646 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1647 } else {
1648 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1650 if ($options['muc']) {
1651 cache_helper::purge_all();
1653 if ($options['theme']) {
1654 theme_reset_all_caches();
1656 if ($options['lang']) {
1657 get_string_manager()->reset_caches();
1659 if ($options['js']) {
1660 js_reset_all_caches();
1662 if ($options['filter']) {
1663 reset_text_filters_cache();
1665 if ($options['other']) {
1666 purge_other_caches();
1671 * Purge all non-MUC caches not otherwise purged in purge_caches.
1673 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1674 * {@link phpunit_util::reset_dataroot()}
1676 function purge_other_caches() {
1677 global $DB, $CFG;
1678 core_text::reset_caches();
1679 if (class_exists('core_plugin_manager')) {
1680 core_plugin_manager::reset_caches();
1683 // Bump up cacherev field for all courses.
1684 try {
1685 increment_revision_number('course', 'cacherev', '');
1686 } catch (moodle_exception $e) {
1687 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1690 $DB->reset_caches();
1692 // Purge all other caches: rss, simplepie, etc.
1693 clearstatcache();
1694 remove_dir($CFG->cachedir.'', true);
1696 // Make sure cache dir is writable, throws exception if not.
1697 make_cache_directory('');
1699 // This is the only place where we purge local caches, we are only adding files there.
1700 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1701 remove_dir($CFG->localcachedir, true);
1702 set_config('localcachedirpurged', time());
1703 make_localcache_directory('', true);
1704 \core\task\manager::clear_static_caches();
1708 * Get volatile flags
1710 * @param string $type
1711 * @param int $changedsince default null
1712 * @return array records array
1714 function get_cache_flags($type, $changedsince = null) {
1715 global $DB;
1717 $params = array('type' => $type, 'expiry' => time());
1718 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1719 if ($changedsince !== null) {
1720 $params['changedsince'] = $changedsince;
1721 $sqlwhere .= " AND timemodified > :changedsince";
1723 $cf = array();
1724 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1725 foreach ($flags as $flag) {
1726 $cf[$flag->name] = $flag->value;
1729 return $cf;
1733 * Get volatile flags
1735 * @param string $type
1736 * @param string $name
1737 * @param int $changedsince default null
1738 * @return string|false The cache flag value or false
1740 function get_cache_flag($type, $name, $changedsince=null) {
1741 global $DB;
1743 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1745 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1746 if ($changedsince !== null) {
1747 $params['changedsince'] = $changedsince;
1748 $sqlwhere .= " AND timemodified > :changedsince";
1751 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1755 * Set a volatile flag
1757 * @param string $type the "type" namespace for the key
1758 * @param string $name the key to set
1759 * @param string $value the value to set (without magic quotes) - null will remove the flag
1760 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1761 * @return bool Always returns true
1763 function set_cache_flag($type, $name, $value, $expiry = null) {
1764 global $DB;
1766 $timemodified = time();
1767 if ($expiry === null || $expiry < $timemodified) {
1768 $expiry = $timemodified + 24 * 60 * 60;
1769 } else {
1770 $expiry = (int)$expiry;
1773 if ($value === null) {
1774 unset_cache_flag($type, $name);
1775 return true;
1778 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1779 // This is a potential problem in DEBUG_DEVELOPER.
1780 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1781 return true; // No need to update.
1783 $f->value = $value;
1784 $f->expiry = $expiry;
1785 $f->timemodified = $timemodified;
1786 $DB->update_record('cache_flags', $f);
1787 } else {
1788 $f = new stdClass();
1789 $f->flagtype = $type;
1790 $f->name = $name;
1791 $f->value = $value;
1792 $f->expiry = $expiry;
1793 $f->timemodified = $timemodified;
1794 $DB->insert_record('cache_flags', $f);
1796 return true;
1800 * Removes a single volatile flag
1802 * @param string $type the "type" namespace for the key
1803 * @param string $name the key to set
1804 * @return bool
1806 function unset_cache_flag($type, $name) {
1807 global $DB;
1808 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1809 return true;
1813 * Garbage-collect volatile flags
1815 * @return bool Always returns true
1817 function gc_cache_flags() {
1818 global $DB;
1819 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1820 return true;
1823 // USER PREFERENCE API.
1826 * Refresh user preference cache. This is used most often for $USER
1827 * object that is stored in session, but it also helps with performance in cron script.
1829 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1831 * @package core
1832 * @category preference
1833 * @access public
1834 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1835 * @param int $cachelifetime Cache life time on the current page (in seconds)
1836 * @throws coding_exception
1837 * @return null
1839 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1840 global $DB;
1841 // Static cache, we need to check on each page load, not only every 2 minutes.
1842 static $loadedusers = array();
1844 if (!isset($user->id)) {
1845 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1848 if (empty($user->id) or isguestuser($user->id)) {
1849 // No permanent storage for not-logged-in users and guest.
1850 if (!isset($user->preference)) {
1851 $user->preference = array();
1853 return;
1856 $timenow = time();
1858 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1859 // Already loaded at least once on this page. Are we up to date?
1860 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1861 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1862 return;
1864 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1865 // No change since the lastcheck on this page.
1866 $user->preference['_lastloaded'] = $timenow;
1867 return;
1871 // OK, so we have to reload all preferences.
1872 $loadedusers[$user->id] = true;
1873 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1874 $user->preference['_lastloaded'] = $timenow;
1878 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1880 * NOTE: internal function, do not call from other code.
1882 * @package core
1883 * @access private
1884 * @param integer $userid the user whose prefs were changed.
1886 function mark_user_preferences_changed($userid) {
1887 global $CFG;
1889 if (empty($userid) or isguestuser($userid)) {
1890 // No cache flags for guest and not-logged-in users.
1891 return;
1894 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1898 * Sets a preference for the specified user.
1900 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1902 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1904 * @package core
1905 * @category preference
1906 * @access public
1907 * @param string $name The key to set as preference for the specified user
1908 * @param string $value The value to set for the $name key in the specified user's
1909 * record, null means delete current value.
1910 * @param stdClass|int|null $user A moodle user object or id, null means current user
1911 * @throws coding_exception
1912 * @return bool Always true or exception
1914 function set_user_preference($name, $value, $user = null) {
1915 global $USER, $DB;
1917 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1918 throw new coding_exception('Invalid preference name in set_user_preference() call');
1921 if (is_null($value)) {
1922 // Null means delete current.
1923 return unset_user_preference($name, $user);
1924 } else if (is_object($value)) {
1925 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1926 } else if (is_array($value)) {
1927 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1929 // Value column maximum length is 1333 characters.
1930 $value = (string)$value;
1931 if (core_text::strlen($value) > 1333) {
1932 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1935 if (is_null($user)) {
1936 $user = $USER;
1937 } else if (isset($user->id)) {
1938 // It is a valid object.
1939 } else if (is_numeric($user)) {
1940 $user = (object)array('id' => (int)$user);
1941 } else {
1942 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1945 check_user_preferences_loaded($user);
1947 if (empty($user->id) or isguestuser($user->id)) {
1948 // No permanent storage for not-logged-in users and guest.
1949 $user->preference[$name] = $value;
1950 return true;
1953 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1954 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1955 // Preference already set to this value.
1956 return true;
1958 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1960 } else {
1961 $preference = new stdClass();
1962 $preference->userid = $user->id;
1963 $preference->name = $name;
1964 $preference->value = $value;
1965 $DB->insert_record('user_preferences', $preference);
1968 // Update value in cache.
1969 $user->preference[$name] = $value;
1970 // Update the $USER in case where we've not a direct reference to $USER.
1971 if ($user !== $USER && $user->id == $USER->id) {
1972 $USER->preference[$name] = $value;
1975 // Set reload flag for other sessions.
1976 mark_user_preferences_changed($user->id);
1978 return true;
1982 * Sets a whole array of preferences for the current user
1984 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1986 * @package core
1987 * @category preference
1988 * @access public
1989 * @param array $prefarray An array of key/value pairs to be set
1990 * @param stdClass|int|null $user A moodle user object or id, null means current user
1991 * @return bool Always true or exception
1993 function set_user_preferences(array $prefarray, $user = null) {
1994 foreach ($prefarray as $name => $value) {
1995 set_user_preference($name, $value, $user);
1997 return true;
2001 * Unsets a preference completely by deleting it from the database
2003 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2005 * @package core
2006 * @category preference
2007 * @access public
2008 * @param string $name The key to unset as preference for the specified user
2009 * @param stdClass|int|null $user A moodle user object or id, null means current user
2010 * @throws coding_exception
2011 * @return bool Always true or exception
2013 function unset_user_preference($name, $user = null) {
2014 global $USER, $DB;
2016 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2017 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2020 if (is_null($user)) {
2021 $user = $USER;
2022 } else if (isset($user->id)) {
2023 // It is a valid object.
2024 } else if (is_numeric($user)) {
2025 $user = (object)array('id' => (int)$user);
2026 } else {
2027 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2030 check_user_preferences_loaded($user);
2032 if (empty($user->id) or isguestuser($user->id)) {
2033 // No permanent storage for not-logged-in user and guest.
2034 unset($user->preference[$name]);
2035 return true;
2038 // Delete from DB.
2039 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2041 // Delete the preference from cache.
2042 unset($user->preference[$name]);
2043 // Update the $USER in case where we've not a direct reference to $USER.
2044 if ($user !== $USER && $user->id == $USER->id) {
2045 unset($USER->preference[$name]);
2048 // Set reload flag for other sessions.
2049 mark_user_preferences_changed($user->id);
2051 return true;
2055 * Used to fetch user preference(s)
2057 * If no arguments are supplied this function will return
2058 * all of the current user preferences as an array.
2060 * If a name is specified then this function
2061 * attempts to return that particular preference value. If
2062 * none is found, then the optional value $default is returned,
2063 * otherwise null.
2065 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2067 * @package core
2068 * @category preference
2069 * @access public
2070 * @param string $name Name of the key to use in finding a preference value
2071 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2072 * @param stdClass|int|null $user A moodle user object or id, null means current user
2073 * @throws coding_exception
2074 * @return string|mixed|null A string containing the value of a single preference. An
2075 * array with all of the preferences or null
2077 function get_user_preferences($name = null, $default = null, $user = null) {
2078 global $USER;
2080 if (is_null($name)) {
2081 // All prefs.
2082 } else if (is_numeric($name) or $name === '_lastloaded') {
2083 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2086 if (is_null($user)) {
2087 $user = $USER;
2088 } else if (isset($user->id)) {
2089 // Is a valid object.
2090 } else if (is_numeric($user)) {
2091 if ($USER->id == $user) {
2092 $user = $USER;
2093 } else {
2094 $user = (object)array('id' => (int)$user);
2096 } else {
2097 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2100 check_user_preferences_loaded($user);
2102 if (empty($name)) {
2103 // All values.
2104 return $user->preference;
2105 } else if (isset($user->preference[$name])) {
2106 // The single string value.
2107 return $user->preference[$name];
2108 } else {
2109 // Default value (null if not specified).
2110 return $default;
2114 // FUNCTIONS FOR HANDLING TIME.
2117 * Given Gregorian date parts in user time produce a GMT timestamp.
2119 * @package core
2120 * @category time
2121 * @param int $year The year part to create timestamp of
2122 * @param int $month The month part to create timestamp of
2123 * @param int $day The day part to create timestamp of
2124 * @param int $hour The hour part to create timestamp of
2125 * @param int $minute The minute part to create timestamp of
2126 * @param int $second The second part to create timestamp of
2127 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2128 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2129 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2130 * applied only if timezone is 99 or string.
2131 * @return int GMT timestamp
2133 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2134 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2135 $date->setDate((int)$year, (int)$month, (int)$day);
2136 $date->setTime((int)$hour, (int)$minute, (int)$second);
2138 $time = $date->getTimestamp();
2140 if ($time === false) {
2141 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2142 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2145 // Moodle BC DST stuff.
2146 if (!$applydst) {
2147 $time += dst_offset_on($time, $timezone);
2150 return $time;
2155 * Format a date/time (seconds) as weeks, days, hours etc as needed
2157 * Given an amount of time in seconds, returns string
2158 * formatted nicely as years, days, hours etc as needed
2160 * @package core
2161 * @category time
2162 * @uses MINSECS
2163 * @uses HOURSECS
2164 * @uses DAYSECS
2165 * @uses YEARSECS
2166 * @param int $totalsecs Time in seconds
2167 * @param stdClass $str Should be a time object
2168 * @return string A nicely formatted date/time string
2170 function format_time($totalsecs, $str = null) {
2172 $totalsecs = abs($totalsecs);
2174 if (!$str) {
2175 // Create the str structure the slow way.
2176 $str = new stdClass();
2177 $str->day = get_string('day');
2178 $str->days = get_string('days');
2179 $str->hour = get_string('hour');
2180 $str->hours = get_string('hours');
2181 $str->min = get_string('min');
2182 $str->mins = get_string('mins');
2183 $str->sec = get_string('sec');
2184 $str->secs = get_string('secs');
2185 $str->year = get_string('year');
2186 $str->years = get_string('years');
2189 $years = floor($totalsecs/YEARSECS);
2190 $remainder = $totalsecs - ($years*YEARSECS);
2191 $days = floor($remainder/DAYSECS);
2192 $remainder = $totalsecs - ($days*DAYSECS);
2193 $hours = floor($remainder/HOURSECS);
2194 $remainder = $remainder - ($hours*HOURSECS);
2195 $mins = floor($remainder/MINSECS);
2196 $secs = $remainder - ($mins*MINSECS);
2198 $ss = ($secs == 1) ? $str->sec : $str->secs;
2199 $sm = ($mins == 1) ? $str->min : $str->mins;
2200 $sh = ($hours == 1) ? $str->hour : $str->hours;
2201 $sd = ($days == 1) ? $str->day : $str->days;
2202 $sy = ($years == 1) ? $str->year : $str->years;
2204 $oyears = '';
2205 $odays = '';
2206 $ohours = '';
2207 $omins = '';
2208 $osecs = '';
2210 if ($years) {
2211 $oyears = $years .' '. $sy;
2213 if ($days) {
2214 $odays = $days .' '. $sd;
2216 if ($hours) {
2217 $ohours = $hours .' '. $sh;
2219 if ($mins) {
2220 $omins = $mins .' '. $sm;
2222 if ($secs) {
2223 $osecs = $secs .' '. $ss;
2226 if ($years) {
2227 return trim($oyears .' '. $odays);
2229 if ($days) {
2230 return trim($odays .' '. $ohours);
2232 if ($hours) {
2233 return trim($ohours .' '. $omins);
2235 if ($mins) {
2236 return trim($omins .' '. $osecs);
2238 if ($secs) {
2239 return $osecs;
2241 return get_string('now');
2245 * Returns a formatted string that represents a date in user time.
2247 * @package core
2248 * @category time
2249 * @param int $date the timestamp in UTC, as obtained from the database.
2250 * @param string $format strftime format. You should probably get this using
2251 * get_string('strftime...', 'langconfig');
2252 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2253 * not 99 then daylight saving will not be added.
2254 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2255 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2256 * If false then the leading zero is maintained.
2257 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2258 * @return string the formatted date/time.
2260 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2261 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2262 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2266 * Returns a html "time" tag with both the exact user date with timezone information
2267 * as a datetime attribute in the W3C format, and the user readable date and time as text.
2269 * @package core
2270 * @category time
2271 * @param int $date the timestamp in UTC, as obtained from the database.
2272 * @param string $format strftime format. You should probably get this using
2273 * get_string('strftime...', 'langconfig');
2274 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2275 * not 99 then daylight saving will not be added.
2276 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2277 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2278 * If false then the leading zero is maintained.
2279 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2280 * @return string the formatted date/time.
2282 function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2283 $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2284 if (CLI_SCRIPT && !PHPUNIT_TEST) {
2285 return $userdatestr;
2287 $machinedate = new DateTime();
2288 $machinedate->setTimestamp(intval($date));
2289 $machinedate->setTimezone(core_date::get_user_timezone_object());
2291 return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2295 * Returns a formatted date ensuring it is UTF-8.
2297 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2298 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2300 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2301 * @param string $format strftime format.
2302 * @param int|float|string $tz the user timezone
2303 * @return string the formatted date/time.
2304 * @since Moodle 2.3.3
2306 function date_format_string($date, $format, $tz = 99) {
2307 global $CFG;
2309 $localewincharset = null;
2310 // Get the calendar type user is using.
2311 if ($CFG->ostype == 'WINDOWS') {
2312 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2313 $localewincharset = $calendartype->locale_win_charset();
2316 if ($localewincharset) {
2317 $format = core_text::convert($format, 'utf-8', $localewincharset);
2320 date_default_timezone_set(core_date::get_user_timezone($tz));
2321 $datestring = strftime($format, $date);
2322 core_date::set_default_server_timezone();
2324 if ($localewincharset) {
2325 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2328 return $datestring;
2332 * Given a $time timestamp in GMT (seconds since epoch),
2333 * returns an array that represents the Gregorian date in user time
2335 * @package core
2336 * @category time
2337 * @param int $time Timestamp in GMT
2338 * @param float|int|string $timezone user timezone
2339 * @return array An array that represents the date in user time
2341 function usergetdate($time, $timezone=99) {
2342 date_default_timezone_set(core_date::get_user_timezone($timezone));
2343 $result = getdate($time);
2344 core_date::set_default_server_timezone();
2346 return $result;
2350 * Given a GMT timestamp (seconds since epoch), offsets it by
2351 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2353 * NOTE: this function does not include DST properly,
2354 * you should use the PHP date stuff instead!
2356 * @package core
2357 * @category time
2358 * @param int $date Timestamp in GMT
2359 * @param float|int|string $timezone user timezone
2360 * @return int
2362 function usertime($date, $timezone=99) {
2363 $userdate = new DateTime('@' . $date);
2364 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2365 $dst = dst_offset_on($date, $timezone);
2367 return $date - $userdate->getOffset() + $dst;
2371 * Given a time, return the GMT timestamp of the most recent midnight
2372 * for the current user.
2374 * @package core
2375 * @category time
2376 * @param int $date Timestamp in GMT
2377 * @param float|int|string $timezone user timezone
2378 * @return int Returns a GMT timestamp
2380 function usergetmidnight($date, $timezone=99) {
2382 $userdate = usergetdate($date, $timezone);
2384 // Time of midnight of this user's day, in GMT.
2385 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2390 * Returns a string that prints the user's timezone
2392 * @package core
2393 * @category time
2394 * @param float|int|string $timezone user timezone
2395 * @return string
2397 function usertimezone($timezone=99) {
2398 $tz = core_date::get_user_timezone($timezone);
2399 return core_date::get_localised_timezone($tz);
2403 * Returns a float or a string which denotes the user's timezone
2404 * 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)
2405 * means that for this timezone there are also DST rules to be taken into account
2406 * Checks various settings and picks the most dominant of those which have a value
2408 * @package core
2409 * @category time
2410 * @param float|int|string $tz timezone to calculate GMT time offset before
2411 * calculating user timezone, 99 is default user timezone
2412 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2413 * @return float|string
2415 function get_user_timezone($tz = 99) {
2416 global $USER, $CFG;
2418 $timezones = array(
2419 $tz,
2420 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2421 isset($USER->timezone) ? $USER->timezone : 99,
2422 isset($CFG->timezone) ? $CFG->timezone : 99,
2425 $tz = 99;
2427 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2428 foreach ($timezones as $nextvalue) {
2429 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2430 $tz = $nextvalue;
2433 return is_numeric($tz) ? (float) $tz : $tz;
2437 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2438 * - Note: Daylight saving only works for string timezones and not for float.
2440 * @package core
2441 * @category time
2442 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2443 * @param int|float|string $strtimezone user timezone
2444 * @return int
2446 function dst_offset_on($time, $strtimezone = null) {
2447 $tz = core_date::get_user_timezone($strtimezone);
2448 $date = new DateTime('@' . $time);
2449 $date->setTimezone(new DateTimeZone($tz));
2450 if ($date->format('I') == '1') {
2451 if ($tz === 'Australia/Lord_Howe') {
2452 return 1800;
2454 return 3600;
2456 return 0;
2460 * Calculates when the day appears in specific month
2462 * @package core
2463 * @category time
2464 * @param int $startday starting day of the month
2465 * @param int $weekday The day when week starts (normally taken from user preferences)
2466 * @param int $month The month whose day is sought
2467 * @param int $year The year of the month whose day is sought
2468 * @return int
2470 function find_day_in_month($startday, $weekday, $month, $year) {
2471 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2473 $daysinmonth = days_in_month($month, $year);
2474 $daysinweek = count($calendartype->get_weekdays());
2476 if ($weekday == -1) {
2477 // Don't care about weekday, so return:
2478 // abs($startday) if $startday != -1
2479 // $daysinmonth otherwise.
2480 return ($startday == -1) ? $daysinmonth : abs($startday);
2483 // From now on we 're looking for a specific weekday.
2484 // Give "end of month" its actual value, since we know it.
2485 if ($startday == -1) {
2486 $startday = -1 * $daysinmonth;
2489 // Starting from day $startday, the sign is the direction.
2490 if ($startday < 1) {
2491 $startday = abs($startday);
2492 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2494 // This is the last such weekday of the month.
2495 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2496 if ($lastinmonth > $daysinmonth) {
2497 $lastinmonth -= $daysinweek;
2500 // Find the first such weekday <= $startday.
2501 while ($lastinmonth > $startday) {
2502 $lastinmonth -= $daysinweek;
2505 return $lastinmonth;
2506 } else {
2507 $indexweekday = dayofweek($startday, $month, $year);
2509 $diff = $weekday - $indexweekday;
2510 if ($diff < 0) {
2511 $diff += $daysinweek;
2514 // This is the first such weekday of the month equal to or after $startday.
2515 $firstfromindex = $startday + $diff;
2517 return $firstfromindex;
2522 * Calculate the number of days in a given month
2524 * @package core
2525 * @category time
2526 * @param int $month The month whose day count is sought
2527 * @param int $year The year of the month whose day count is sought
2528 * @return int
2530 function days_in_month($month, $year) {
2531 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2532 return $calendartype->get_num_days_in_month($year, $month);
2536 * Calculate the position in the week of a specific calendar day
2538 * @package core
2539 * @category time
2540 * @param int $day The day of the date whose position in the week is sought
2541 * @param int $month The month of the date whose position in the week is sought
2542 * @param int $year The year of the date whose position in the week is sought
2543 * @return int
2545 function dayofweek($day, $month, $year) {
2546 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2547 return $calendartype->get_weekday($year, $month, $day);
2550 // USER AUTHENTICATION AND LOGIN.
2553 * Returns full login url.
2555 * Any form submissions for authentication to this URL must include username,
2556 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2558 * @return string login url
2560 function get_login_url() {
2561 global $CFG;
2563 return "$CFG->wwwroot/login/index.php";
2567 * This function checks that the current user is logged in and has the
2568 * required privileges
2570 * This function checks that the current user is logged in, and optionally
2571 * whether they are allowed to be in a particular course and view a particular
2572 * course module.
2573 * If they are not logged in, then it redirects them to the site login unless
2574 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2575 * case they are automatically logged in as guests.
2576 * If $courseid is given and the user is not enrolled in that course then the
2577 * user is redirected to the course enrolment page.
2578 * If $cm is given and the course module is hidden and the user is not a teacher
2579 * in the course then the user is redirected to the course home page.
2581 * When $cm parameter specified, this function sets page layout to 'module'.
2582 * You need to change it manually later if some other layout needed.
2584 * @package core_access
2585 * @category access
2587 * @param mixed $courseorid id of the course or course object
2588 * @param bool $autologinguest default true
2589 * @param object $cm course module object
2590 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2591 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2592 * in order to keep redirects working properly. MDL-14495
2593 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2594 * @return mixed Void, exit, and die depending on path
2595 * @throws coding_exception
2596 * @throws require_login_exception
2597 * @throws moodle_exception
2599 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2600 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2602 // Must not redirect when byteserving already started.
2603 if (!empty($_SERVER['HTTP_RANGE'])) {
2604 $preventredirect = true;
2607 if (AJAX_SCRIPT) {
2608 // We cannot redirect for AJAX scripts either.
2609 $preventredirect = true;
2612 // Setup global $COURSE, themes, language and locale.
2613 if (!empty($courseorid)) {
2614 if (is_object($courseorid)) {
2615 $course = $courseorid;
2616 } else if ($courseorid == SITEID) {
2617 $course = clone($SITE);
2618 } else {
2619 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2621 if ($cm) {
2622 if ($cm->course != $course->id) {
2623 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2625 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2626 if (!($cm instanceof cm_info)) {
2627 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2628 // db queries so this is not really a performance concern, however it is obviously
2629 // better if you use get_fast_modinfo to get the cm before calling this.
2630 $modinfo = get_fast_modinfo($course);
2631 $cm = $modinfo->get_cm($cm->id);
2634 } else {
2635 // Do not touch global $COURSE via $PAGE->set_course(),
2636 // the reasons is we need to be able to call require_login() at any time!!
2637 $course = $SITE;
2638 if ($cm) {
2639 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2643 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2644 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2645 // risk leading the user back to the AJAX request URL.
2646 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2647 $setwantsurltome = false;
2650 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2651 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2652 if ($preventredirect) {
2653 throw new require_login_session_timeout_exception();
2654 } else {
2655 if ($setwantsurltome) {
2656 $SESSION->wantsurl = qualified_me();
2658 redirect(get_login_url());
2662 // If the user is not even logged in yet then make sure they are.
2663 if (!isloggedin()) {
2664 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2665 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2666 // Misconfigured site guest, just redirect to login page.
2667 redirect(get_login_url());
2668 exit; // Never reached.
2670 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2671 complete_user_login($guest);
2672 $USER->autologinguest = true;
2673 $SESSION->lang = $lang;
2674 } else {
2675 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2676 if ($preventredirect) {
2677 throw new require_login_exception('You are not logged in');
2680 if ($setwantsurltome) {
2681 $SESSION->wantsurl = qualified_me();
2684 $referer = get_local_referer(false);
2685 if (!empty($referer)) {
2686 $SESSION->fromurl = $referer;
2689 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2690 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2691 foreach($authsequence as $authname) {
2692 $authplugin = get_auth_plugin($authname);
2693 $authplugin->pre_loginpage_hook();
2694 if (isloggedin()) {
2695 break;
2699 // If we're still not logged in then go to the login page
2700 if (!isloggedin()) {
2701 redirect(get_login_url());
2702 exit; // Never reached.
2707 // Loginas as redirection if needed.
2708 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2709 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2710 if ($USER->loginascontext->instanceid != $course->id) {
2711 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2716 // Check whether the user should be changing password (but only if it is REALLY them).
2717 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2718 $userauth = get_auth_plugin($USER->auth);
2719 if ($userauth->can_change_password() and !$preventredirect) {
2720 if ($setwantsurltome) {
2721 $SESSION->wantsurl = qualified_me();
2723 if ($changeurl = $userauth->change_password_url()) {
2724 // Use plugin custom url.
2725 redirect($changeurl);
2726 } else {
2727 // Use moodle internal method.
2728 redirect($CFG->wwwroot .'/login/change_password.php');
2730 } else if ($userauth->can_change_password()) {
2731 throw new moodle_exception('forcepasswordchangenotice');
2732 } else {
2733 throw new moodle_exception('nopasswordchangeforced', 'auth');
2737 // Check that the user account is properly set up. If we can't redirect to
2738 // edit their profile and this is not a WS request, perform just the lax check.
2739 // It will allow them to use filepicker on the profile edit page.
2741 if ($preventredirect && !WS_SERVER) {
2742 $usernotfullysetup = user_not_fully_set_up($USER, false);
2743 } else {
2744 $usernotfullysetup = user_not_fully_set_up($USER, true);
2747 if ($usernotfullysetup) {
2748 if ($preventredirect) {
2749 throw new moodle_exception('usernotfullysetup');
2751 if ($setwantsurltome) {
2752 $SESSION->wantsurl = qualified_me();
2754 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2757 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2758 sesskey();
2760 // Do not bother admins with any formalities, except for activities pending deletion.
2761 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2762 // Set the global $COURSE.
2763 if ($cm) {
2764 $PAGE->set_cm($cm, $course);
2765 $PAGE->set_pagelayout('incourse');
2766 } else if (!empty($courseorid)) {
2767 $PAGE->set_course($course);
2769 // Set accesstime or the user will appear offline which messes up messaging.
2770 // Do not update access time for webservice or ajax requests.
2771 if (!WS_SERVER && !AJAX_SCRIPT) {
2772 user_accesstime_log($course->id);
2774 return;
2777 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2778 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2779 if (!defined('NO_SITEPOLICY_CHECK')) {
2780 define('NO_SITEPOLICY_CHECK', false);
2783 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2784 // Do not test if the script explicitly asked for skipping the site policies check.
2785 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2786 $manager = new \core_privacy\local\sitepolicy\manager();
2787 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2788 if ($preventredirect) {
2789 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2791 if ($setwantsurltome) {
2792 $SESSION->wantsurl = qualified_me();
2794 redirect($policyurl);
2798 // Fetch the system context, the course context, and prefetch its child contexts.
2799 $sysctx = context_system::instance();
2800 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2801 if ($cm) {
2802 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2803 } else {
2804 $cmcontext = null;
2807 // If the site is currently under maintenance, then print a message.
2808 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2809 if ($preventredirect) {
2810 throw new require_login_exception('Maintenance in progress');
2812 $PAGE->set_context(null);
2813 print_maintenance_message();
2816 // Make sure the course itself is not hidden.
2817 if ($course->id == SITEID) {
2818 // Frontpage can not be hidden.
2819 } else {
2820 if (is_role_switched($course->id)) {
2821 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2822 } else {
2823 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2824 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2825 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2826 if ($preventredirect) {
2827 throw new require_login_exception('Course is hidden');
2829 $PAGE->set_context(null);
2830 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2831 // the navigation will mess up when trying to find it.
2832 navigation_node::override_active_url(new moodle_url('/'));
2833 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2838 // Is the user enrolled?
2839 if ($course->id == SITEID) {
2840 // Everybody is enrolled on the frontpage.
2841 } else {
2842 if (\core\session\manager::is_loggedinas()) {
2843 // Make sure the REAL person can access this course first.
2844 $realuser = \core\session\manager::get_realuser();
2845 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2846 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2847 if ($preventredirect) {
2848 throw new require_login_exception('Invalid course login-as access');
2850 $PAGE->set_context(null);
2851 echo $OUTPUT->header();
2852 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2856 $access = false;
2858 if (is_role_switched($course->id)) {
2859 // Ok, user had to be inside this course before the switch.
2860 $access = true;
2862 } else if (is_viewing($coursecontext, $USER)) {
2863 // Ok, no need to mess with enrol.
2864 $access = true;
2866 } else {
2867 if (isset($USER->enrol['enrolled'][$course->id])) {
2868 if ($USER->enrol['enrolled'][$course->id] > time()) {
2869 $access = true;
2870 if (isset($USER->enrol['tempguest'][$course->id])) {
2871 unset($USER->enrol['tempguest'][$course->id]);
2872 remove_temp_course_roles($coursecontext);
2874 } else {
2875 // Expired.
2876 unset($USER->enrol['enrolled'][$course->id]);
2879 if (isset($USER->enrol['tempguest'][$course->id])) {
2880 if ($USER->enrol['tempguest'][$course->id] == 0) {
2881 $access = true;
2882 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2883 $access = true;
2884 } else {
2885 // Expired.
2886 unset($USER->enrol['tempguest'][$course->id]);
2887 remove_temp_course_roles($coursecontext);
2891 if (!$access) {
2892 // Cache not ok.
2893 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2894 if ($until !== false) {
2895 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2896 if ($until == 0) {
2897 $until = ENROL_MAX_TIMESTAMP;
2899 $USER->enrol['enrolled'][$course->id] = $until;
2900 $access = true;
2902 } else {
2903 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2904 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2905 $enrols = enrol_get_plugins(true);
2906 // First ask all enabled enrol instances in course if they want to auto enrol user.
2907 foreach ($instances as $instance) {
2908 if (!isset($enrols[$instance->enrol])) {
2909 continue;
2911 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2912 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2913 if ($until !== false) {
2914 if ($until == 0) {
2915 $until = ENROL_MAX_TIMESTAMP;
2917 $USER->enrol['enrolled'][$course->id] = $until;
2918 $access = true;
2919 break;
2922 // If not enrolled yet try to gain temporary guest access.
2923 if (!$access) {
2924 foreach ($instances as $instance) {
2925 if (!isset($enrols[$instance->enrol])) {
2926 continue;
2928 // Get a duration for the guest access, a timestamp in the future or false.
2929 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2930 if ($until !== false and $until > time()) {
2931 $USER->enrol['tempguest'][$course->id] = $until;
2932 $access = true;
2933 break;
2941 if (!$access) {
2942 if ($preventredirect) {
2943 throw new require_login_exception('Not enrolled');
2945 if ($setwantsurltome) {
2946 $SESSION->wantsurl = qualified_me();
2948 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2952 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
2953 if ($cm && $cm->deletioninprogress) {
2954 if ($preventredirect) {
2955 throw new moodle_exception('activityisscheduledfordeletion');
2957 require_once($CFG->dirroot . '/course/lib.php');
2958 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
2961 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2962 if ($cm && !$cm->uservisible) {
2963 if ($preventredirect) {
2964 throw new require_login_exception('Activity is hidden');
2966 // Get the error message that activity is not available and why (if explanation can be shown to the user).
2967 $PAGE->set_course($course);
2968 $renderer = $PAGE->get_renderer('course');
2969 $message = $renderer->course_section_cm_unavailable_error_message($cm);
2970 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
2973 // Set the global $COURSE.
2974 if ($cm) {
2975 $PAGE->set_cm($cm, $course);
2976 $PAGE->set_pagelayout('incourse');
2977 } else if (!empty($courseorid)) {
2978 $PAGE->set_course($course);
2981 // Finally access granted, update lastaccess times.
2982 // Do not update access time for webservice or ajax requests.
2983 if (!WS_SERVER && !AJAX_SCRIPT) {
2984 user_accesstime_log($course->id);
2990 * This function just makes sure a user is logged out.
2992 * @package core_access
2993 * @category access
2995 function require_logout() {
2996 global $USER, $DB;
2998 if (!isloggedin()) {
2999 // This should not happen often, no need for hooks or events here.
3000 \core\session\manager::terminate_current();
3001 return;
3004 // Execute hooks before action.
3005 $authplugins = array();
3006 $authsequence = get_enabled_auth_plugins();
3007 foreach ($authsequence as $authname) {
3008 $authplugins[$authname] = get_auth_plugin($authname);
3009 $authplugins[$authname]->prelogout_hook();
3012 // Store info that gets removed during logout.
3013 $sid = session_id();
3014 $event = \core\event\user_loggedout::create(
3015 array(
3016 'userid' => $USER->id,
3017 'objectid' => $USER->id,
3018 'other' => array('sessionid' => $sid),
3021 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3022 $event->add_record_snapshot('sessions', $session);
3025 // Clone of $USER object to be used by auth plugins.
3026 $user = fullclone($USER);
3028 // Delete session record and drop $_SESSION content.
3029 \core\session\manager::terminate_current();
3031 // Trigger event AFTER action.
3032 $event->trigger();
3034 // Hook to execute auth plugins redirection after event trigger.
3035 foreach ($authplugins as $authplugin) {
3036 $authplugin->postlogout_hook($user);
3041 * Weaker version of require_login()
3043 * This is a weaker version of {@link require_login()} which only requires login
3044 * when called from within a course rather than the site page, unless
3045 * the forcelogin option is turned on.
3046 * @see require_login()
3048 * @package core_access
3049 * @category access
3051 * @param mixed $courseorid The course object or id in question
3052 * @param bool $autologinguest Allow autologin guests if that is wanted
3053 * @param object $cm Course activity module if known
3054 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3055 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3056 * in order to keep redirects working properly. MDL-14495
3057 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3058 * @return void
3059 * @throws coding_exception
3061 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3062 global $CFG, $PAGE, $SITE;
3063 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3064 or (!is_object($courseorid) and $courseorid == SITEID));
3065 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3066 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3067 // db queries so this is not really a performance concern, however it is obviously
3068 // better if you use get_fast_modinfo to get the cm before calling this.
3069 if (is_object($courseorid)) {
3070 $course = $courseorid;
3071 } else {
3072 $course = clone($SITE);
3074 $modinfo = get_fast_modinfo($course);
3075 $cm = $modinfo->get_cm($cm->id);
3077 if (!empty($CFG->forcelogin)) {
3078 // Login required for both SITE and courses.
3079 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3081 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3082 // Always login for hidden activities.
3083 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3085 } else if (isloggedin() && !isguestuser()) {
3086 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3087 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3089 } else if ($issite) {
3090 // Login for SITE not required.
3091 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3092 if (!empty($courseorid)) {
3093 if (is_object($courseorid)) {
3094 $course = $courseorid;
3095 } else {
3096 $course = clone $SITE;
3098 if ($cm) {
3099 if ($cm->course != $course->id) {
3100 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3102 $PAGE->set_cm($cm, $course);
3103 $PAGE->set_pagelayout('incourse');
3104 } else {
3105 $PAGE->set_course($course);
3107 } else {
3108 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3109 $PAGE->set_course($PAGE->course);
3111 user_accesstime_log(SITEID);
3112 return;
3114 } else {
3115 // Course login always required.
3116 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3121 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3123 * @param string $keyvalue the key value
3124 * @param string $script unique script identifier
3125 * @param int $instance instance id
3126 * @return stdClass the key entry in the user_private_key table
3127 * @since Moodle 3.2
3128 * @throws moodle_exception
3130 function validate_user_key($keyvalue, $script, $instance) {
3131 global $DB;
3133 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3134 print_error('invalidkey');
3137 if (!empty($key->validuntil) and $key->validuntil < time()) {
3138 print_error('expiredkey');
3141 if ($key->iprestriction) {
3142 $remoteaddr = getremoteaddr(null);
3143 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3144 print_error('ipmismatch');
3147 return $key;
3151 * Require key login. Function terminates with error if key not found or incorrect.
3153 * @uses NO_MOODLE_COOKIES
3154 * @uses PARAM_ALPHANUM
3155 * @param string $script unique script identifier
3156 * @param int $instance optional instance id
3157 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3158 * @return int Instance ID
3160 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3161 global $DB;
3163 if (!NO_MOODLE_COOKIES) {
3164 print_error('sessioncookiesdisable');
3167 // Extra safety.
3168 \core\session\manager::write_close();
3170 if (null === $keyvalue) {
3171 $keyvalue = required_param('key', PARAM_ALPHANUM);
3174 $key = validate_user_key($keyvalue, $script, $instance);
3176 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3177 print_error('invaliduserid');
3180 // Emulate normal session.
3181 enrol_check_plugins($user);
3182 \core\session\manager::set_user($user);
3184 // Note we are not using normal login.
3185 if (!defined('USER_KEY_LOGIN')) {
3186 define('USER_KEY_LOGIN', true);
3189 // Return instance id - it might be empty.
3190 return $key->instance;
3194 * Creates a new private user access key.
3196 * @param string $script unique target identifier
3197 * @param int $userid
3198 * @param int $instance optional instance id
3199 * @param string $iprestriction optional ip restricted access
3200 * @param int $validuntil key valid only until given data
3201 * @return string access key value
3203 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3204 global $DB;
3206 $key = new stdClass();
3207 $key->script = $script;
3208 $key->userid = $userid;
3209 $key->instance = $instance;
3210 $key->iprestriction = $iprestriction;
3211 $key->validuntil = $validuntil;
3212 $key->timecreated = time();
3214 // Something long and unique.
3215 $key->value = md5($userid.'_'.time().random_string(40));
3216 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3217 // Must be unique.
3218 $key->value = md5($userid.'_'.time().random_string(40));
3220 $DB->insert_record('user_private_key', $key);
3221 return $key->value;
3225 * Delete the user's new private user access keys for a particular script.
3227 * @param string $script unique target identifier
3228 * @param int $userid
3229 * @return void
3231 function delete_user_key($script, $userid) {
3232 global $DB;
3233 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3237 * Gets a private user access key (and creates one if one doesn't exist).
3239 * @param string $script unique target identifier
3240 * @param int $userid
3241 * @param int $instance optional instance id
3242 * @param string $iprestriction optional ip restricted access
3243 * @param int $validuntil key valid only until given date
3244 * @return string access key value
3246 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3247 global $DB;
3249 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3250 'instance' => $instance, 'iprestriction' => $iprestriction,
3251 'validuntil' => $validuntil))) {
3252 return $key->value;
3253 } else {
3254 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3260 * Modify the user table by setting the currently logged in user's last login to now.
3262 * @return bool Always returns true
3264 function update_user_login_times() {
3265 global $USER, $DB;
3267 if (isguestuser()) {
3268 // Do not update guest access times/ips for performance.
3269 return true;
3272 $now = time();
3274 $user = new stdClass();
3275 $user->id = $USER->id;
3277 // Make sure all users that logged in have some firstaccess.
3278 if ($USER->firstaccess == 0) {
3279 $USER->firstaccess = $user->firstaccess = $now;
3282 // Store the previous current as lastlogin.
3283 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3285 $USER->currentlogin = $user->currentlogin = $now;
3287 // Function user_accesstime_log() may not update immediately, better do it here.
3288 $USER->lastaccess = $user->lastaccess = $now;
3289 $USER->lastip = $user->lastip = getremoteaddr();
3291 // Note: do not call user_update_user() here because this is part of the login process,
3292 // the login event means that these fields were updated.
3293 $DB->update_record('user', $user);
3294 return true;
3298 * Determines if a user has completed setting up their account.
3300 * The lax mode (with $strict = false) has been introduced for special cases
3301 * only where we want to skip certain checks intentionally. This is valid in
3302 * certain mnet or ajax scenarios when the user cannot / should not be
3303 * redirected to edit their profile. In most cases, you should perform the
3304 * strict check.
3306 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3307 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3308 * @return bool
3310 function user_not_fully_set_up($user, $strict = true) {
3311 global $CFG;
3312 require_once($CFG->dirroot.'/user/profile/lib.php');
3314 if (isguestuser($user)) {
3315 return false;
3318 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3319 return true;
3322 if ($strict) {
3323 if (empty($user->id)) {
3324 // Strict mode can be used with existing accounts only.
3325 return true;
3327 if (!profile_has_required_custom_fields_set($user->id)) {
3328 return true;
3332 return false;
3336 * Check whether the user has exceeded the bounce threshold
3338 * @param stdClass $user A {@link $USER} object
3339 * @return bool true => User has exceeded bounce threshold
3341 function over_bounce_threshold($user) {
3342 global $CFG, $DB;
3344 if (empty($CFG->handlebounces)) {
3345 return false;
3348 if (empty($user->id)) {
3349 // No real (DB) user, nothing to do here.
3350 return false;
3353 // Set sensible defaults.
3354 if (empty($CFG->minbounces)) {
3355 $CFG->minbounces = 10;
3357 if (empty($CFG->bounceratio)) {
3358 $CFG->bounceratio = .20;
3360 $bouncecount = 0;
3361 $sendcount = 0;
3362 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3363 $bouncecount = $bounce->value;
3365 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3366 $sendcount = $send->value;
3368 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3372 * Used to increment or reset email sent count
3374 * @param stdClass $user object containing an id
3375 * @param bool $reset will reset the count to 0
3376 * @return void
3378 function set_send_count($user, $reset=false) {
3379 global $DB;
3381 if (empty($user->id)) {
3382 // No real (DB) user, nothing to do here.
3383 return;
3386 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3387 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3388 $DB->update_record('user_preferences', $pref);
3389 } else if (!empty($reset)) {
3390 // If it's not there and we're resetting, don't bother. Make a new one.
3391 $pref = new stdClass();
3392 $pref->name = 'email_send_count';
3393 $pref->value = 1;
3394 $pref->userid = $user->id;
3395 $DB->insert_record('user_preferences', $pref, false);
3400 * Increment or reset user's email bounce count
3402 * @param stdClass $user object containing an id
3403 * @param bool $reset will reset the count to 0
3405 function set_bounce_count($user, $reset=false) {
3406 global $DB;
3408 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3409 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3410 $DB->update_record('user_preferences', $pref);
3411 } else if (!empty($reset)) {
3412 // If it's not there and we're resetting, don't bother. Make a new one.
3413 $pref = new stdClass();
3414 $pref->name = 'email_bounce_count';
3415 $pref->value = 1;
3416 $pref->userid = $user->id;
3417 $DB->insert_record('user_preferences', $pref, false);
3422 * Determines if the logged in user is currently moving an activity
3424 * @param int $courseid The id of the course being tested
3425 * @return bool
3427 function ismoving($courseid) {
3428 global $USER;
3430 if (!empty($USER->activitycopy)) {
3431 return ($USER->activitycopycourse == $courseid);
3433 return false;
3437 * Returns a persons full name
3439 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3440 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3441 * specify one.
3443 * @param stdClass $user A {@link $USER} object to get full name of.
3444 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3445 * @return string
3447 function fullname($user, $override=false) {
3448 global $CFG, $SESSION;
3450 if (!isset($user->firstname) and !isset($user->lastname)) {
3451 return '';
3454 // Get all of the name fields.
3455 $allnames = get_all_user_name_fields();
3456 if ($CFG->debugdeveloper) {
3457 foreach ($allnames as $allname) {
3458 if (!property_exists($user, $allname)) {
3459 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3460 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3461 // Message has been sent, no point in sending the message multiple times.
3462 break;
3467 if (!$override) {
3468 if (!empty($CFG->forcefirstname)) {
3469 $user->firstname = $CFG->forcefirstname;
3471 if (!empty($CFG->forcelastname)) {
3472 $user->lastname = $CFG->forcelastname;
3476 if (!empty($SESSION->fullnamedisplay)) {
3477 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3480 $template = null;
3481 // If the fullnamedisplay setting is available, set the template to that.
3482 if (isset($CFG->fullnamedisplay)) {
3483 $template = $CFG->fullnamedisplay;
3485 // If the template is empty, or set to language, return the language string.
3486 if ((empty($template) || $template == 'language') && !$override) {
3487 return get_string('fullnamedisplay', null, $user);
3490 // Check to see if we are displaying according to the alternative full name format.
3491 if ($override) {
3492 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3493 // Default to show just the user names according to the fullnamedisplay string.
3494 return get_string('fullnamedisplay', null, $user);
3495 } else {
3496 // If the override is true, then change the template to use the complete name.
3497 $template = $CFG->alternativefullnameformat;
3501 $requirednames = array();
3502 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3503 foreach ($allnames as $allname) {
3504 if (strpos($template, $allname) !== false) {
3505 $requirednames[] = $allname;
3509 $displayname = $template;
3510 // Switch in the actual data into the template.
3511 foreach ($requirednames as $altname) {
3512 if (isset($user->$altname)) {
3513 // Using empty() on the below if statement causes breakages.
3514 if ((string)$user->$altname == '') {
3515 $displayname = str_replace($altname, 'EMPTY', $displayname);
3516 } else {
3517 $displayname = str_replace($altname, $user->$altname, $displayname);
3519 } else {
3520 $displayname = str_replace($altname, 'EMPTY', $displayname);
3523 // Tidy up any misc. characters (Not perfect, but gets most characters).
3524 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3525 // katakana and parenthesis.
3526 $patterns = array();
3527 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3528 // filled in by a user.
3529 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3530 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3531 // This regular expression is to remove any double spaces in the display name.
3532 $patterns[] = '/\s{2,}/u';
3533 foreach ($patterns as $pattern) {
3534 $displayname = preg_replace($pattern, ' ', $displayname);
3537 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3538 $displayname = trim($displayname);
3539 if (empty($displayname)) {
3540 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3541 // people in general feel is a good setting to fall back on.
3542 $displayname = $user->firstname;
3544 return $displayname;
3548 * A centralised location for the all name fields. Returns an array / sql string snippet.
3550 * @param bool $returnsql True for an sql select field snippet.
3551 * @param string $tableprefix table query prefix to use in front of each field.
3552 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3553 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3554 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3555 * @return array|string All name fields.
3557 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3558 // This array is provided in this order because when called by fullname() (above) if firstname is before
3559 // firstnamephonetic str_replace() will change the wrong placeholder.
3560 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3561 'lastnamephonetic' => 'lastnamephonetic',
3562 'middlename' => 'middlename',
3563 'alternatename' => 'alternatename',
3564 'firstname' => 'firstname',
3565 'lastname' => 'lastname');
3567 // Let's add a prefix to the array of user name fields if provided.
3568 if ($prefix) {
3569 foreach ($alternatenames as $key => $altname) {
3570 $alternatenames[$key] = $prefix . $altname;
3574 // If we want the end result to have firstname and lastname at the front / top of the result.
3575 if ($order) {
3576 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3577 for ($i = 0; $i < 2; $i++) {
3578 // Get the last element.
3579 $lastelement = end($alternatenames);
3580 // Remove it from the array.
3581 unset($alternatenames[$lastelement]);
3582 // Put the element back on the top of the array.
3583 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3587 // Create an sql field snippet if requested.
3588 if ($returnsql) {
3589 if ($tableprefix) {
3590 if ($fieldprefix) {
3591 foreach ($alternatenames as $key => $altname) {
3592 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3594 } else {
3595 foreach ($alternatenames as $key => $altname) {
3596 $alternatenames[$key] = $tableprefix . '.' . $altname;
3600 $alternatenames = implode(',', $alternatenames);
3602 return $alternatenames;
3606 * Reduces lines of duplicated code for getting user name fields.
3608 * See also {@link user_picture::unalias()}
3610 * @param object $addtoobject Object to add user name fields to.
3611 * @param object $secondobject Object that contains user name field information.
3612 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3613 * @param array $additionalfields Additional fields to be matched with data in the second object.
3614 * The key can be set to the user table field name.
3615 * @return object User name fields.
3617 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3618 $fields = get_all_user_name_fields(false, null, $prefix);
3619 if ($additionalfields) {
3620 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3621 // the key is a number and then sets the key to the array value.
3622 foreach ($additionalfields as $key => $value) {
3623 if (is_numeric($key)) {
3624 $additionalfields[$value] = $prefix . $value;
3625 unset($additionalfields[$key]);
3626 } else {
3627 $additionalfields[$key] = $prefix . $value;
3630 $fields = array_merge($fields, $additionalfields);
3632 foreach ($fields as $key => $field) {
3633 // Important that we have all of the user name fields present in the object that we are sending back.
3634 $addtoobject->$key = '';
3635 if (isset($secondobject->$field)) {
3636 $addtoobject->$key = $secondobject->$field;
3639 return $addtoobject;
3643 * Returns an array of values in order of occurance in a provided string.
3644 * The key in the result is the character postion in the string.
3646 * @param array $values Values to be found in the string format
3647 * @param string $stringformat The string which may contain values being searched for.
3648 * @return array An array of values in order according to placement in the string format.
3650 function order_in_string($values, $stringformat) {
3651 $valuearray = array();
3652 foreach ($values as $value) {
3653 $pattern = "/$value\b/";
3654 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3655 if (preg_match($pattern, $stringformat)) {
3656 $replacement = "thing";
3657 // Replace the value with something more unique to ensure we get the right position when using strpos().
3658 $newformat = preg_replace($pattern, $replacement, $stringformat);
3659 $position = strpos($newformat, $replacement);
3660 $valuearray[$position] = $value;
3663 ksort($valuearray);
3664 return $valuearray;
3668 * Checks if current user is shown any extra fields when listing users.
3670 * @param object $context Context
3671 * @param array $already Array of fields that we're going to show anyway
3672 * so don't bother listing them
3673 * @return array Array of field names from user table, not including anything
3674 * listed in $already
3676 function get_extra_user_fields($context, $already = array()) {
3677 global $CFG;
3679 // Only users with permission get the extra fields.
3680 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3681 return array();
3684 // Split showuseridentity on comma (filter needed in case the showuseridentity is empty).
3685 $extra = array_filter(explode(',', $CFG->showuseridentity));
3687 foreach ($extra as $key => $field) {
3688 if (in_array($field, $already)) {
3689 unset($extra[$key]);
3693 // If the identity fields are also among hidden fields, make sure the user can see them.
3694 $hiddenfields = array_filter(explode(',', $CFG->hiddenuserfields));
3695 $hiddenidentifiers = array_intersect($extra, $hiddenfields);
3697 if ($hiddenidentifiers) {
3698 if ($context->get_course_context(false)) {
3699 // We are somewhere inside a course.
3700 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3702 } else {
3703 // We are not inside a course.
3704 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
3707 if (!$canviewhiddenuserfields) {
3708 // Remove hidden identifiers from the list.
3709 $extra = array_diff($extra, $hiddenidentifiers);
3713 // Re-index the entries.
3714 $extra = array_values($extra);
3716 return $extra;
3720 * If the current user is to be shown extra user fields when listing or
3721 * selecting users, returns a string suitable for including in an SQL select
3722 * clause to retrieve those fields.
3724 * @param context $context Context
3725 * @param string $alias Alias of user table, e.g. 'u' (default none)
3726 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3727 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3728 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3730 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3731 $fields = get_extra_user_fields($context, $already);
3732 $result = '';
3733 // Add punctuation for alias.
3734 if ($alias !== '') {
3735 $alias .= '.';
3737 foreach ($fields as $field) {
3738 $result .= ', ' . $alias . $field;
3739 if ($prefix) {
3740 $result .= ' AS ' . $prefix . $field;
3743 return $result;
3747 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3748 * @param string $field Field name, e.g. 'phone1'
3749 * @return string Text description taken from language file, e.g. 'Phone number'
3751 function get_user_field_name($field) {
3752 // Some fields have language strings which are not the same as field name.
3753 switch ($field) {
3754 case 'url' : {
3755 return get_string('webpage');
3757 case 'icq' : {
3758 return get_string('icqnumber');
3760 case 'skype' : {
3761 return get_string('skypeid');
3763 case 'aim' : {
3764 return get_string('aimid');
3766 case 'yahoo' : {
3767 return get_string('yahooid');
3769 case 'msn' : {
3770 return get_string('msnid');
3772 case 'picture' : {
3773 return get_string('pictureofuser');
3776 // Otherwise just use the same lang string.
3777 return get_string($field);
3781 * Returns whether a given authentication plugin exists.
3783 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3784 * @return boolean Whether the plugin is available.
3786 function exists_auth_plugin($auth) {
3787 global $CFG;
3789 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3790 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3792 return false;
3796 * Checks if a given plugin is in the list of enabled authentication plugins.
3798 * @param string $auth Authentication plugin.
3799 * @return boolean Whether the plugin is enabled.
3801 function is_enabled_auth($auth) {
3802 if (empty($auth)) {
3803 return false;
3806 $enabled = get_enabled_auth_plugins();
3808 return in_array($auth, $enabled);
3812 * Returns an authentication plugin instance.
3814 * @param string $auth name of authentication plugin
3815 * @return auth_plugin_base An instance of the required authentication plugin.
3817 function get_auth_plugin($auth) {
3818 global $CFG;
3820 // Check the plugin exists first.
3821 if (! exists_auth_plugin($auth)) {
3822 print_error('authpluginnotfound', 'debug', '', $auth);
3825 // Return auth plugin instance.
3826 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3827 $class = "auth_plugin_$auth";
3828 return new $class;
3832 * Returns array of active auth plugins.
3834 * @param bool $fix fix $CFG->auth if needed
3835 * @return array
3837 function get_enabled_auth_plugins($fix=false) {
3838 global $CFG;
3840 $default = array('manual', 'nologin');
3842 if (empty($CFG->auth)) {
3843 $auths = array();
3844 } else {
3845 $auths = explode(',', $CFG->auth);
3848 if ($fix) {
3849 $auths = array_unique($auths);
3850 foreach ($auths as $k => $authname) {
3851 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3852 unset($auths[$k]);
3855 $newconfig = implode(',', $auths);
3856 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3857 set_config('auth', $newconfig);
3861 return (array_merge($default, $auths));
3865 * Returns true if an internal authentication method is being used.
3866 * if method not specified then, global default is assumed
3868 * @param string $auth Form of authentication required
3869 * @return bool
3871 function is_internal_auth($auth) {
3872 // Throws error if bad $auth.
3873 $authplugin = get_auth_plugin($auth);
3874 return $authplugin->is_internal();
3878 * Returns true if the user is a 'restored' one.
3880 * Used in the login process to inform the user and allow him/her to reset the password
3882 * @param string $username username to be checked
3883 * @return bool
3885 function is_restored_user($username) {
3886 global $CFG, $DB;
3888 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3892 * Returns an array of user fields
3894 * @return array User field/column names
3896 function get_user_fieldnames() {
3897 global $DB;
3899 $fieldarray = $DB->get_columns('user');
3900 unset($fieldarray['id']);
3901 $fieldarray = array_keys($fieldarray);
3903 return $fieldarray;
3907 * Creates a bare-bones user record
3909 * @todo Outline auth types and provide code example
3911 * @param string $username New user's username to add to record
3912 * @param string $password New user's password to add to record
3913 * @param string $auth Form of authentication required
3914 * @return stdClass A complete user object
3916 function create_user_record($username, $password, $auth = 'manual') {
3917 global $CFG, $DB;
3918 require_once($CFG->dirroot.'/user/profile/lib.php');
3919 require_once($CFG->dirroot.'/user/lib.php');
3921 // Just in case check text case.
3922 $username = trim(core_text::strtolower($username));
3924 $authplugin = get_auth_plugin($auth);
3925 $customfields = $authplugin->get_custom_user_profile_fields();
3926 $newuser = new stdClass();
3927 if ($newinfo = $authplugin->get_userinfo($username)) {
3928 $newinfo = truncate_userinfo($newinfo);
3929 foreach ($newinfo as $key => $value) {
3930 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3931 $newuser->$key = $value;
3936 if (!empty($newuser->email)) {
3937 if (email_is_not_allowed($newuser->email)) {
3938 unset($newuser->email);
3942 if (!isset($newuser->city)) {
3943 $newuser->city = '';
3946 $newuser->auth = $auth;
3947 $newuser->username = $username;
3949 // Fix for MDL-8480
3950 // user CFG lang for user if $newuser->lang is empty
3951 // or $user->lang is not an installed language.
3952 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3953 $newuser->lang = $CFG->lang;
3955 $newuser->confirmed = 1;
3956 $newuser->lastip = getremoteaddr();
3957 $newuser->timecreated = time();
3958 $newuser->timemodified = $newuser->timecreated;
3959 $newuser->mnethostid = $CFG->mnet_localhost_id;
3961 $newuser->id = user_create_user($newuser, false, false);
3963 // Save user profile data.
3964 profile_save_data($newuser);
3966 $user = get_complete_user_data('id', $newuser->id);
3967 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3968 set_user_preference('auth_forcepasswordchange', 1, $user);
3970 // Set the password.
3971 update_internal_user_password($user, $password);
3973 // Trigger event.
3974 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3976 return $user;
3980 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3982 * @param string $username user's username to update the record
3983 * @return stdClass A complete user object
3985 function update_user_record($username) {
3986 global $DB, $CFG;
3987 // Just in case check text case.
3988 $username = trim(core_text::strtolower($username));
3990 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3991 return update_user_record_by_id($oldinfo->id);
3995 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3997 * @param int $id user id
3998 * @return stdClass A complete user object
4000 function update_user_record_by_id($id) {
4001 global $DB, $CFG;
4002 require_once($CFG->dirroot."/user/profile/lib.php");
4003 require_once($CFG->dirroot.'/user/lib.php');
4005 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
4006 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
4008 $newuser = array();
4009 $userauth = get_auth_plugin($oldinfo->auth);
4011 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
4012 $newinfo = truncate_userinfo($newinfo);
4013 $customfields = $userauth->get_custom_user_profile_fields();
4015 foreach ($newinfo as $key => $value) {
4016 $iscustom = in_array($key, $customfields);
4017 if (!$iscustom) {
4018 $key = strtolower($key);
4020 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4021 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4022 // Unknown or must not be changed.
4023 continue;
4025 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
4026 continue;
4028 $confval = $userauth->config->{'field_updatelocal_' . $key};
4029 $lockval = $userauth->config->{'field_lock_' . $key};
4030 if ($confval === 'onlogin') {
4031 // MDL-4207 Don't overwrite modified user profile values with
4032 // empty LDAP values when 'unlocked if empty' is set. The purpose
4033 // of the setting 'unlocked if empty' is to allow the user to fill
4034 // in a value for the selected field _if LDAP is giving
4035 // nothing_ for this field. Thus it makes sense to let this value
4036 // stand in until LDAP is giving a value for this field.
4037 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4038 if ($iscustom || (in_array($key, $userauth->userfields) &&
4039 ((string)$oldinfo->$key !== (string)$value))) {
4040 $newuser[$key] = (string)$value;
4045 if ($newuser) {
4046 $newuser['id'] = $oldinfo->id;
4047 $newuser['timemodified'] = time();
4048 user_update_user((object) $newuser, false, false);
4050 // Save user profile data.
4051 profile_save_data((object) $newuser);
4053 // Trigger event.
4054 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4058 return get_complete_user_data('id', $oldinfo->id);
4062 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4064 * @param array $info Array of user properties to truncate if needed
4065 * @return array The now truncated information that was passed in
4067 function truncate_userinfo(array $info) {
4068 // Define the limits.
4069 $limit = array(
4070 'username' => 100,
4071 'idnumber' => 255,
4072 'firstname' => 100,
4073 'lastname' => 100,
4074 'email' => 100,
4075 'icq' => 15,
4076 'phone1' => 20,
4077 'phone2' => 20,
4078 'institution' => 255,
4079 'department' => 255,
4080 'address' => 255,
4081 'city' => 120,
4082 'country' => 2,
4083 'url' => 255,
4086 // Apply where needed.
4087 foreach (array_keys($info) as $key) {
4088 if (!empty($limit[$key])) {
4089 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4093 return $info;
4097 * Marks user deleted in internal user database and notifies the auth plugin.
4098 * Also unenrols user from all roles and does other cleanup.
4100 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4102 * @param stdClass $user full user object before delete
4103 * @return boolean success
4104 * @throws coding_exception if invalid $user parameter detected
4106 function delete_user(stdClass $user) {
4107 global $CFG, $DB, $SESSION;
4108 require_once($CFG->libdir.'/grouplib.php');
4109 require_once($CFG->libdir.'/gradelib.php');
4110 require_once($CFG->dirroot.'/message/lib.php');
4111 require_once($CFG->dirroot.'/user/lib.php');
4113 // Make sure nobody sends bogus record type as parameter.
4114 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4115 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4118 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4119 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4120 debugging('Attempt to delete unknown user account.');
4121 return false;
4124 // There must be always exactly one guest record, originally the guest account was identified by username only,
4125 // now we use $CFG->siteguest for performance reasons.
4126 if ($user->username === 'guest' or isguestuser($user)) {
4127 debugging('Guest user account can not be deleted.');
4128 return false;
4131 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4132 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4133 if ($user->auth === 'manual' and is_siteadmin($user)) {
4134 debugging('Local administrator accounts can not be deleted.');
4135 return false;
4138 // Allow plugins to use this user object before we completely delete it.
4139 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4140 foreach ($pluginsfunction as $plugintype => $plugins) {
4141 foreach ($plugins as $pluginfunction) {
4142 $pluginfunction($user);
4147 // Keep user record before updating it, as we have to pass this to user_deleted event.
4148 $olduser = clone $user;
4150 // Keep a copy of user context, we need it for event.
4151 $usercontext = context_user::instance($user->id);
4153 // Delete all grades - backup is kept in grade_grades_history table.
4154 grade_user_delete($user->id);
4156 // TODO: remove from cohorts using standard API here.
4158 // Remove user tags.
4159 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4161 // Unconditionally unenrol from all courses.
4162 enrol_user_delete($user);
4164 // Unenrol from all roles in all contexts.
4165 // This might be slow but it is really needed - modules might do some extra cleanup!
4166 role_unassign_all(array('userid' => $user->id));
4168 // Now do a brute force cleanup.
4170 // Remove from all cohorts.
4171 $DB->delete_records('cohort_members', array('userid' => $user->id));
4173 // Remove from all groups.
4174 $DB->delete_records('groups_members', array('userid' => $user->id));
4176 // Brute force unenrol from all courses.
4177 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4179 // Purge user preferences.
4180 $DB->delete_records('user_preferences', array('userid' => $user->id));
4182 // Purge user extra profile info.
4183 $DB->delete_records('user_info_data', array('userid' => $user->id));
4185 // Purge log of previous password hashes.
4186 $DB->delete_records('user_password_history', array('userid' => $user->id));
4188 // Last course access not necessary either.
4189 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4190 // Remove all user tokens.
4191 $DB->delete_records('external_tokens', array('userid' => $user->id));
4193 // Unauthorise the user for all services.
4194 $DB->delete_records('external_services_users', array('userid' => $user->id));
4196 // Remove users private keys.
4197 $DB->delete_records('user_private_key', array('userid' => $user->id));
4199 // Remove users customised pages.
4200 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4202 // Delete user from $SESSION->bulk_users.
4203 if (isset($SESSION->bulk_users[$user->id])) {
4204 unset($SESSION->bulk_users[$user->id]);
4207 // Force logout - may fail if file based sessions used, sorry.
4208 \core\session\manager::kill_user_sessions($user->id);
4210 // Generate username from email address, or a fake email.
4211 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4212 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
4214 // Workaround for bulk deletes of users with the same email address.
4215 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4216 $delname++;
4219 // Mark internal user record as "deleted".
4220 $updateuser = new stdClass();
4221 $updateuser->id = $user->id;
4222 $updateuser->deleted = 1;
4223 $updateuser->username = $delname; // Remember it just in case.
4224 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4225 $updateuser->idnumber = ''; // Clear this field to free it up.
4226 $updateuser->picture = 0;
4227 $updateuser->timemodified = time();
4229 // Don't trigger update event, as user is being deleted.
4230 user_update_user($updateuser, false, false);
4232 // Delete all content associated with the user context, but not the context itself.
4233 $usercontext->delete_content();
4235 // Any plugin that needs to cleanup should register this event.
4236 // Trigger event.
4237 $event = \core\event\user_deleted::create(
4238 array(
4239 'objectid' => $user->id,
4240 'relateduserid' => $user->id,
4241 'context' => $usercontext,
4242 'other' => array(
4243 'username' => $user->username,
4244 'email' => $user->email,
4245 'idnumber' => $user->idnumber,
4246 'picture' => $user->picture,
4247 'mnethostid' => $user->mnethostid
4251 $event->add_record_snapshot('user', $olduser);
4252 $event->trigger();
4254 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4255 // should know about this updated property persisted to the user's table.
4256 $user->timemodified = $updateuser->timemodified;
4258 // Notify auth plugin - do not block the delete even when plugin fails.
4259 $authplugin = get_auth_plugin($user->auth);
4260 $authplugin->user_delete($user);
4262 return true;
4266 * Retrieve the guest user object.
4268 * @return stdClass A {@link $USER} object
4270 function guest_user() {
4271 global $CFG, $DB;
4273 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4274 $newuser->confirmed = 1;
4275 $newuser->lang = $CFG->lang;
4276 $newuser->lastip = getremoteaddr();
4279 return $newuser;
4283 * Authenticates a user against the chosen authentication mechanism
4285 * Given a username and password, this function looks them
4286 * up using the currently selected authentication mechanism,
4287 * and if the authentication is successful, it returns a
4288 * valid $user object from the 'user' table.
4290 * Uses auth_ functions from the currently active auth module
4292 * After authenticate_user_login() returns success, you will need to
4293 * log that the user has logged in, and call complete_user_login() to set
4294 * the session up.
4296 * Note: this function works only with non-mnet accounts!
4298 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4299 * @param string $password User's password
4300 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4301 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4302 * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4303 * @return stdClass|false A {@link $USER} object or false if error
4305 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4306 global $CFG, $DB;
4307 require_once("$CFG->libdir/authlib.php");
4309 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4310 // we have found the user
4312 } else if (!empty($CFG->authloginviaemail)) {
4313 if ($email = clean_param($username, PARAM_EMAIL)) {
4314 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4315 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4316 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4317 if (count($users) === 1) {
4318 // Use email for login only if unique.
4319 $user = reset($users);
4320 $user = get_complete_user_data('id', $user->id);
4321 $username = $user->username;
4323 unset($users);
4327 // Make sure this request came from the login form.
4328 if (!\core\session\manager::validate_login_token($logintoken)) {
4329 $failurereason = AUTH_LOGIN_FAILED;
4331 // Trigger login failed event.
4332 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4333 'other' => array('username' => $username, 'reason' => $failurereason)));
4334 $event->trigger();
4335 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4336 return false;
4339 $authsenabled = get_enabled_auth_plugins();
4341 if ($user) {
4342 // Use manual if auth not set.
4343 $auth = empty($user->auth) ? 'manual' : $user->auth;
4345 if (in_array($user->auth, $authsenabled)) {
4346 $authplugin = get_auth_plugin($user->auth);
4347 $authplugin->pre_user_login_hook($user);
4350 if (!empty($user->suspended)) {
4351 $failurereason = AUTH_LOGIN_SUSPENDED;
4353 // Trigger login failed event.
4354 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4355 'other' => array('username' => $username, 'reason' => $failurereason)));
4356 $event->trigger();
4357 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4358 return false;
4360 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4361 // Legacy way to suspend user.
4362 $failurereason = AUTH_LOGIN_SUSPENDED;
4364 // Trigger login failed event.
4365 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4366 'other' => array('username' => $username, 'reason' => $failurereason)));
4367 $event->trigger();
4368 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4369 return false;
4371 $auths = array($auth);
4373 } else {
4374 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4375 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4376 $failurereason = AUTH_LOGIN_NOUSER;
4378 // Trigger login failed event.
4379 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4380 'reason' => $failurereason)));
4381 $event->trigger();
4382 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4383 return false;
4386 // User does not exist.
4387 $auths = $authsenabled;
4388 $user = new stdClass();
4389 $user->id = 0;
4392 if ($ignorelockout) {
4393 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4394 // or this function is called from a SSO script.
4395 } else if ($user->id) {
4396 // Verify login lockout after other ways that may prevent user login.
4397 if (login_is_lockedout($user)) {
4398 $failurereason = AUTH_LOGIN_LOCKOUT;
4400 // Trigger login failed event.
4401 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4402 'other' => array('username' => $username, 'reason' => $failurereason)));
4403 $event->trigger();
4405 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4406 return false;
4408 } else {
4409 // We can not lockout non-existing accounts.
4412 foreach ($auths as $auth) {
4413 $authplugin = get_auth_plugin($auth);
4415 // On auth fail fall through to the next plugin.
4416 if (!$authplugin->user_login($username, $password)) {
4417 continue;
4420 // Successful authentication.
4421 if ($user->id) {
4422 // User already exists in database.
4423 if (empty($user->auth)) {
4424 // For some reason auth isn't set yet.
4425 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4426 $user->auth = $auth;
4429 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4430 // the current hash algorithm while we have access to the user's password.
4431 update_internal_user_password($user, $password);
4433 if ($authplugin->is_synchronised_with_external()) {
4434 // Update user record from external DB.
4435 $user = update_user_record_by_id($user->id);
4437 } else {
4438 // The user is authenticated but user creation may be disabled.
4439 if (!empty($CFG->authpreventaccountcreation)) {
4440 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4442 // Trigger login failed event.
4443 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4444 'reason' => $failurereason)));
4445 $event->trigger();
4447 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4448 $_SERVER['HTTP_USER_AGENT']);
4449 return false;
4450 } else {
4451 $user = create_user_record($username, $password, $auth);
4455 $authplugin->sync_roles($user);
4457 foreach ($authsenabled as $hau) {
4458 $hauth = get_auth_plugin($hau);
4459 $hauth->user_authenticated_hook($user, $username, $password);
4462 if (empty($user->id)) {
4463 $failurereason = AUTH_LOGIN_NOUSER;
4464 // Trigger login failed event.
4465 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4466 'reason' => $failurereason)));
4467 $event->trigger();
4468 return false;
4471 if (!empty($user->suspended)) {
4472 // Just in case some auth plugin suspended account.
4473 $failurereason = AUTH_LOGIN_SUSPENDED;
4474 // Trigger login failed event.
4475 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4476 'other' => array('username' => $username, 'reason' => $failurereason)));
4477 $event->trigger();
4478 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4479 return false;
4482 login_attempt_valid($user);
4483 $failurereason = AUTH_LOGIN_OK;
4484 return $user;
4487 // Failed if all the plugins have failed.
4488 if (debugging('', DEBUG_ALL)) {
4489 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4492 if ($user->id) {
4493 login_attempt_failed($user);
4494 $failurereason = AUTH_LOGIN_FAILED;
4495 // Trigger login failed event.
4496 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4497 'other' => array('username' => $username, 'reason' => $failurereason)));
4498 $event->trigger();
4499 } else {
4500 $failurereason = AUTH_LOGIN_NOUSER;
4501 // Trigger login failed event.
4502 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4503 'reason' => $failurereason)));
4504 $event->trigger();
4507 return false;
4511 * Call to complete the user login process after authenticate_user_login()
4512 * has succeeded. It will setup the $USER variable and other required bits
4513 * and pieces.
4515 * NOTE:
4516 * - It will NOT log anything -- up to the caller to decide what to log.
4517 * - this function does not set any cookies any more!
4519 * @param stdClass $user
4520 * @return stdClass A {@link $USER} object - BC only, do not use
4522 function complete_user_login($user) {
4523 global $CFG, $DB, $USER, $SESSION;
4525 \core\session\manager::login_user($user);
4527 // Reload preferences from DB.
4528 unset($USER->preference);
4529 check_user_preferences_loaded($USER);
4531 // Update login times.
4532 update_user_login_times();
4534 // Extra session prefs init.
4535 set_login_session_preferences();
4537 // Trigger login event.
4538 $event = \core\event\user_loggedin::create(
4539 array(
4540 'userid' => $USER->id,
4541 'objectid' => $USER->id,
4542 'other' => array('username' => $USER->username),
4545 $event->trigger();
4547 // Queue migrating the messaging data, if we need to.
4548 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4549 // Check if there are any legacy messages to migrate.
4550 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4551 \core_message\task\migrate_message_data::queue_task($USER->id);
4552 } else {
4553 set_user_preference('core_message_migrate_data', true, $USER->id);
4557 if (isguestuser()) {
4558 // No need to continue when user is THE guest.
4559 return $USER;
4562 if (CLI_SCRIPT) {
4563 // We can redirect to password change URL only in browser.
4564 return $USER;
4567 // Select password change url.
4568 $userauth = get_auth_plugin($USER->auth);
4570 // Check whether the user should be changing password.
4571 if (get_user_preferences('auth_forcepasswordchange', false)) {
4572 if ($userauth->can_change_password()) {
4573 if ($changeurl = $userauth->change_password_url()) {
4574 redirect($changeurl);
4575 } else {
4576 require_once($CFG->dirroot . '/login/lib.php');
4577 $SESSION->wantsurl = core_login_get_return_url();
4578 redirect($CFG->wwwroot.'/login/change_password.php');
4580 } else {
4581 print_error('nopasswordchangeforced', 'auth');
4584 return $USER;
4588 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4590 * @param string $password String to check.
4591 * @return boolean True if the $password matches the format of an md5 sum.
4593 function password_is_legacy_hash($password) {
4594 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4598 * Compare password against hash stored in user object to determine if it is valid.
4600 * If necessary it also updates the stored hash to the current format.
4602 * @param stdClass $user (Password property may be updated).
4603 * @param string $password Plain text password.
4604 * @return bool True if password is valid.
4606 function validate_internal_user_password($user, $password) {
4607 global $CFG;
4609 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4610 // Internal password is not used at all, it can not validate.
4611 return false;
4614 // If hash isn't a legacy (md5) hash, validate using the library function.
4615 if (!password_is_legacy_hash($user->password)) {
4616 return password_verify($password, $user->password);
4619 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4620 // is valid we can then update it to the new algorithm.
4622 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4623 $validated = false;
4625 if ($user->password === md5($password.$sitesalt)
4626 or $user->password === md5($password)
4627 or $user->password === md5(addslashes($password).$sitesalt)
4628 or $user->password === md5(addslashes($password))) {
4629 // Note: we are intentionally using the addslashes() here because we
4630 // need to accept old password hashes of passwords with magic quotes.
4631 $validated = true;
4633 } else {
4634 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4635 $alt = 'passwordsaltalt'.$i;
4636 if (!empty($CFG->$alt)) {
4637 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4638 $validated = true;
4639 break;
4645 if ($validated) {
4646 // If the password matches the existing md5 hash, update to the
4647 // current hash algorithm while we have access to the user's password.
4648 update_internal_user_password($user, $password);
4651 return $validated;
4655 * Calculate hash for a plain text password.
4657 * @param string $password Plain text password to be hashed.
4658 * @param bool $fasthash If true, use a low cost factor when generating the hash
4659 * This is much faster to generate but makes the hash
4660 * less secure. It is used when lots of hashes need to
4661 * be generated quickly.
4662 * @return string The hashed password.
4664 * @throws moodle_exception If a problem occurs while generating the hash.
4666 function hash_internal_user_password($password, $fasthash = false) {
4667 global $CFG;
4669 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4670 $options = ($fasthash) ? array('cost' => 4) : array();
4672 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4674 if ($generatedhash === false || $generatedhash === null) {
4675 throw new moodle_exception('Failed to generate password hash.');
4678 return $generatedhash;
4682 * Update password hash in user object (if necessary).
4684 * The password is updated if:
4685 * 1. The password has changed (the hash of $user->password is different
4686 * to the hash of $password).
4687 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4688 * md5 algorithm).
4690 * Updating the password will modify the $user object and the database
4691 * record to use the current hashing algorithm.
4692 * It will remove Web Services user tokens too.
4694 * @param stdClass $user User object (password property may be updated).
4695 * @param string $password Plain text password.
4696 * @param bool $fasthash If true, use a low cost factor when generating the hash
4697 * This is much faster to generate but makes the hash
4698 * less secure. It is used when lots of hashes need to
4699 * be generated quickly.
4700 * @return bool Always returns true.
4702 function update_internal_user_password($user, $password, $fasthash = false) {
4703 global $CFG, $DB;
4705 // Figure out what the hashed password should be.
4706 if (!isset($user->auth)) {
4707 debugging('User record in update_internal_user_password() must include field auth',
4708 DEBUG_DEVELOPER);
4709 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4711 $authplugin = get_auth_plugin($user->auth);
4712 if ($authplugin->prevent_local_passwords()) {
4713 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4714 } else {
4715 $hashedpassword = hash_internal_user_password($password, $fasthash);
4718 $algorithmchanged = false;
4720 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4721 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4722 $passwordchanged = ($user->password !== $hashedpassword);
4724 } else if (isset($user->password)) {
4725 // If verification fails then it means the password has changed.
4726 $passwordchanged = !password_verify($password, $user->password);
4727 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4728 } else {
4729 // While creating new user, password in unset in $user object, to avoid
4730 // saving it with user_create()
4731 $passwordchanged = true;
4734 if ($passwordchanged || $algorithmchanged) {
4735 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4736 $user->password = $hashedpassword;
4738 // Trigger event.
4739 $user = $DB->get_record('user', array('id' => $user->id));
4740 \core\event\user_password_updated::create_from_user($user)->trigger();
4742 // Remove WS user tokens.
4743 if (!empty($CFG->passwordchangetokendeletion)) {
4744 require_once($CFG->dirroot.'/webservice/lib.php');
4745 webservice::delete_user_ws_tokens($user->id);
4749 return true;
4753 * Get a complete user record, which includes all the info in the user record.
4755 * Intended for setting as $USER session variable
4757 * @param string $field The user field to be checked for a given value.
4758 * @param string $value The value to match for $field.
4759 * @param int $mnethostid
4760 * @return mixed False, or A {@link $USER} object.
4762 function get_complete_user_data($field, $value, $mnethostid = null) {
4763 global $CFG, $DB;
4765 if (!$field || !$value) {
4766 return false;
4769 // Build the WHERE clause for an SQL query.
4770 $params = array('fieldval' => $value);
4771 $constraints = "$field = :fieldval AND deleted <> 1";
4773 // If we are loading user data based on anything other than id,
4774 // we must also restrict our search based on mnet host.
4775 if ($field != 'id') {
4776 if (empty($mnethostid)) {
4777 // If empty, we restrict to local users.
4778 $mnethostid = $CFG->mnet_localhost_id;
4781 if (!empty($mnethostid)) {
4782 $params['mnethostid'] = $mnethostid;
4783 $constraints .= " AND mnethostid = :mnethostid";
4786 // Get all the basic user data.
4787 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4788 return false;
4791 // Get various settings and preferences.
4793 // Preload preference cache.
4794 check_user_preferences_loaded($user);
4796 // Load course enrolment related stuff.
4797 $user->lastcourseaccess = array(); // During last session.
4798 $user->currentcourseaccess = array(); // During current session.
4799 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4800 foreach ($lastaccesses as $lastaccess) {
4801 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4805 $sql = "SELECT g.id, g.courseid
4806 FROM {groups} g, {groups_members} gm
4807 WHERE gm.groupid=g.id AND gm.userid=?";
4809 // This is a special hack to speedup calendar display.
4810 $user->groupmember = array();
4811 if (!isguestuser($user)) {
4812 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4813 foreach ($groups as $group) {
4814 if (!array_key_exists($group->courseid, $user->groupmember)) {
4815 $user->groupmember[$group->courseid] = array();
4817 $user->groupmember[$group->courseid][$group->id] = $group->id;
4822 // Add cohort theme.
4823 if (!empty($CFG->allowcohortthemes)) {
4824 require_once($CFG->dirroot . '/cohort/lib.php');
4825 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4826 $user->cohorttheme = $cohorttheme;
4830 // Add the custom profile fields to the user record.
4831 $user->profile = array();
4832 if (!isguestuser($user)) {
4833 require_once($CFG->dirroot.'/user/profile/lib.php');
4834 profile_load_custom_fields($user);
4837 // Rewrite some variables if necessary.
4838 if (!empty($user->description)) {
4839 // No need to cart all of it around.
4840 $user->description = true;
4842 if (isguestuser($user)) {
4843 // Guest language always same as site.
4844 $user->lang = $CFG->lang;
4845 // Name always in current language.
4846 $user->firstname = get_string('guestuser');
4847 $user->lastname = ' ';
4850 return $user;
4854 * Validate a password against the configured password policy
4856 * @param string $password the password to be checked against the password policy
4857 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4858 * @return bool true if the password is valid according to the policy. false otherwise.
4860 function check_password_policy($password, &$errmsg) {
4861 global $CFG;
4863 if (!empty($CFG->passwordpolicy)) {
4864 $errmsg = '';
4865 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4866 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4868 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4869 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4871 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4872 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4874 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4875 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4877 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4878 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4880 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4881 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4885 // Fire any additional password policy functions from plugins.
4886 // Plugin functions should output an error message string or empty string for success.
4887 $pluginsfunction = get_plugins_with_function('check_password_policy');
4888 foreach ($pluginsfunction as $plugintype => $plugins) {
4889 foreach ($plugins as $pluginfunction) {
4890 $pluginerr = $pluginfunction($password);
4891 if ($pluginerr) {
4892 $errmsg .= '<div>'. $pluginerr .'</div>';
4897 if ($errmsg == '') {
4898 return true;
4899 } else {
4900 return false;
4906 * When logging in, this function is run to set certain preferences for the current SESSION.
4908 function set_login_session_preferences() {
4909 global $SESSION;
4911 $SESSION->justloggedin = true;
4913 unset($SESSION->lang);
4914 unset($SESSION->forcelang);
4915 unset($SESSION->load_navigation_admin);
4920 * Delete a course, including all related data from the database, and any associated files.
4922 * @param mixed $courseorid The id of the course or course object to delete.
4923 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4924 * @return bool true if all the removals succeeded. false if there were any failures. If this
4925 * method returns false, some of the removals will probably have succeeded, and others
4926 * failed, but you have no way of knowing which.
4928 function delete_course($courseorid, $showfeedback = true) {
4929 global $DB;
4931 if (is_object($courseorid)) {
4932 $courseid = $courseorid->id;
4933 $course = $courseorid;
4934 } else {
4935 $courseid = $courseorid;
4936 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4937 return false;
4940 $context = context_course::instance($courseid);
4942 // Frontpage course can not be deleted!!
4943 if ($courseid == SITEID) {
4944 return false;
4947 // Allow plugins to use this course before we completely delete it.
4948 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
4949 foreach ($pluginsfunction as $plugintype => $plugins) {
4950 foreach ($plugins as $pluginfunction) {
4951 $pluginfunction($course);
4956 // Make the course completely empty.
4957 remove_course_contents($courseid, $showfeedback);
4959 // Delete the course and related context instance.
4960 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4962 $DB->delete_records("course", array("id" => $courseid));
4963 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4965 // Reset all course related caches here.
4966 if (class_exists('format_base', false)) {
4967 format_base::reset_course_cache($courseid);
4970 // Trigger a course deleted event.
4971 $event = \core\event\course_deleted::create(array(
4972 'objectid' => $course->id,
4973 'context' => $context,
4974 'other' => array(
4975 'shortname' => $course->shortname,
4976 'fullname' => $course->fullname,
4977 'idnumber' => $course->idnumber
4980 $event->add_record_snapshot('course', $course);
4981 $event->trigger();
4983 return true;
4987 * Clear a course out completely, deleting all content but don't delete the course itself.
4989 * This function does not verify any permissions.
4991 * Please note this function also deletes all user enrolments,
4992 * enrolment instances and role assignments by default.
4994 * $options:
4995 * - 'keep_roles_and_enrolments' - false by default
4996 * - 'keep_groups_and_groupings' - false by default
4998 * @param int $courseid The id of the course that is being deleted
4999 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5000 * @param array $options extra options
5001 * @return bool true if all the removals succeeded. false if there were any failures. If this
5002 * method returns false, some of the removals will probably have succeeded, and others
5003 * failed, but you have no way of knowing which.
5005 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5006 global $CFG, $DB, $OUTPUT;
5008 require_once($CFG->libdir.'/badgeslib.php');
5009 require_once($CFG->libdir.'/completionlib.php');
5010 require_once($CFG->libdir.'/questionlib.php');
5011 require_once($CFG->libdir.'/gradelib.php');
5012 require_once($CFG->dirroot.'/group/lib.php');
5013 require_once($CFG->dirroot.'/comment/lib.php');
5014 require_once($CFG->dirroot.'/rating/lib.php');
5015 require_once($CFG->dirroot.'/notes/lib.php');
5017 // Handle course badges.
5018 badges_handle_course_deletion($courseid);
5020 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5021 $strdeleted = get_string('deleted').' - ';
5023 // Some crazy wishlist of stuff we should skip during purging of course content.
5024 $options = (array)$options;
5026 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5027 $coursecontext = context_course::instance($courseid);
5028 $fs = get_file_storage();
5030 // Delete course completion information, this has to be done before grades and enrols.
5031 $cc = new completion_info($course);
5032 $cc->clear_criteria();
5033 if ($showfeedback) {
5034 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5037 // Remove all data from gradebook - this needs to be done before course modules
5038 // because while deleting this information, the system may need to reference
5039 // the course modules that own the grades.
5040 remove_course_grades($courseid, $showfeedback);
5041 remove_grade_letters($coursecontext, $showfeedback);
5043 // Delete course blocks in any all child contexts,
5044 // they may depend on modules so delete them first.
5045 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5046 foreach ($childcontexts as $childcontext) {
5047 blocks_delete_all_for_context($childcontext->id);
5049 unset($childcontexts);
5050 blocks_delete_all_for_context($coursecontext->id);
5051 if ($showfeedback) {
5052 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5055 // Get the list of all modules that are properly installed.
5056 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5058 // Delete every instance of every module,
5059 // this has to be done before deleting of course level stuff.
5060 $locations = core_component::get_plugin_list('mod');
5061 foreach ($locations as $modname => $moddir) {
5062 if ($modname === 'NEWMODULE') {
5063 continue;
5065 if (array_key_exists($modname, $allmodules)) {
5066 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5067 FROM {".$modname."} m
5068 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5069 WHERE m.course = :courseid";
5070 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5071 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5073 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5074 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5076 if ($instances) {
5077 foreach ($instances as $cm) {
5078 if ($cm->id) {
5079 // Delete activity context questions and question categories.
5080 question_delete_activity($cm, $showfeedback);
5081 // Notify the competency subsystem.
5082 \core_competency\api::hook_course_module_deleted($cm);
5084 if (function_exists($moddelete)) {
5085 // This purges all module data in related tables, extra user prefs, settings, etc.
5086 $moddelete($cm->modinstance);
5087 } else {
5088 // NOTE: we should not allow installation of modules with missing delete support!
5089 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5090 $DB->delete_records($modname, array('id' => $cm->modinstance));
5093 if ($cm->id) {
5094 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5095 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5096 $DB->delete_records('course_modules', array('id' => $cm->id));
5100 if ($instances and $showfeedback) {
5101 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5103 } else {
5104 // Ooops, this module is not properly installed, force-delete it in the next block.
5108 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5110 // Delete completion defaults.
5111 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5113 // Remove all data from availability and completion tables that is associated
5114 // with course-modules belonging to this course. Note this is done even if the
5115 // features are not enabled now, in case they were enabled previously.
5116 $DB->delete_records_select('course_modules_completion',
5117 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5118 array($courseid));
5120 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5121 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5122 $allmodulesbyid = array_flip($allmodules);
5123 foreach ($cms as $cm) {
5124 if (array_key_exists($cm->module, $allmodulesbyid)) {
5125 try {
5126 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5127 } catch (Exception $e) {
5128 // Ignore weird or missing table problems.
5131 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5132 $DB->delete_records('course_modules', array('id' => $cm->id));
5135 if ($showfeedback) {
5136 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5139 // Delete questions and question categories.
5140 question_delete_course($course, $showfeedback);
5141 if ($showfeedback) {
5142 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5145 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5146 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5147 foreach ($childcontexts as $childcontext) {
5148 $childcontext->delete();
5150 unset($childcontexts);
5152 // Remove all roles and enrolments by default.
5153 if (empty($options['keep_roles_and_enrolments'])) {
5154 // This hack is used in restore when deleting contents of existing course.
5155 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5156 enrol_course_delete($course);
5157 if ($showfeedback) {
5158 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5162 // Delete any groups, removing members and grouping/course links first.
5163 if (empty($options['keep_groups_and_groupings'])) {
5164 groups_delete_groupings($course->id, $showfeedback);
5165 groups_delete_groups($course->id, $showfeedback);
5168 // Filters be gone!
5169 filter_delete_all_for_context($coursecontext->id);
5171 // Notes, you shall not pass!
5172 note_delete_all($course->id);
5174 // Die comments!
5175 comment::delete_comments($coursecontext->id);
5177 // Ratings are history too.
5178 $delopt = new stdclass();
5179 $delopt->contextid = $coursecontext->id;
5180 $rm = new rating_manager();
5181 $rm->delete_ratings($delopt);
5183 // Delete course tags.
5184 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5186 // Notify the competency subsystem.
5187 \core_competency\api::hook_course_deleted($course);
5189 // Delete calendar events.
5190 $DB->delete_records('event', array('courseid' => $course->id));
5191 $fs->delete_area_files($coursecontext->id, 'calendar');
5193 // Delete all related records in other core tables that may have a courseid
5194 // This array stores the tables that need to be cleared, as
5195 // table_name => column_name that contains the course id.
5196 $tablestoclear = array(
5197 'backup_courses' => 'courseid', // Scheduled backup stuff.
5198 'user_lastaccess' => 'courseid', // User access info.
5200 foreach ($tablestoclear as $table => $col) {
5201 $DB->delete_records($table, array($col => $course->id));
5204 // Delete all course backup files.
5205 $fs->delete_area_files($coursecontext->id, 'backup');
5207 // Cleanup course record - remove links to deleted stuff.
5208 $oldcourse = new stdClass();
5209 $oldcourse->id = $course->id;
5210 $oldcourse->summary = '';
5211 $oldcourse->cacherev = 0;
5212 $oldcourse->legacyfiles = 0;
5213 if (!empty($options['keep_groups_and_groupings'])) {
5214 $oldcourse->defaultgroupingid = 0;
5216 $DB->update_record('course', $oldcourse);
5218 // Delete course sections.
5219 $DB->delete_records('course_sections', array('course' => $course->id));
5221 // Delete legacy, section and any other course files.
5222 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5224 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5225 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5226 // Easy, do not delete the context itself...
5227 $coursecontext->delete_content();
5228 } else {
5229 // Hack alert!!!!
5230 // We can not drop all context stuff because it would bork enrolments and roles,
5231 // there might be also files used by enrol plugins...
5234 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5235 // also some non-standard unsupported plugins may try to store something there.
5236 fulldelete($CFG->dataroot.'/'.$course->id);
5238 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5239 $cachemodinfo = cache::make('core', 'coursemodinfo');
5240 $cachemodinfo->delete($courseid);
5242 // Trigger a course content deleted event.
5243 $event = \core\event\course_content_deleted::create(array(
5244 'objectid' => $course->id,
5245 'context' => $coursecontext,
5246 'other' => array('shortname' => $course->shortname,
5247 'fullname' => $course->fullname,
5248 'options' => $options) // Passing this for legacy reasons.
5250 $event->add_record_snapshot('course', $course);
5251 $event->trigger();
5253 return true;
5257 * Change dates in module - used from course reset.
5259 * @param string $modname forum, assignment, etc
5260 * @param array $fields array of date fields from mod table
5261 * @param int $timeshift time difference
5262 * @param int $courseid
5263 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5264 * @return bool success
5266 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5267 global $CFG, $DB;
5268 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5270 $return = true;
5271 $params = array($timeshift, $courseid);
5272 foreach ($fields as $field) {
5273 $updatesql = "UPDATE {".$modname."}
5274 SET $field = $field + ?
5275 WHERE course=? AND $field<>0";
5276 if ($modid) {
5277 $updatesql .= ' AND id=?';
5278 $params[] = $modid;
5280 $return = $DB->execute($updatesql, $params) && $return;
5283 return $return;
5287 * This function will empty a course of user data.
5288 * It will retain the activities and the structure of the course.
5290 * @param object $data an object containing all the settings including courseid (without magic quotes)
5291 * @return array status array of array component, item, error
5293 function reset_course_userdata($data) {
5294 global $CFG, $DB;
5295 require_once($CFG->libdir.'/gradelib.php');
5296 require_once($CFG->libdir.'/completionlib.php');
5297 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5298 require_once($CFG->dirroot.'/group/lib.php');
5300 $data->courseid = $data->id;
5301 $context = context_course::instance($data->courseid);
5303 $eventparams = array(
5304 'context' => $context,
5305 'courseid' => $data->id,
5306 'other' => array(
5307 'reset_options' => (array) $data
5310 $event = \core\event\course_reset_started::create($eventparams);
5311 $event->trigger();
5313 // Calculate the time shift of dates.
5314 if (!empty($data->reset_start_date)) {
5315 // Time part of course startdate should be zero.
5316 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5317 } else {
5318 $data->timeshift = 0;
5321 // Result array: component, item, error.
5322 $status = array();
5324 // Start the resetting.
5325 $componentstr = get_string('general');
5327 // Move the course start time.
5328 if (!empty($data->reset_start_date) and $data->timeshift) {
5329 // Change course start data.
5330 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5331 // Update all course and group events - do not move activity events.
5332 $updatesql = "UPDATE {event}
5333 SET timestart = timestart + ?
5334 WHERE courseid=? AND instance=0";
5335 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5337 // Update any date activity restrictions.
5338 if ($CFG->enableavailability) {
5339 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5342 // Update completion expected dates.
5343 if ($CFG->enablecompletion) {
5344 $modinfo = get_fast_modinfo($data->courseid);
5345 $changed = false;
5346 foreach ($modinfo->get_cms() as $cm) {
5347 if ($cm->completion && !empty($cm->completionexpected)) {
5348 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5349 array('id' => $cm->id));
5350 $changed = true;
5354 // Clear course cache if changes made.
5355 if ($changed) {
5356 rebuild_course_cache($data->courseid, true);
5359 // Update course date completion criteria.
5360 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5363 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5366 if (!empty($data->reset_end_date)) {
5367 // If the user set a end date value respect it.
5368 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5369 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5370 // If there is a time shift apply it to the end date as well.
5371 $enddate = $data->reset_end_date_old + $data->timeshift;
5372 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5375 if (!empty($data->reset_events)) {
5376 $DB->delete_records('event', array('courseid' => $data->courseid));
5377 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5380 if (!empty($data->reset_notes)) {
5381 require_once($CFG->dirroot.'/notes/lib.php');
5382 note_delete_all($data->courseid);
5383 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5386 if (!empty($data->delete_blog_associations)) {
5387 require_once($CFG->dirroot.'/blog/lib.php');
5388 blog_remove_associations_for_course($data->courseid);
5389 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5392 if (!empty($data->reset_completion)) {
5393 // Delete course and activity completion information.
5394 $course = $DB->get_record('course', array('id' => $data->courseid));
5395 $cc = new completion_info($course);
5396 $cc->delete_all_completion_data();
5397 $status[] = array('component' => $componentstr,
5398 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5401 if (!empty($data->reset_competency_ratings)) {
5402 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5403 $status[] = array('component' => $componentstr,
5404 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5407 $componentstr = get_string('roles');
5409 if (!empty($data->reset_roles_overrides)) {
5410 $children = $context->get_child_contexts();
5411 foreach ($children as $child) {
5412 $child->delete_capabilities();
5414 $context->delete_capabilities();
5415 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5418 if (!empty($data->reset_roles_local)) {
5419 $children = $context->get_child_contexts();
5420 foreach ($children as $child) {
5421 role_unassign_all(array('contextid' => $child->id));
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 foreach ($data->unenrol_users as $withroleid) {
5439 if ($withroleid) {
5440 $sql = "SELECT ue.*
5441 FROM {user_enrolments} ue
5442 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5443 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5444 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5445 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5447 } else {
5448 // Without any role assigned at course context.
5449 $sql = "SELECT ue.*
5450 FROM {user_enrolments} ue
5451 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5452 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5453 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5454 WHERE ra.id IS null";
5455 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5458 $rs = $DB->get_recordset_sql($sql, $params);
5459 foreach ($rs as $ue) {
5460 if (!isset($instances[$ue->enrolid])) {
5461 continue;
5463 $instance = $instances[$ue->enrolid];
5464 $plugin = $plugins[$instance->enrol];
5465 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5466 continue;
5469 $plugin->unenrol_user($instance, $ue->userid);
5470 $data->unenrolled[$ue->userid] = $ue->userid;
5472 $rs->close();
5475 if (!empty($data->unenrolled)) {
5476 $status[] = array(
5477 'component' => $componentstr,
5478 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5479 'error' => false
5483 $componentstr = get_string('groups');
5485 // Remove all group members.
5486 if (!empty($data->reset_groups_members)) {
5487 groups_delete_group_members($data->courseid);
5488 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5491 // Remove all groups.
5492 if (!empty($data->reset_groups_remove)) {
5493 groups_delete_groups($data->courseid, false);
5494 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5497 // Remove all grouping members.
5498 if (!empty($data->reset_groupings_members)) {
5499 groups_delete_groupings_groups($data->courseid, false);
5500 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5503 // Remove all groupings.
5504 if (!empty($data->reset_groupings_remove)) {
5505 groups_delete_groupings($data->courseid, false);
5506 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5509 // Look in every instance of every module for data to delete.
5510 $unsupportedmods = array();
5511 if ($allmods = $DB->get_records('modules') ) {
5512 foreach ($allmods as $mod) {
5513 $modname = $mod->name;
5514 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5515 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5516 if (file_exists($modfile)) {
5517 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5518 continue; // Skip mods with no instances.
5520 include_once($modfile);
5521 if (function_exists($moddeleteuserdata)) {
5522 $modstatus = $moddeleteuserdata($data);
5523 if (is_array($modstatus)) {
5524 $status = array_merge($status, $modstatus);
5525 } else {
5526 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5528 } else {
5529 $unsupportedmods[] = $mod;
5531 } else {
5532 debugging('Missing lib.php in '.$modname.' module!');
5534 // Update calendar events for all modules.
5535 course_module_bulk_update_calendar_events($modname, $data->courseid);
5539 // Mention unsupported mods.
5540 if (!empty($unsupportedmods)) {
5541 foreach ($unsupportedmods as $mod) {
5542 $status[] = array(
5543 'component' => get_string('modulenameplural', $mod->name),
5544 'item' => '',
5545 'error' => get_string('resetnotimplemented')
5550 $componentstr = get_string('gradebook', 'grades');
5551 // Reset gradebook,.
5552 if (!empty($data->reset_gradebook_items)) {
5553 remove_course_grades($data->courseid, false);
5554 grade_grab_course_grades($data->courseid);
5555 grade_regrade_final_grades($data->courseid);
5556 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5558 } else if (!empty($data->reset_gradebook_grades)) {
5559 grade_course_reset($data->courseid);
5560 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5562 // Reset comments.
5563 if (!empty($data->reset_comments)) {
5564 require_once($CFG->dirroot.'/comment/lib.php');
5565 comment::reset_course_page_comments($context);
5568 $event = \core\event\course_reset_ended::create($eventparams);
5569 $event->trigger();
5571 return $status;
5575 * Generate an email processing address.
5577 * @param int $modid
5578 * @param string $modargs
5579 * @return string Returns email processing address
5581 function generate_email_processing_address($modid, $modargs) {
5582 global $CFG;
5584 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5585 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5591 * @todo Finish documenting this function
5593 * @param string $modargs
5594 * @param string $body Currently unused
5596 function moodle_process_email($modargs, $body) {
5597 global $DB;
5599 // The first char should be an unencoded letter. We'll take this as an action.
5600 switch ($modargs{0}) {
5601 case 'B': { // Bounce.
5602 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5603 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5604 // Check the half md5 of their email.
5605 $md5check = substr(md5($user->email), 0, 16);
5606 if ($md5check == substr($modargs, -16)) {
5607 set_bounce_count($user);
5609 // Else maybe they've already changed it?
5612 break;
5613 // Maybe more later?
5617 // CORRESPONDENCE.
5620 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5622 * @param string $action 'get', 'buffer', 'close' or 'flush'
5623 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5625 function get_mailer($action='get') {
5626 global $CFG;
5628 /** @var moodle_phpmailer $mailer */
5629 static $mailer = null;
5630 static $counter = 0;
5632 if (!isset($CFG->smtpmaxbulk)) {
5633 $CFG->smtpmaxbulk = 1;
5636 if ($action == 'get') {
5637 $prevkeepalive = false;
5639 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5640 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5641 $counter++;
5642 // Reset the mailer.
5643 $mailer->Priority = 3;
5644 $mailer->CharSet = 'UTF-8'; // Our default.
5645 $mailer->ContentType = "text/plain";
5646 $mailer->Encoding = "8bit";
5647 $mailer->From = "root@localhost";
5648 $mailer->FromName = "Root User";
5649 $mailer->Sender = "";
5650 $mailer->Subject = "";
5651 $mailer->Body = "";
5652 $mailer->AltBody = "";
5653 $mailer->ConfirmReadingTo = "";
5655 $mailer->clearAllRecipients();
5656 $mailer->clearReplyTos();
5657 $mailer->clearAttachments();
5658 $mailer->clearCustomHeaders();
5659 return $mailer;
5662 $prevkeepalive = $mailer->SMTPKeepAlive;
5663 get_mailer('flush');
5666 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5667 $mailer = new moodle_phpmailer();
5669 $counter = 1;
5671 if ($CFG->smtphosts == 'qmail') {
5672 // Use Qmail system.
5673 $mailer->isQmail();
5675 } else if (empty($CFG->smtphosts)) {
5676 // Use PHP mail() = sendmail.
5677 $mailer->isMail();
5679 } else {
5680 // Use SMTP directly.
5681 $mailer->isSMTP();
5682 if (!empty($CFG->debugsmtp)) {
5683 $mailer->SMTPDebug = 3;
5685 // Specify main and backup servers.
5686 $mailer->Host = $CFG->smtphosts;
5687 // Specify secure connection protocol.
5688 $mailer->SMTPSecure = $CFG->smtpsecure;
5689 // Use previous keepalive.
5690 $mailer->SMTPKeepAlive = $prevkeepalive;
5692 if ($CFG->smtpuser) {
5693 // Use SMTP authentication.
5694 $mailer->SMTPAuth = true;
5695 $mailer->Username = $CFG->smtpuser;
5696 $mailer->Password = $CFG->smtppass;
5700 return $mailer;
5703 $nothing = null;
5705 // Keep smtp session open after sending.
5706 if ($action == 'buffer') {
5707 if (!empty($CFG->smtpmaxbulk)) {
5708 get_mailer('flush');
5709 $m = get_mailer();
5710 if ($m->Mailer == 'smtp') {
5711 $m->SMTPKeepAlive = true;
5714 return $nothing;
5717 // Close smtp session, but continue buffering.
5718 if ($action == 'flush') {
5719 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5720 if (!empty($mailer->SMTPDebug)) {
5721 echo '<pre>'."\n";
5723 $mailer->SmtpClose();
5724 if (!empty($mailer->SMTPDebug)) {
5725 echo '</pre>';
5728 return $nothing;
5731 // Close smtp session, do not buffer anymore.
5732 if ($action == 'close') {
5733 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5734 get_mailer('flush');
5735 $mailer->SMTPKeepAlive = false;
5737 $mailer = null; // Better force new instance.
5738 return $nothing;
5743 * A helper function to test for email diversion
5745 * @param string $email
5746 * @return bool Returns true if the email should be diverted
5748 function email_should_be_diverted($email) {
5749 global $CFG;
5751 if (empty($CFG->divertallemailsto)) {
5752 return false;
5755 if (empty($CFG->divertallemailsexcept)) {
5756 return true;
5759 $patterns = array_map('trim', explode(',', $CFG->divertallemailsexcept));
5760 foreach ($patterns as $pattern) {
5761 if (preg_match("/$pattern/", $email)) {
5762 return false;
5766 return true;
5770 * Generate a unique email Message-ID using the moodle domain and install path
5772 * @param string $localpart An optional unique message id prefix.
5773 * @return string The formatted ID ready for appending to the email headers.
5775 function generate_email_messageid($localpart = null) {
5776 global $CFG;
5778 $urlinfo = parse_url($CFG->wwwroot);
5779 $base = '@' . $urlinfo['host'];
5781 // If multiple moodles are on the same domain we want to tell them
5782 // apart so we add the install path to the local part. This means
5783 // that the id local part should never contain a / character so
5784 // we can correctly parse the id to reassemble the wwwroot.
5785 if (isset($urlinfo['path'])) {
5786 $base = $urlinfo['path'] . $base;
5789 if (empty($localpart)) {
5790 $localpart = uniqid('', true);
5793 // Because we may have an option /installpath suffix to the local part
5794 // of the id we need to escape any / chars which are in the $localpart.
5795 $localpart = str_replace('/', '%2F', $localpart);
5797 return '<' . $localpart . $base . '>';
5801 * Send an email to a specified user
5803 * @param stdClass $user A {@link $USER} object
5804 * @param stdClass $from A {@link $USER} object
5805 * @param string $subject plain text subject line of the email
5806 * @param string $messagetext plain text version of the message
5807 * @param string $messagehtml complete html version of the message (optional)
5808 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5809 * @param string $attachname the name of the file (extension indicates MIME)
5810 * @param bool $usetrueaddress determines whether $from email address should
5811 * be sent out. Will be overruled by user profile setting for maildisplay
5812 * @param string $replyto Email address to reply to
5813 * @param string $replytoname Name of reply to recipient
5814 * @param int $wordwrapwidth custom word wrap width, default 79
5815 * @return bool Returns true if mail was sent OK and false if there was an error.
5817 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5818 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5820 global $CFG, $PAGE, $SITE;
5822 if (empty($user) or empty($user->id)) {
5823 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5824 return false;
5827 if (empty($user->email)) {
5828 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5829 return false;
5832 if (!empty($user->deleted)) {
5833 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5834 return false;
5837 if (defined('BEHAT_SITE_RUNNING')) {
5838 // Fake email sending in behat.
5839 return true;
5842 if (!empty($CFG->noemailever)) {
5843 // Hidden setting for development sites, set in config.php if needed.
5844 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5845 return true;
5848 if (email_should_be_diverted($user->email)) {
5849 $subject = "[DIVERTED {$user->email}] $subject";
5850 $user = clone($user);
5851 $user->email = $CFG->divertallemailsto;
5854 // Skip mail to suspended users.
5855 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5856 return true;
5859 if (!validate_email($user->email)) {
5860 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5861 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5862 return false;
5865 if (over_bounce_threshold($user)) {
5866 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5867 return false;
5870 // TLD .invalid is specifically reserved for invalid domain names.
5871 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5872 if (substr($user->email, -8) == '.invalid') {
5873 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5874 return true; // This is not an error.
5877 // If the user is a remote mnet user, parse the email text for URL to the
5878 // wwwroot and modify the url to direct the user's browser to login at their
5879 // home site (identity provider - idp) before hitting the link itself.
5880 if (is_mnet_remote_user($user)) {
5881 require_once($CFG->dirroot.'/mnet/lib.php');
5883 $jumpurl = mnet_get_idp_jump_url($user);
5884 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5886 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5887 $callback,
5888 $messagetext);
5889 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5890 $callback,
5891 $messagehtml);
5893 $mail = get_mailer();
5895 if (!empty($mail->SMTPDebug)) {
5896 echo '<pre>' . "\n";
5899 $temprecipients = array();
5900 $tempreplyto = array();
5902 // Make sure that we fall back onto some reasonable no-reply address.
5903 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
5904 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
5906 if (!validate_email($noreplyaddress)) {
5907 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
5908 $noreplyaddress = $noreplyaddressdefault;
5911 // Make up an email address for handling bounces.
5912 if (!empty($CFG->handlebounces)) {
5913 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5914 $mail->Sender = generate_email_processing_address(0, $modargs);
5915 } else {
5916 $mail->Sender = $noreplyaddress;
5919 // Make sure that the explicit replyto is valid, fall back to the implicit one.
5920 if (!empty($replyto) && !validate_email($replyto)) {
5921 debugging('email_to_user: Invalid replyto-email '.s($replyto));
5922 $replyto = $noreplyaddress;
5925 if (is_string($from)) { // So we can pass whatever we want if there is need.
5926 $mail->From = $noreplyaddress;
5927 $mail->FromName = $from;
5928 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
5929 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
5930 // in a course with the sender.
5931 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
5932 if (!validate_email($from->email)) {
5933 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
5934 // Better not to use $noreplyaddress in this case.
5935 return false;
5937 $mail->From = $from->email;
5938 $fromdetails = new stdClass();
5939 $fromdetails->name = fullname($from);
5940 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5941 $fromdetails->siteshortname = format_string($SITE->shortname);
5942 $fromstring = $fromdetails->name;
5943 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
5944 $fromstring = get_string('emailvia', 'core', $fromdetails);
5946 $mail->FromName = $fromstring;
5947 if (empty($replyto)) {
5948 $tempreplyto[] = array($from->email, fullname($from));
5950 } else {
5951 $mail->From = $noreplyaddress;
5952 $fromdetails = new stdClass();
5953 $fromdetails->name = fullname($from);
5954 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5955 $fromdetails->siteshortname = format_string($SITE->shortname);
5956 $fromstring = $fromdetails->name;
5957 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
5958 $fromstring = get_string('emailvia', 'core', $fromdetails);
5960 $mail->FromName = $fromstring;
5961 if (empty($replyto)) {
5962 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
5966 if (!empty($replyto)) {
5967 $tempreplyto[] = array($replyto, $replytoname);
5970 $temprecipients[] = array($user->email, fullname($user));
5972 // Set word wrap.
5973 $mail->WordWrap = $wordwrapwidth;
5975 if (!empty($from->customheaders)) {
5976 // Add custom headers.
5977 if (is_array($from->customheaders)) {
5978 foreach ($from->customheaders as $customheader) {
5979 $mail->addCustomHeader($customheader);
5981 } else {
5982 $mail->addCustomHeader($from->customheaders);
5986 // If the X-PHP-Originating-Script email header is on then also add an additional
5987 // header with details of where exactly in moodle the email was triggered from,
5988 // either a call to message_send() or to email_to_user().
5989 if (ini_get('mail.add_x_header')) {
5991 $stack = debug_backtrace(false);
5992 $origin = $stack[0];
5994 foreach ($stack as $depth => $call) {
5995 if ($call['function'] == 'message_send') {
5996 $origin = $call;
6000 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
6001 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
6002 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
6005 if (!empty($from->priority)) {
6006 $mail->Priority = $from->priority;
6009 $renderer = $PAGE->get_renderer('core');
6010 $context = array(
6011 'sitefullname' => $SITE->fullname,
6012 'siteshortname' => $SITE->shortname,
6013 'sitewwwroot' => $CFG->wwwroot,
6014 'subject' => $subject,
6015 'to' => $user->email,
6016 'toname' => fullname($user),
6017 'from' => $mail->From,
6018 'fromname' => $mail->FromName,
6020 if (!empty($tempreplyto[0])) {
6021 $context['replyto'] = $tempreplyto[0][0];
6022 $context['replytoname'] = $tempreplyto[0][1];
6024 if ($user->id > 0) {
6025 $context['touserid'] = $user->id;
6026 $context['tousername'] = $user->username;
6029 if (!empty($user->mailformat) && $user->mailformat == 1) {
6030 // Only process html templates if the user preferences allow html email.
6032 if ($messagehtml) {
6033 // If html has been given then pass it through the template.
6034 $context['body'] = $messagehtml;
6035 $messagehtml = $renderer->render_from_template('core/email_html', $context);
6037 } else {
6038 // If no html has been given, BUT there is an html wrapping template then
6039 // auto convert the text to html and then wrap it.
6040 $autohtml = trim(text_to_html($messagetext));
6041 $context['body'] = $autohtml;
6042 $temphtml = $renderer->render_from_template('core/email_html', $context);
6043 if ($autohtml != $temphtml) {
6044 $messagehtml = $temphtml;
6049 $context['body'] = $messagetext;
6050 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
6051 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
6052 $messagetext = $renderer->render_from_template('core/email_text', $context);
6054 // Autogenerate a MessageID if it's missing.
6055 if (empty($mail->MessageID)) {
6056 $mail->MessageID = generate_email_messageid();
6059 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6060 // Don't ever send HTML to users who don't want it.
6061 $mail->isHTML(true);
6062 $mail->Encoding = 'quoted-printable';
6063 $mail->Body = $messagehtml;
6064 $mail->AltBody = "\n$messagetext\n";
6065 } else {
6066 $mail->IsHTML(false);
6067 $mail->Body = "\n$messagetext\n";
6070 if ($attachment && $attachname) {
6071 if (preg_match( "~\\.\\.~" , $attachment )) {
6072 // Security check for ".." in dir path.
6073 $supportuser = core_user::get_support_user();
6074 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6075 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6076 } else {
6077 require_once($CFG->libdir.'/filelib.php');
6078 $mimetype = mimeinfo('type', $attachname);
6080 $attachmentpath = $attachment;
6082 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6083 $attachpath = str_replace('\\', '/', $attachmentpath);
6084 // Make sure both variables are normalised before comparing.
6085 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
6087 // If the attachment is a full path to a file in the tempdir, use it as is,
6088 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6089 if (strpos($attachpath, $temppath) !== 0) {
6090 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
6093 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
6097 // Check if the email should be sent in an other charset then the default UTF-8.
6098 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6100 // Use the defined site mail charset or eventually the one preferred by the recipient.
6101 $charset = $CFG->sitemailcharset;
6102 if (!empty($CFG->allowusermailcharset)) {
6103 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6104 $charset = $useremailcharset;
6108 // Convert all the necessary strings if the charset is supported.
6109 $charsets = get_list_of_charsets();
6110 unset($charsets['UTF-8']);
6111 if (in_array($charset, $charsets)) {
6112 $mail->CharSet = $charset;
6113 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6114 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6115 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6116 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6118 foreach ($temprecipients as $key => $values) {
6119 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6121 foreach ($tempreplyto as $key => $values) {
6122 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6127 foreach ($temprecipients as $values) {
6128 $mail->addAddress($values[0], $values[1]);
6130 foreach ($tempreplyto as $values) {
6131 $mail->addReplyTo($values[0], $values[1]);
6134 if ($mail->send()) {
6135 set_send_count($user);
6136 if (!empty($mail->SMTPDebug)) {
6137 echo '</pre>';
6139 return true;
6140 } else {
6141 // Trigger event for failing to send email.
6142 $event = \core\event\email_failed::create(array(
6143 'context' => context_system::instance(),
6144 'userid' => $from->id,
6145 'relateduserid' => $user->id,
6146 'other' => array(
6147 'subject' => $subject,
6148 'message' => $messagetext,
6149 'errorinfo' => $mail->ErrorInfo
6152 $event->trigger();
6153 if (CLI_SCRIPT) {
6154 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6156 if (!empty($mail->SMTPDebug)) {
6157 echo '</pre>';
6159 return false;
6164 * Check to see if a user's real email address should be used for the "From" field.
6166 * @param object $from The user object for the user we are sending the email from.
6167 * @param object $user The user object that we are sending the email to.
6168 * @param array $unused No longer used.
6169 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6171 function can_send_from_real_email_address($from, $user, $unused = null) {
6172 global $CFG;
6173 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6174 return false;
6176 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6177 // Email is in the list of allowed domains for sending email,
6178 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6179 // in a course with the sender.
6180 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6181 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6182 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6183 && enrol_get_shared_courses($user, $from, false, true)))) {
6184 return true;
6186 return false;
6190 * Generate a signoff for emails based on support settings
6192 * @return string
6194 function generate_email_signoff() {
6195 global $CFG;
6197 $signoff = "\n";
6198 if (!empty($CFG->supportname)) {
6199 $signoff .= $CFG->supportname."\n";
6201 if (!empty($CFG->supportemail)) {
6202 $signoff .= $CFG->supportemail."\n";
6204 if (!empty($CFG->supportpage)) {
6205 $signoff .= $CFG->supportpage."\n";
6207 return $signoff;
6211 * Sets specified user's password and send the new password to the user via email.
6213 * @param stdClass $user A {@link $USER} object
6214 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6215 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6217 function setnew_password_and_mail($user, $fasthash = false) {
6218 global $CFG, $DB;
6220 // We try to send the mail in language the user understands,
6221 // unfortunately the filter_string() does not support alternative langs yet
6222 // so multilang will not work properly for site->fullname.
6223 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6225 $site = get_site();
6227 $supportuser = core_user::get_support_user();
6229 $newpassword = generate_password();
6231 update_internal_user_password($user, $newpassword, $fasthash);
6233 $a = new stdClass();
6234 $a->firstname = fullname($user, true);
6235 $a->sitename = format_string($site->fullname);
6236 $a->username = $user->username;
6237 $a->newpassword = $newpassword;
6238 $a->link = $CFG->wwwroot .'/login/?lang='.$lang;
6239 $a->signoff = generate_email_signoff();
6241 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6243 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6245 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6246 return email_to_user($user, $supportuser, $subject, $message);
6251 * Resets specified user's password and send the new password to the user via email.
6253 * @param stdClass $user A {@link $USER} object
6254 * @return bool Returns true if mail was sent OK and false if there was an error.
6256 function reset_password_and_mail($user) {
6257 global $CFG;
6259 $site = get_site();
6260 $supportuser = core_user::get_support_user();
6262 $userauth = get_auth_plugin($user->auth);
6263 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6264 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6265 return false;
6268 $newpassword = generate_password();
6270 if (!$userauth->user_update_password($user, $newpassword)) {
6271 print_error("cannotsetpassword");
6274 $a = new stdClass();
6275 $a->firstname = $user->firstname;
6276 $a->lastname = $user->lastname;
6277 $a->sitename = format_string($site->fullname);
6278 $a->username = $user->username;
6279 $a->newpassword = $newpassword;
6280 $a->link = $CFG->wwwroot .'/login/change_password.php';
6281 $a->signoff = generate_email_signoff();
6283 $message = get_string('newpasswordtext', '', $a);
6285 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6287 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6289 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6290 return email_to_user($user, $supportuser, $subject, $message);
6294 * Send email to specified user with confirmation text and activation link.
6296 * @param stdClass $user A {@link $USER} object
6297 * @param string $confirmationurl user confirmation URL
6298 * @return bool Returns true if mail was sent OK and false if there was an error.
6300 function send_confirmation_email($user, $confirmationurl = null) {
6301 global $CFG;
6303 $site = get_site();
6304 $supportuser = core_user::get_support_user();
6306 $data = new stdClass();
6307 $data->firstname = fullname($user);
6308 $data->sitename = format_string($site->fullname);
6309 $data->admin = generate_email_signoff();
6311 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6313 if (empty($confirmationurl)) {
6314 $confirmationurl = '/login/confirm.php';
6317 $confirmationurl = new moodle_url($confirmationurl);
6318 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6319 $confirmationurl->remove_params('data');
6320 $confirmationpath = $confirmationurl->out(false);
6322 // We need to custom encode the username to include trailing dots in the link.
6323 // Because of this custom encoding we can't use moodle_url directly.
6324 // Determine if a query string is present in the confirmation url.
6325 $hasquerystring = strpos($confirmationpath, '?') !== false;
6326 // Perform normal url encoding of the username first.
6327 $username = urlencode($user->username);
6328 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6329 $username = str_replace('.', '%2E', $username);
6331 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6333 $message = get_string('emailconfirmation', '', $data);
6334 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6336 $user->mailformat = 1; // Always send HTML version as well.
6338 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6339 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6343 * Sends a password change confirmation email.
6345 * @param stdClass $user A {@link $USER} object
6346 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6347 * @return bool Returns true if mail was sent OK and false if there was an error.
6349 function send_password_change_confirmation_email($user, $resetrecord) {
6350 global $CFG;
6352 $site = get_site();
6353 $supportuser = core_user::get_support_user();
6354 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6356 $data = new stdClass();
6357 $data->firstname = $user->firstname;
6358 $data->lastname = $user->lastname;
6359 $data->username = $user->username;
6360 $data->sitename = format_string($site->fullname);
6361 $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6362 $data->admin = generate_email_signoff();
6363 $data->resetminutes = $pwresetmins;
6365 $message = get_string('emailresetconfirmation', '', $data);
6366 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6368 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6369 return email_to_user($user, $supportuser, $subject, $message);
6374 * Sends an email containinginformation on how to change your password.
6376 * @param stdClass $user A {@link $USER} object
6377 * @return bool Returns true if mail was sent OK and false if there was an error.
6379 function send_password_change_info($user) {
6380 global $CFG;
6382 $site = get_site();
6383 $supportuser = core_user::get_support_user();
6384 $systemcontext = context_system::instance();
6386 $data = new stdClass();
6387 $data->firstname = $user->firstname;
6388 $data->lastname = $user->lastname;
6389 $data->username = $user->username;
6390 $data->sitename = format_string($site->fullname);
6391 $data->admin = generate_email_signoff();
6393 $userauth = get_auth_plugin($user->auth);
6395 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6396 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6397 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6398 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6399 return email_to_user($user, $supportuser, $subject, $message);
6402 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6403 // We have some external url for password changing.
6404 $data->link .= $userauth->change_password_url();
6406 } else {
6407 // No way to change password, sorry.
6408 $data->link = '';
6411 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6412 $message = get_string('emailpasswordchangeinfo', '', $data);
6413 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6414 } else {
6415 $message = get_string('emailpasswordchangeinfofail', '', $data);
6416 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6419 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6420 return email_to_user($user, $supportuser, $subject, $message);
6425 * Check that an email is allowed. It returns an error message if there was a problem.
6427 * @param string $email Content of email
6428 * @return string|false
6430 function email_is_not_allowed($email) {
6431 global $CFG;
6433 if (!empty($CFG->allowemailaddresses)) {
6434 $allowed = explode(' ', $CFG->allowemailaddresses);
6435 foreach ($allowed as $allowedpattern) {
6436 $allowedpattern = trim($allowedpattern);
6437 if (!$allowedpattern) {
6438 continue;
6440 if (strpos($allowedpattern, '.') === 0) {
6441 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6442 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6443 return false;
6446 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6447 return false;
6450 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6452 } else if (!empty($CFG->denyemailaddresses)) {
6453 $denied = explode(' ', $CFG->denyemailaddresses);
6454 foreach ($denied as $deniedpattern) {
6455 $deniedpattern = trim($deniedpattern);
6456 if (!$deniedpattern) {
6457 continue;
6459 if (strpos($deniedpattern, '.') === 0) {
6460 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6461 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6462 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6465 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6466 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6471 return false;
6474 // FILE HANDLING.
6477 * Returns local file storage instance
6479 * @return file_storage
6481 function get_file_storage($reset = false) {
6482 global $CFG;
6484 static $fs = null;
6486 if ($reset) {
6487 $fs = null;
6488 return;
6491 if ($fs) {
6492 return $fs;
6495 require_once("$CFG->libdir/filelib.php");
6497 $fs = new file_storage();
6499 return $fs;
6503 * Returns local file storage instance
6505 * @return file_browser
6507 function get_file_browser() {
6508 global $CFG;
6510 static $fb = null;
6512 if ($fb) {
6513 return $fb;
6516 require_once("$CFG->libdir/filelib.php");
6518 $fb = new file_browser();
6520 return $fb;
6524 * Returns file packer
6526 * @param string $mimetype default application/zip
6527 * @return file_packer
6529 function get_file_packer($mimetype='application/zip') {
6530 global $CFG;
6532 static $fp = array();
6534 if (isset($fp[$mimetype])) {
6535 return $fp[$mimetype];
6538 switch ($mimetype) {
6539 case 'application/zip':
6540 case 'application/vnd.moodle.profiling':
6541 $classname = 'zip_packer';
6542 break;
6544 case 'application/x-gzip' :
6545 $classname = 'tgz_packer';
6546 break;
6548 case 'application/vnd.moodle.backup':
6549 $classname = 'mbz_packer';
6550 break;
6552 default:
6553 return false;
6556 require_once("$CFG->libdir/filestorage/$classname.php");
6557 $fp[$mimetype] = new $classname();
6559 return $fp[$mimetype];
6563 * Returns current name of file on disk if it exists.
6565 * @param string $newfile File to be verified
6566 * @return string Current name of file on disk if true
6568 function valid_uploaded_file($newfile) {
6569 if (empty($newfile)) {
6570 return '';
6572 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6573 return $newfile['tmp_name'];
6574 } else {
6575 return '';
6580 * Returns the maximum size for uploading files.
6582 * There are seven possible upload limits:
6583 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6584 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6585 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6586 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6587 * 5. by the Moodle admin in $CFG->maxbytes
6588 * 6. by the teacher in the current course $course->maxbytes
6589 * 7. by the teacher for the current module, eg $assignment->maxbytes
6591 * These last two are passed to this function as arguments (in bytes).
6592 * Anything defined as 0 is ignored.
6593 * The smallest of all the non-zero numbers is returned.
6595 * @todo Finish documenting this function
6597 * @param int $sitebytes Set maximum size
6598 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6599 * @param int $modulebytes Current module ->maxbytes (in bytes)
6600 * @param bool $unused This parameter has been deprecated and is not used any more.
6601 * @return int The maximum size for uploading files.
6603 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6605 if (! $filesize = ini_get('upload_max_filesize')) {
6606 $filesize = '5M';
6608 $minimumsize = get_real_size($filesize);
6610 if ($postsize = ini_get('post_max_size')) {
6611 $postsize = get_real_size($postsize);
6612 if ($postsize < $minimumsize) {
6613 $minimumsize = $postsize;
6617 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6618 $minimumsize = $sitebytes;
6621 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6622 $minimumsize = $coursebytes;
6625 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6626 $minimumsize = $modulebytes;
6629 return $minimumsize;
6633 * Returns the maximum size for uploading files for the current user
6635 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6637 * @param context $context The context in which to check user capabilities
6638 * @param int $sitebytes Set maximum size
6639 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6640 * @param int $modulebytes Current module ->maxbytes (in bytes)
6641 * @param stdClass $user The user
6642 * @param bool $unused This parameter has been deprecated and is not used any more.
6643 * @return int The maximum size for uploading files.
6645 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6646 $unused = false) {
6647 global $USER;
6649 if (empty($user)) {
6650 $user = $USER;
6653 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6654 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6657 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6661 * Returns an array of possible sizes in local language
6663 * Related to {@link get_max_upload_file_size()} - this function returns an
6664 * array of possible sizes in an array, translated to the
6665 * local language.
6667 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6669 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6670 * with the value set to 0. This option will be the first in the list.
6672 * @uses SORT_NUMERIC
6673 * @param int $sitebytes Set maximum size
6674 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6675 * @param int $modulebytes Current module ->maxbytes (in bytes)
6676 * @param int|array $custombytes custom upload size/s which will be added to list,
6677 * Only value/s smaller then maxsize will be added to list.
6678 * @return array
6680 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6681 global $CFG;
6683 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6684 return array();
6687 if ($sitebytes == 0) {
6688 // Will get the minimum of upload_max_filesize or post_max_size.
6689 $sitebytes = get_max_upload_file_size();
6692 $filesize = array();
6693 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6694 5242880, 10485760, 20971520, 52428800, 104857600,
6695 262144000, 524288000, 786432000, 1073741824,
6696 2147483648, 4294967296, 8589934592);
6698 // If custombytes is given and is valid then add it to the list.
6699 if (is_number($custombytes) and $custombytes > 0) {
6700 $custombytes = (int)$custombytes;
6701 if (!in_array($custombytes, $sizelist)) {
6702 $sizelist[] = $custombytes;
6704 } else if (is_array($custombytes)) {
6705 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6708 // Allow maxbytes to be selected if it falls outside the above boundaries.
6709 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6710 // Note: get_real_size() is used in order to prevent problems with invalid values.
6711 $sizelist[] = get_real_size($CFG->maxbytes);
6714 foreach ($sizelist as $sizebytes) {
6715 if ($sizebytes < $maxsize && $sizebytes > 0) {
6716 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6720 $limitlevel = '';
6721 $displaysize = '';
6722 if ($modulebytes &&
6723 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6724 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6725 $limitlevel = get_string('activity', 'core');
6726 $displaysize = display_size($modulebytes);
6727 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6729 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6730 $limitlevel = get_string('course', 'core');
6731 $displaysize = display_size($coursebytes);
6732 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6734 } else if ($sitebytes) {
6735 $limitlevel = get_string('site', 'core');
6736 $displaysize = display_size($sitebytes);
6737 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6740 krsort($filesize, SORT_NUMERIC);
6741 if ($limitlevel) {
6742 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6743 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6746 return $filesize;
6750 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6752 * If excludefiles is defined, then that file/directory is ignored
6753 * If getdirs is true, then (sub)directories are included in the output
6754 * If getfiles is true, then files are included in the output
6755 * (at least one of these must be true!)
6757 * @todo Finish documenting this function. Add examples of $excludefile usage.
6759 * @param string $rootdir A given root directory to start from
6760 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6761 * @param bool $descend If true then subdirectories are recursed as well
6762 * @param bool $getdirs If true then (sub)directories are included in the output
6763 * @param bool $getfiles If true then files are included in the output
6764 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6766 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6768 $dirs = array();
6770 if (!$getdirs and !$getfiles) { // Nothing to show.
6771 return $dirs;
6774 if (!is_dir($rootdir)) { // Must be a directory.
6775 return $dirs;
6778 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6779 return $dirs;
6782 if (!is_array($excludefiles)) {
6783 $excludefiles = array($excludefiles);
6786 while (false !== ($file = readdir($dir))) {
6787 $firstchar = substr($file, 0, 1);
6788 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6789 continue;
6791 $fullfile = $rootdir .'/'. $file;
6792 if (filetype($fullfile) == 'dir') {
6793 if ($getdirs) {
6794 $dirs[] = $file;
6796 if ($descend) {
6797 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6798 foreach ($subdirs as $subdir) {
6799 $dirs[] = $file .'/'. $subdir;
6802 } else if ($getfiles) {
6803 $dirs[] = $file;
6806 closedir($dir);
6808 asort($dirs);
6810 return $dirs;
6815 * Adds up all the files in a directory and works out the size.
6817 * @param string $rootdir The directory to start from
6818 * @param string $excludefile A file to exclude when summing directory size
6819 * @return int The summed size of all files and subfiles within the root directory
6821 function get_directory_size($rootdir, $excludefile='') {
6822 global $CFG;
6824 // Do it this way if we can, it's much faster.
6825 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6826 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6827 $output = null;
6828 $return = null;
6829 exec($command, $output, $return);
6830 if (is_array($output)) {
6831 // We told it to return k.
6832 return get_real_size(intval($output[0]).'k');
6836 if (!is_dir($rootdir)) {
6837 // Must be a directory.
6838 return 0;
6841 if (!$dir = @opendir($rootdir)) {
6842 // Can't open it for some reason.
6843 return 0;
6846 $size = 0;
6848 while (false !== ($file = readdir($dir))) {
6849 $firstchar = substr($file, 0, 1);
6850 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6851 continue;
6853 $fullfile = $rootdir .'/'. $file;
6854 if (filetype($fullfile) == 'dir') {
6855 $size += get_directory_size($fullfile, $excludefile);
6856 } else {
6857 $size += filesize($fullfile);
6860 closedir($dir);
6862 return $size;
6866 * Converts bytes into display form
6868 * @static string $gb Localized string for size in gigabytes
6869 * @static string $mb Localized string for size in megabytes
6870 * @static string $kb Localized string for size in kilobytes
6871 * @static string $b Localized string for size in bytes
6872 * @param int $size The size to convert to human readable form
6873 * @return string
6875 function display_size($size) {
6877 static $gb, $mb, $kb, $b;
6879 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6880 return get_string('unlimited');
6883 if (empty($gb)) {
6884 $gb = get_string('sizegb');
6885 $mb = get_string('sizemb');
6886 $kb = get_string('sizekb');
6887 $b = get_string('sizeb');
6890 if ($size >= 1073741824) {
6891 $size = round($size / 1073741824 * 10) / 10 . $gb;
6892 } else if ($size >= 1048576) {
6893 $size = round($size / 1048576 * 10) / 10 . $mb;
6894 } else if ($size >= 1024) {
6895 $size = round($size / 1024 * 10) / 10 . $kb;
6896 } else {
6897 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6899 return $size;
6903 * Cleans a given filename by removing suspicious or troublesome characters
6905 * @see clean_param()
6906 * @param string $string file name
6907 * @return string cleaned file name
6909 function clean_filename($string) {
6910 return clean_param($string, PARAM_FILE);
6913 // STRING TRANSLATION.
6916 * Returns the code for the current language
6918 * @category string
6919 * @return string
6921 function current_language() {
6922 global $CFG, $USER, $SESSION, $COURSE;
6924 if (!empty($SESSION->forcelang)) {
6925 // Allows overriding course-forced language (useful for admins to check
6926 // issues in courses whose language they don't understand).
6927 // Also used by some code to temporarily get language-related information in a
6928 // specific language (see force_current_language()).
6929 $return = $SESSION->forcelang;
6931 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6932 // Course language can override all other settings for this page.
6933 $return = $COURSE->lang;
6935 } else if (!empty($SESSION->lang)) {
6936 // Session language can override other settings.
6937 $return = $SESSION->lang;
6939 } else if (!empty($USER->lang)) {
6940 $return = $USER->lang;
6942 } else if (isset($CFG->lang)) {
6943 $return = $CFG->lang;
6945 } else {
6946 $return = 'en';
6949 // Just in case this slipped in from somewhere by accident.
6950 $return = str_replace('_utf8', '', $return);
6952 return $return;
6956 * Returns parent language of current active language if defined
6958 * @category string
6959 * @param string $lang null means current language
6960 * @return string
6962 function get_parent_language($lang=null) {
6964 // Let's hack around the current language.
6965 if (!empty($lang)) {
6966 $oldforcelang = force_current_language($lang);
6969 $parentlang = get_string('parentlanguage', 'langconfig');
6970 if ($parentlang === 'en') {
6971 $parentlang = '';
6974 // Let's hack around the current language.
6975 if (!empty($lang)) {
6976 force_current_language($oldforcelang);
6979 return $parentlang;
6983 * Force the current language to get strings and dates localised in the given language.
6985 * After calling this function, all strings will be provided in the given language
6986 * until this function is called again, or equivalent code is run.
6988 * @param string $language
6989 * @return string previous $SESSION->forcelang value
6991 function force_current_language($language) {
6992 global $SESSION;
6993 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6994 if ($language !== $sessionforcelang) {
6995 // Seting forcelang to null or an empty string disables it's effect.
6996 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6997 $SESSION->forcelang = $language;
6998 moodle_setlocale();
7001 return $sessionforcelang;
7005 * Returns current string_manager instance.
7007 * The param $forcereload is needed for CLI installer only where the string_manager instance
7008 * must be replaced during the install.php script life time.
7010 * @category string
7011 * @param bool $forcereload shall the singleton be released and new instance created instead?
7012 * @return core_string_manager
7014 function get_string_manager($forcereload=false) {
7015 global $CFG;
7017 static $singleton = null;
7019 if ($forcereload) {
7020 $singleton = null;
7022 if ($singleton === null) {
7023 if (empty($CFG->early_install_lang)) {
7025 if (empty($CFG->langlist)) {
7026 $translist = array();
7027 } else {
7028 $translist = explode(',', $CFG->langlist);
7029 $translist = array_map('trim', $translist);
7032 if (!empty($CFG->config_php_settings['customstringmanager'])) {
7033 $classname = $CFG->config_php_settings['customstringmanager'];
7035 if (class_exists($classname)) {
7036 $implements = class_implements($classname);
7038 if (isset($implements['core_string_manager'])) {
7039 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist);
7040 return $singleton;
7042 } else {
7043 debugging('Unable to instantiate custom string manager: class '.$classname.
7044 ' does not implement the core_string_manager interface.');
7047 } else {
7048 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7052 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
7054 } else {
7055 $singleton = new core_string_manager_install();
7059 return $singleton;
7063 * Returns a localized string.
7065 * Returns the translated string specified by $identifier as
7066 * for $module. Uses the same format files as STphp.
7067 * $a is an object, string or number that can be used
7068 * within translation strings
7070 * eg 'hello {$a->firstname} {$a->lastname}'
7071 * or 'hello {$a}'
7073 * If you would like to directly echo the localized string use
7074 * the function {@link print_string()}
7076 * Example usage of this function involves finding the string you would
7077 * like a local equivalent of and using its identifier and module information
7078 * to retrieve it.<br/>
7079 * If you open moodle/lang/en/moodle.php and look near line 278
7080 * you will find a string to prompt a user for their word for 'course'
7081 * <code>
7082 * $string['course'] = 'Course';
7083 * </code>
7084 * So if you want to display the string 'Course'
7085 * in any language that supports it on your site
7086 * you just need to use the identifier 'course'
7087 * <code>
7088 * $mystring = '<strong>'. get_string('course') .'</strong>';
7089 * or
7090 * </code>
7091 * If the string you want is in another file you'd take a slightly
7092 * different approach. Looking in moodle/lang/en/calendar.php you find
7093 * around line 75:
7094 * <code>
7095 * $string['typecourse'] = 'Course event';
7096 * </code>
7097 * If you want to display the string "Course event" in any language
7098 * supported you would use the identifier 'typecourse' and the module 'calendar'
7099 * (because it is in the file calendar.php):
7100 * <code>
7101 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7102 * </code>
7104 * As a last resort, should the identifier fail to map to a string
7105 * the returned string will be [[ $identifier ]]
7107 * In Moodle 2.3 there is a new argument to this function $lazyload.
7108 * Setting $lazyload to true causes get_string to return a lang_string object
7109 * rather than the string itself. The fetching of the string is then put off until
7110 * the string object is first used. The object can be used by calling it's out
7111 * method or by casting the object to a string, either directly e.g.
7112 * (string)$stringobject
7113 * or indirectly by using the string within another string or echoing it out e.g.
7114 * echo $stringobject
7115 * return "<p>{$stringobject}</p>";
7116 * It is worth noting that using $lazyload and attempting to use the string as an
7117 * array key will cause a fatal error as objects cannot be used as array keys.
7118 * But you should never do that anyway!
7119 * For more information {@link lang_string}
7121 * @category string
7122 * @param string $identifier The key identifier for the localized string
7123 * @param string $component The module where the key identifier is stored,
7124 * usually expressed as the filename in the language pack without the
7125 * .php on the end but can also be written as mod/forum or grade/export/xls.
7126 * If none is specified then moodle.php is used.
7127 * @param string|object|array $a An object, string or number that can be used
7128 * within translation strings
7129 * @param bool $lazyload If set to true a string object is returned instead of
7130 * the string itself. The string then isn't calculated until it is first used.
7131 * @return string The localized string.
7132 * @throws coding_exception
7134 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7135 global $CFG;
7137 // If the lazy load argument has been supplied return a lang_string object
7138 // instead.
7139 // We need to make sure it is true (and a bool) as you will see below there
7140 // used to be a forth argument at one point.
7141 if ($lazyload === true) {
7142 return new lang_string($identifier, $component, $a);
7145 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7146 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7149 // There is now a forth argument again, this time it is a boolean however so
7150 // we can still check for the old extralocations parameter.
7151 if (!is_bool($lazyload) && !empty($lazyload)) {
7152 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7155 if (strpos($component, '/') !== false) {
7156 debugging('The module name you passed to get_string is the deprecated format ' .
7157 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7158 $componentpath = explode('/', $component);
7160 switch ($componentpath[0]) {
7161 case 'mod':
7162 $component = $componentpath[1];
7163 break;
7164 case 'blocks':
7165 case 'block':
7166 $component = 'block_'.$componentpath[1];
7167 break;
7168 case 'enrol':
7169 $component = 'enrol_'.$componentpath[1];
7170 break;
7171 case 'format':
7172 $component = 'format_'.$componentpath[1];
7173 break;
7174 case 'grade':
7175 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7176 break;
7180 $result = get_string_manager()->get_string($identifier, $component, $a);
7182 // Debugging feature lets you display string identifier and component.
7183 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7184 $result .= ' {' . $identifier . '/' . $component . '}';
7186 return $result;
7190 * Converts an array of strings to their localized value.
7192 * @param array $array An array of strings
7193 * @param string $component The language module that these strings can be found in.
7194 * @return stdClass translated strings.
7196 function get_strings($array, $component = '') {
7197 $string = new stdClass;
7198 foreach ($array as $item) {
7199 $string->$item = get_string($item, $component);
7201 return $string;
7205 * Prints out a translated string.
7207 * Prints out a translated string using the return value from the {@link get_string()} function.
7209 * Example usage of this function when the string is in the moodle.php file:<br/>
7210 * <code>
7211 * echo '<strong>';
7212 * print_string('course');
7213 * echo '</strong>';
7214 * </code>
7216 * Example usage of this function when the string is not in the moodle.php file:<br/>
7217 * <code>
7218 * echo '<h1>';
7219 * print_string('typecourse', 'calendar');
7220 * echo '</h1>';
7221 * </code>
7223 * @category string
7224 * @param string $identifier The key identifier for the localized string
7225 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7226 * @param string|object|array $a An object, string or number that can be used within translation strings
7228 function print_string($identifier, $component = '', $a = null) {
7229 echo get_string($identifier, $component, $a);
7233 * Returns a list of charset codes
7235 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7236 * (checking that such charset is supported by the texlib library!)
7238 * @return array And associative array with contents in the form of charset => charset
7240 function get_list_of_charsets() {
7242 $charsets = array(
7243 'EUC-JP' => 'EUC-JP',
7244 'ISO-2022-JP'=> 'ISO-2022-JP',
7245 'ISO-8859-1' => 'ISO-8859-1',
7246 'SHIFT-JIS' => 'SHIFT-JIS',
7247 'GB2312' => 'GB2312',
7248 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7249 'UTF-8' => 'UTF-8');
7251 asort($charsets);
7253 return $charsets;
7257 * Returns a list of valid and compatible themes
7259 * @return array
7261 function get_list_of_themes() {
7262 global $CFG;
7264 $themes = array();
7266 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7267 $themelist = explode(',', $CFG->themelist);
7268 } else {
7269 $themelist = array_keys(core_component::get_plugin_list("theme"));
7272 foreach ($themelist as $key => $themename) {
7273 $theme = theme_config::load($themename);
7274 $themes[$themename] = $theme;
7277 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7279 return $themes;
7283 * Factory function for emoticon_manager
7285 * @return emoticon_manager singleton
7287 function get_emoticon_manager() {
7288 static $singleton = null;
7290 if (is_null($singleton)) {
7291 $singleton = new emoticon_manager();
7294 return $singleton;
7298 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7300 * Whenever this manager mentiones 'emoticon object', the following data
7301 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7302 * altidentifier and altcomponent
7304 * @see admin_setting_emoticons
7306 * @copyright 2010 David Mudrak
7307 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7309 class emoticon_manager {
7312 * Returns the currently enabled emoticons
7314 * @return array of emoticon objects
7316 public function get_emoticons() {
7317 global $CFG;
7319 if (empty($CFG->emoticons)) {
7320 return array();
7323 $emoticons = $this->decode_stored_config($CFG->emoticons);
7325 if (!is_array($emoticons)) {
7326 // Something is wrong with the format of stored setting.
7327 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7328 return array();
7331 return $emoticons;
7335 * Converts emoticon object into renderable pix_emoticon object
7337 * @param stdClass $emoticon emoticon object
7338 * @param array $attributes explicit HTML attributes to set
7339 * @return pix_emoticon
7341 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7342 $stringmanager = get_string_manager();
7343 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7344 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7345 } else {
7346 $alt = s($emoticon->text);
7348 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7352 * Encodes the array of emoticon objects into a string storable in config table
7354 * @see self::decode_stored_config()
7355 * @param array $emoticons array of emtocion objects
7356 * @return string
7358 public function encode_stored_config(array $emoticons) {
7359 return json_encode($emoticons);
7363 * Decodes the string into an array of emoticon objects
7365 * @see self::encode_stored_config()
7366 * @param string $encoded
7367 * @return string|null
7369 public function decode_stored_config($encoded) {
7370 $decoded = json_decode($encoded);
7371 if (!is_array($decoded)) {
7372 return null;
7374 return $decoded;
7378 * Returns default set of emoticons supported by Moodle
7380 * @return array of sdtClasses
7382 public function default_emoticons() {
7383 return array(
7384 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7385 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7386 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7387 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7388 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7389 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7390 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7391 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7392 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7393 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7394 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7395 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7396 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7397 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7398 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7399 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7400 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7401 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7402 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7403 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7404 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7405 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7406 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7407 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7408 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7409 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7410 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7411 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7412 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7413 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7418 * Helper method preparing the stdClass with the emoticon properties
7420 * @param string|array $text or array of strings
7421 * @param string $imagename to be used by {@link pix_emoticon}
7422 * @param string $altidentifier alternative string identifier, null for no alt
7423 * @param string $altcomponent where the alternative string is defined
7424 * @param string $imagecomponent to be used by {@link pix_emoticon}
7425 * @return stdClass
7427 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7428 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7429 return (object)array(
7430 'text' => $text,
7431 'imagename' => $imagename,
7432 'imagecomponent' => $imagecomponent,
7433 'altidentifier' => $altidentifier,
7434 'altcomponent' => $altcomponent,
7439 // ENCRYPTION.
7442 * rc4encrypt
7444 * @param string $data Data to encrypt.
7445 * @return string The now encrypted data.
7447 function rc4encrypt($data) {
7448 return endecrypt(get_site_identifier(), $data, '');
7452 * rc4decrypt
7454 * @param string $data Data to decrypt.
7455 * @return string The now decrypted data.
7457 function rc4decrypt($data) {
7458 return endecrypt(get_site_identifier(), $data, 'de');
7462 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7464 * @todo Finish documenting this function
7466 * @param string $pwd The password to use when encrypting or decrypting
7467 * @param string $data The data to be decrypted/encrypted
7468 * @param string $case Either 'de' for decrypt or '' for encrypt
7469 * @return string
7471 function endecrypt ($pwd, $data, $case) {
7473 if ($case == 'de') {
7474 $data = urldecode($data);
7477 $key[] = '';
7478 $box[] = '';
7479 $pwdlength = strlen($pwd);
7481 for ($i = 0; $i <= 255; $i++) {
7482 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7483 $box[$i] = $i;
7486 $x = 0;
7488 for ($i = 0; $i <= 255; $i++) {
7489 $x = ($x + $box[$i] + $key[$i]) % 256;
7490 $tempswap = $box[$i];
7491 $box[$i] = $box[$x];
7492 $box[$x] = $tempswap;
7495 $cipher = '';
7497 $a = 0;
7498 $j = 0;
7500 for ($i = 0; $i < strlen($data); $i++) {
7501 $a = ($a + 1) % 256;
7502 $j = ($j + $box[$a]) % 256;
7503 $temp = $box[$a];
7504 $box[$a] = $box[$j];
7505 $box[$j] = $temp;
7506 $k = $box[(($box[$a] + $box[$j]) % 256)];
7507 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7508 $cipher .= chr($cipherby);
7511 if ($case == 'de') {
7512 $cipher = urldecode(urlencode($cipher));
7513 } else {
7514 $cipher = urlencode($cipher);
7517 return $cipher;
7520 // ENVIRONMENT CHECKING.
7523 * This method validates a plug name. It is much faster than calling clean_param.
7525 * @param string $name a string that might be a plugin name.
7526 * @return bool if this string is a valid plugin name.
7528 function is_valid_plugin_name($name) {
7529 // This does not work for 'mod', bad luck, use any other type.
7530 return core_component::is_valid_plugin_name('tool', $name);
7534 * Get a list of all the plugins of a given type that define a certain API function
7535 * in a certain file. The plugin component names and function names are returned.
7537 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7538 * @param string $function the part of the name of the function after the
7539 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7540 * names like report_courselist_hook.
7541 * @param string $file the name of file within the plugin that defines the
7542 * function. Defaults to lib.php.
7543 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7544 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7546 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7547 global $CFG;
7549 // We don't include here as all plugin types files would be included.
7550 $plugins = get_plugins_with_function($function, $file, false);
7552 if (empty($plugins[$plugintype])) {
7553 return array();
7556 $allplugins = core_component::get_plugin_list($plugintype);
7558 // Reformat the array and include the files.
7559 $pluginfunctions = array();
7560 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7562 // Check that it has not been removed and the file is still available.
7563 if (!empty($allplugins[$pluginname])) {
7565 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7566 if (file_exists($filepath)) {
7567 include_once($filepath);
7568 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7573 return $pluginfunctions;
7577 * Get a list of all the plugins that define a certain API function in a certain file.
7579 * @param string $function the part of the name of the function after the
7580 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7581 * names like report_courselist_hook.
7582 * @param string $file the name of file within the plugin that defines the
7583 * function. Defaults to lib.php.
7584 * @param bool $include Whether to include the files that contain the functions or not.
7585 * @return array with [plugintype][plugin] = functionname
7587 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7588 global $CFG;
7590 if (during_initial_install() || isset($CFG->upgraderunning)) {
7591 // API functions _must not_ be called during an installation or upgrade.
7592 return [];
7595 $cache = \cache::make('core', 'plugin_functions');
7597 // Including both although I doubt that we will find two functions definitions with the same name.
7598 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7599 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7600 $pluginfunctions = $cache->get($key);
7602 // Use the plugin manager to check that plugins are currently installed.
7603 $pluginmanager = \core_plugin_manager::instance();
7605 if ($pluginfunctions !== false) {
7607 // Checking that the files are still available.
7608 foreach ($pluginfunctions as $plugintype => $plugins) {
7610 $allplugins = \core_component::get_plugin_list($plugintype);
7611 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7612 foreach ($plugins as $plugin => $function) {
7613 if (!isset($installedplugins[$plugin])) {
7614 // Plugin code is still present on disk but it is not installed.
7615 unset($pluginfunctions[$plugintype][$plugin]);
7616 continue;
7619 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7620 if (empty($allplugins[$plugin])) {
7621 unset($pluginfunctions[$plugintype][$plugin]);
7622 continue;
7625 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7626 if ($include && $fileexists) {
7627 // Include the files if it was requested.
7628 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7629 } else if (!$fileexists) {
7630 // If the file is not available any more it should not be returned.
7631 unset($pluginfunctions[$plugintype][$plugin]);
7635 return $pluginfunctions;
7638 $pluginfunctions = array();
7640 // To fill the cached. Also, everything should continue working with cache disabled.
7641 $plugintypes = \core_component::get_plugin_types();
7642 foreach ($plugintypes as $plugintype => $unused) {
7644 // We need to include files here.
7645 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7646 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7647 foreach ($pluginswithfile as $plugin => $notused) {
7649 if (!isset($installedplugins[$plugin])) {
7650 continue;
7653 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7655 $pluginfunction = false;
7656 if (function_exists($fullfunction)) {
7657 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7658 $pluginfunction = $fullfunction;
7660 } else if ($plugintype === 'mod') {
7661 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7662 $shortfunction = $plugin . '_' . $function;
7663 if (function_exists($shortfunction)) {
7664 $pluginfunction = $shortfunction;
7668 if ($pluginfunction) {
7669 if (empty($pluginfunctions[$plugintype])) {
7670 $pluginfunctions[$plugintype] = array();
7672 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7677 $cache->set($key, $pluginfunctions);
7679 return $pluginfunctions;
7684 * Lists plugin-like directories within specified directory
7686 * This function was originally used for standard Moodle plugins, please use
7687 * new core_component::get_plugin_list() now.
7689 * This function is used for general directory listing and backwards compatility.
7691 * @param string $directory relative directory from root
7692 * @param string $exclude dir name to exclude from the list (defaults to none)
7693 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7694 * @return array Sorted array of directory names found under the requested parameters
7696 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7697 global $CFG;
7699 $plugins = array();
7701 if (empty($basedir)) {
7702 $basedir = $CFG->dirroot .'/'. $directory;
7704 } else {
7705 $basedir = $basedir .'/'. $directory;
7708 if ($CFG->debugdeveloper and empty($exclude)) {
7709 // Make sure devs do not use this to list normal plugins,
7710 // this is intended for general directories that are not plugins!
7712 $subtypes = core_component::get_plugin_types();
7713 if (in_array($basedir, $subtypes)) {
7714 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7716 unset($subtypes);
7719 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7720 if (!$dirhandle = opendir($basedir)) {
7721 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7722 return array();
7724 while (false !== ($dir = readdir($dirhandle))) {
7725 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7726 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7727 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7728 continue;
7730 if (filetype($basedir .'/'. $dir) != 'dir') {
7731 continue;
7733 $plugins[] = $dir;
7735 closedir($dirhandle);
7737 if ($plugins) {
7738 asort($plugins);
7740 return $plugins;
7744 * Invoke plugin's callback functions
7746 * @param string $type plugin type e.g. 'mod'
7747 * @param string $name plugin name
7748 * @param string $feature feature name
7749 * @param string $action feature's action
7750 * @param array $params parameters of callback function, should be an array
7751 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7752 * @return mixed
7754 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7756 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7757 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7761 * Invoke component's callback functions
7763 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7764 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7765 * @param array $params parameters of callback function
7766 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7767 * @return mixed
7769 function component_callback($component, $function, array $params = array(), $default = null) {
7771 $functionname = component_callback_exists($component, $function);
7773 if ($functionname) {
7774 // Function exists, so just return function result.
7775 $ret = call_user_func_array($functionname, $params);
7776 if (is_null($ret)) {
7777 return $default;
7778 } else {
7779 return $ret;
7782 return $default;
7786 * Determine if a component callback exists and return the function name to call. Note that this
7787 * function will include the required library files so that the functioname returned can be
7788 * called directly.
7790 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7791 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7792 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7793 * @throws coding_exception if invalid component specfied
7795 function component_callback_exists($component, $function) {
7796 global $CFG; // This is needed for the inclusions.
7798 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7799 if (empty($cleancomponent)) {
7800 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7802 $component = $cleancomponent;
7804 list($type, $name) = core_component::normalize_component($component);
7805 $component = $type . '_' . $name;
7807 $oldfunction = $name.'_'.$function;
7808 $function = $component.'_'.$function;
7810 $dir = core_component::get_component_directory($component);
7811 if (empty($dir)) {
7812 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7815 // Load library and look for function.
7816 if (file_exists($dir.'/lib.php')) {
7817 require_once($dir.'/lib.php');
7820 if (!function_exists($function) and function_exists($oldfunction)) {
7821 if ($type !== 'mod' and $type !== 'core') {
7822 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7824 $function = $oldfunction;
7827 if (function_exists($function)) {
7828 return $function;
7830 return false;
7834 * Call the specified callback method on the provided class.
7836 * If the callback returns null, then the default value is returned instead.
7837 * If the class does not exist, then the default value is returned.
7839 * @param string $classname The name of the class to call upon.
7840 * @param string $methodname The name of the staticically defined method on the class.
7841 * @param array $params The arguments to pass into the method.
7842 * @param mixed $default The default value.
7843 * @return mixed The return value.
7845 function component_class_callback($classname, $methodname, array $params, $default = null) {
7846 if (!class_exists($classname)) {
7847 return $default;
7850 if (!method_exists($classname, $methodname)) {
7851 return $default;
7854 $fullfunction = $classname . '::' . $methodname;
7855 $result = call_user_func_array($fullfunction, $params);
7857 if (null === $result) {
7858 return $default;
7859 } else {
7860 return $result;
7865 * Checks whether a plugin supports a specified feature.
7867 * @param string $type Plugin type e.g. 'mod'
7868 * @param string $name Plugin name e.g. 'forum'
7869 * @param string $feature Feature code (FEATURE_xx constant)
7870 * @param mixed $default default value if feature support unknown
7871 * @return mixed Feature result (false if not supported, null if feature is unknown,
7872 * otherwise usually true but may have other feature-specific value such as array)
7873 * @throws coding_exception
7875 function plugin_supports($type, $name, $feature, $default = null) {
7876 global $CFG;
7878 if ($type === 'mod' and $name === 'NEWMODULE') {
7879 // Somebody forgot to rename the module template.
7880 return false;
7883 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7884 if (empty($component)) {
7885 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7888 $function = null;
7890 if ($type === 'mod') {
7891 // We need this special case because we support subplugins in modules,
7892 // otherwise it would end up in infinite loop.
7893 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7894 include_once("$CFG->dirroot/mod/$name/lib.php");
7895 $function = $component.'_supports';
7896 if (!function_exists($function)) {
7897 // Legacy non-frankenstyle function name.
7898 $function = $name.'_supports';
7902 } else {
7903 if (!$path = core_component::get_plugin_directory($type, $name)) {
7904 // Non existent plugin type.
7905 return false;
7907 if (file_exists("$path/lib.php")) {
7908 include_once("$path/lib.php");
7909 $function = $component.'_supports';
7913 if ($function and function_exists($function)) {
7914 $supports = $function($feature);
7915 if (is_null($supports)) {
7916 // Plugin does not know - use default.
7917 return $default;
7918 } else {
7919 return $supports;
7923 // Plugin does not care, so use default.
7924 return $default;
7928 * Returns true if the current version of PHP is greater that the specified one.
7930 * @todo Check PHP version being required here is it too low?
7932 * @param string $version The version of php being tested.
7933 * @return bool
7935 function check_php_version($version='5.2.4') {
7936 return (version_compare(phpversion(), $version) >= 0);
7940 * Determine if moodle installation requires update.
7942 * Checks version numbers of main code and all plugins to see
7943 * if there are any mismatches.
7945 * @return bool
7947 function moodle_needs_upgrading() {
7948 global $CFG;
7950 if (empty($CFG->version)) {
7951 return true;
7954 // There is no need to purge plugininfo caches here because
7955 // these caches are not used during upgrade and they are purged after
7956 // every upgrade.
7958 if (empty($CFG->allversionshash)) {
7959 return true;
7962 $hash = core_component::get_all_versions_hash();
7964 return ($hash !== $CFG->allversionshash);
7968 * Returns the major version of this site
7970 * Moodle version numbers consist of three numbers separated by a dot, for
7971 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7972 * called major version. This function extracts the major version from either
7973 * $CFG->release (default) or eventually from the $release variable defined in
7974 * the main version.php.
7976 * @param bool $fromdisk should the version if source code files be used
7977 * @return string|false the major version like '2.3', false if could not be determined
7979 function moodle_major_version($fromdisk = false) {
7980 global $CFG;
7982 if ($fromdisk) {
7983 $release = null;
7984 require($CFG->dirroot.'/version.php');
7985 if (empty($release)) {
7986 return false;
7989 } else {
7990 if (empty($CFG->release)) {
7991 return false;
7993 $release = $CFG->release;
7996 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7997 return $matches[0];
7998 } else {
7999 return false;
8003 // MISCELLANEOUS.
8006 * Sets the system locale
8008 * @category string
8009 * @param string $locale Can be used to force a locale
8011 function moodle_setlocale($locale='') {
8012 global $CFG;
8014 static $currentlocale = ''; // Last locale caching.
8016 $oldlocale = $currentlocale;
8018 // Fetch the correct locale based on ostype.
8019 if ($CFG->ostype == 'WINDOWS') {
8020 $stringtofetch = 'localewin';
8021 } else {
8022 $stringtofetch = 'locale';
8025 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8026 if (!empty($locale)) {
8027 $currentlocale = $locale;
8028 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
8029 $currentlocale = $CFG->locale;
8030 } else {
8031 $currentlocale = get_string($stringtofetch, 'langconfig');
8034 // Do nothing if locale already set up.
8035 if ($oldlocale == $currentlocale) {
8036 return;
8039 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8040 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8041 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8043 // Get current values.
8044 $monetary= setlocale (LC_MONETARY, 0);
8045 $numeric = setlocale (LC_NUMERIC, 0);
8046 $ctype = setlocale (LC_CTYPE, 0);
8047 if ($CFG->ostype != 'WINDOWS') {
8048 $messages= setlocale (LC_MESSAGES, 0);
8050 // Set locale to all.
8051 $result = setlocale (LC_ALL, $currentlocale);
8052 // If setting of locale fails try the other utf8 or utf-8 variant,
8053 // some operating systems support both (Debian), others just one (OSX).
8054 if ($result === false) {
8055 if (stripos($currentlocale, '.UTF-8') !== false) {
8056 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8057 setlocale (LC_ALL, $newlocale);
8058 } else if (stripos($currentlocale, '.UTF8') !== false) {
8059 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8060 setlocale (LC_ALL, $newlocale);
8063 // Set old values.
8064 setlocale (LC_MONETARY, $monetary);
8065 setlocale (LC_NUMERIC, $numeric);
8066 if ($CFG->ostype != 'WINDOWS') {
8067 setlocale (LC_MESSAGES, $messages);
8069 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8070 // To workaround a well-known PHP problem with Turkish letter Ii.
8071 setlocale (LC_CTYPE, $ctype);
8076 * Count words in a string.
8078 * Words are defined as things between whitespace.
8080 * @category string
8081 * @param string $string The text to be searched for words.
8082 * @return int The count of words in the specified string
8084 function count_words($string) {
8085 $string = strip_tags($string);
8086 // Decode HTML entities.
8087 $string = html_entity_decode($string);
8088 // Replace underscores (which are classed as word characters) with spaces.
8089 $string = preg_replace('/_/u', ' ', $string);
8090 // Remove any characters that shouldn't be treated as word boundaries.
8091 $string = preg_replace('/[\'"’-]/u', '', $string);
8092 // Remove dots and commas from within numbers only.
8093 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
8095 return count(preg_split('/\w\b/u', $string)) - 1;
8099 * Count letters in a string.
8101 * Letters are defined as chars not in tags and different from whitespace.
8103 * @category string
8104 * @param string $string The text to be searched for letters.
8105 * @return int The count of letters in the specified text.
8107 function count_letters($string) {
8108 $string = strip_tags($string); // Tags are out now.
8109 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8111 return core_text::strlen($string);
8115 * Generate and return a random string of the specified length.
8117 * @param int $length The length of the string to be created.
8118 * @return string
8120 function random_string($length=15) {
8121 $randombytes = random_bytes_emulate($length);
8122 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8123 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8124 $pool .= '0123456789';
8125 $poollen = strlen($pool);
8126 $string = '';
8127 for ($i = 0; $i < $length; $i++) {
8128 $rand = ord($randombytes[$i]);
8129 $string .= substr($pool, ($rand%($poollen)), 1);
8131 return $string;
8135 * Generate a complex random string (useful for md5 salts)
8137 * This function is based on the above {@link random_string()} however it uses a
8138 * larger pool of characters and generates a string between 24 and 32 characters
8140 * @param int $length Optional if set generates a string to exactly this length
8141 * @return string
8143 function complex_random_string($length=null) {
8144 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8145 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8146 $poollen = strlen($pool);
8147 if ($length===null) {
8148 $length = floor(rand(24, 32));
8150 $randombytes = random_bytes_emulate($length);
8151 $string = '';
8152 for ($i = 0; $i < $length; $i++) {
8153 $rand = ord($randombytes[$i]);
8154 $string .= $pool[($rand%$poollen)];
8156 return $string;
8160 * Try to generates cryptographically secure pseudo-random bytes.
8162 * Note this is achieved by fallbacking between:
8163 * - PHP 7 random_bytes().
8164 * - OpenSSL openssl_random_pseudo_bytes().
8165 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8167 * @param int $length requested length in bytes
8168 * @return string binary data
8170 function random_bytes_emulate($length) {
8171 global $CFG;
8172 if ($length <= 0) {
8173 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8174 return '';
8176 if (function_exists('random_bytes')) {
8177 // Use PHP 7 goodness.
8178 $hash = @random_bytes($length);
8179 if ($hash !== false) {
8180 return $hash;
8183 if (function_exists('openssl_random_pseudo_bytes')) {
8184 // If you have the openssl extension enabled.
8185 $hash = openssl_random_pseudo_bytes($length);
8186 if ($hash !== false) {
8187 return $hash;
8191 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8192 $staticdata = serialize($CFG) . serialize($_SERVER);
8193 $hash = '';
8194 do {
8195 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8196 } while (strlen($hash) < $length);
8198 return substr($hash, 0, $length);
8202 * Given some text (which may contain HTML) and an ideal length,
8203 * this function truncates the text neatly on a word boundary if possible
8205 * @category string
8206 * @param string $text text to be shortened
8207 * @param int $ideal ideal string length
8208 * @param boolean $exact if false, $text will not be cut mid-word
8209 * @param string $ending The string to append if the passed string is truncated
8210 * @return string $truncate shortened string
8212 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8213 // If the plain text is shorter than the maximum length, return the whole text.
8214 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8215 return $text;
8218 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8219 // and only tag in its 'line'.
8220 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8222 $totallength = core_text::strlen($ending);
8223 $truncate = '';
8225 // This array stores information about open and close tags and their position
8226 // in the truncated string. Each item in the array is an object with fields
8227 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8228 // (byte position in truncated text).
8229 $tagdetails = array();
8231 foreach ($lines as $linematchings) {
8232 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8233 if (!empty($linematchings[1])) {
8234 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8235 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8236 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8237 // Record closing tag.
8238 $tagdetails[] = (object) array(
8239 'open' => false,
8240 'tag' => core_text::strtolower($tagmatchings[1]),
8241 'pos' => core_text::strlen($truncate),
8244 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8245 // Record opening tag.
8246 $tagdetails[] = (object) array(
8247 'open' => true,
8248 'tag' => core_text::strtolower($tagmatchings[1]),
8249 'pos' => core_text::strlen($truncate),
8251 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8252 $tagdetails[] = (object) array(
8253 'open' => true,
8254 'tag' => core_text::strtolower('if'),
8255 'pos' => core_text::strlen($truncate),
8257 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8258 $tagdetails[] = (object) array(
8259 'open' => false,
8260 'tag' => core_text::strtolower('if'),
8261 'pos' => core_text::strlen($truncate),
8265 // Add html-tag to $truncate'd text.
8266 $truncate .= $linematchings[1];
8269 // Calculate the length of the plain text part of the line; handle entities as one character.
8270 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8271 if ($totallength + $contentlength > $ideal) {
8272 // The number of characters which are left.
8273 $left = $ideal - $totallength;
8274 $entitieslength = 0;
8275 // Search for html entities.
8276 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)) {
8277 // Calculate the real length of all entities in the legal range.
8278 foreach ($entities[0] as $entity) {
8279 if ($entity[1]+1-$entitieslength <= $left) {
8280 $left--;
8281 $entitieslength += core_text::strlen($entity[0]);
8282 } else {
8283 // No more characters left.
8284 break;
8288 $breakpos = $left + $entitieslength;
8290 // If the words shouldn't be cut in the middle...
8291 if (!$exact) {
8292 // Search the last occurence of a space.
8293 for (; $breakpos > 0; $breakpos--) {
8294 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8295 if ($char === '.' or $char === ' ') {
8296 $breakpos += 1;
8297 break;
8298 } else if (strlen($char) > 2) {
8299 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8300 $breakpos += 1;
8301 break;
8306 if ($breakpos == 0) {
8307 // This deals with the test_shorten_text_no_spaces case.
8308 $breakpos = $left + $entitieslength;
8309 } else if ($breakpos > $left + $entitieslength) {
8310 // This deals with the previous for loop breaking on the first char.
8311 $breakpos = $left + $entitieslength;
8314 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8315 // Maximum length is reached, so get off the loop.
8316 break;
8317 } else {
8318 $truncate .= $linematchings[2];
8319 $totallength += $contentlength;
8322 // If the maximum length is reached, get off the loop.
8323 if ($totallength >= $ideal) {
8324 break;
8328 // Add the defined ending to the text.
8329 $truncate .= $ending;
8331 // Now calculate the list of open html tags based on the truncate position.
8332 $opentags = array();
8333 foreach ($tagdetails as $taginfo) {
8334 if ($taginfo->open) {
8335 // Add tag to the beginning of $opentags list.
8336 array_unshift($opentags, $taginfo->tag);
8337 } else {
8338 // Can have multiple exact same open tags, close the last one.
8339 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8340 if ($pos !== false) {
8341 unset($opentags[$pos]);
8346 // Close all unclosed html-tags.
8347 foreach ($opentags as $tag) {
8348 if ($tag === 'if') {
8349 $truncate .= '<!--<![endif]-->';
8350 } else {
8351 $truncate .= '</' . $tag . '>';
8355 return $truncate;
8359 * Shortens a given filename by removing characters positioned after the ideal string length.
8360 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8361 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8363 * @param string $filename file name
8364 * @param int $length ideal string length
8365 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8366 * @return string $shortened shortened file name
8368 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8369 $shortened = $filename;
8370 // Extract a part of the filename if it's char size exceeds the ideal string length.
8371 if (core_text::strlen($filename) > $length) {
8372 // Exclude extension if present in filename.
8373 $mimetypes = get_mimetypes_array();
8374 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8375 if ($extension && !empty($mimetypes[$extension])) {
8376 $basename = pathinfo($filename, PATHINFO_FILENAME);
8377 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8378 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8379 $shortened .= '.' . $extension;
8380 } else {
8381 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8382 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8385 return $shortened;
8389 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8391 * @param array $path The paths to reduce the length.
8392 * @param int $length Ideal string length
8393 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8394 * @return array $result Shortened paths in array.
8396 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8397 $result = null;
8399 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8400 $carry[] = shorten_filename($singlepath, $length, $includehash);
8401 return $carry;
8402 }, []);
8404 return $result;
8408 * Given dates in seconds, how many weeks is the date from startdate
8409 * The first week is 1, the second 2 etc ...
8411 * @param int $startdate Timestamp for the start date
8412 * @param int $thedate Timestamp for the end date
8413 * @return string
8415 function getweek ($startdate, $thedate) {
8416 if ($thedate < $startdate) {
8417 return 0;
8420 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8424 * Returns a randomly generated password of length $maxlen. inspired by
8426 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8427 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8429 * @param int $maxlen The maximum size of the password being generated.
8430 * @return string
8432 function generate_password($maxlen=10) {
8433 global $CFG;
8435 if (empty($CFG->passwordpolicy)) {
8436 $fillers = PASSWORD_DIGITS;
8437 $wordlist = file($CFG->wordlist);
8438 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8439 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8440 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8441 $password = $word1 . $filler1 . $word2;
8442 } else {
8443 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8444 $digits = $CFG->minpassworddigits;
8445 $lower = $CFG->minpasswordlower;
8446 $upper = $CFG->minpasswordupper;
8447 $nonalphanum = $CFG->minpasswordnonalphanum;
8448 $total = $lower + $upper + $digits + $nonalphanum;
8449 // Var minlength should be the greater one of the two ( $minlen and $total ).
8450 $minlen = $minlen < $total ? $total : $minlen;
8451 // Var maxlen can never be smaller than minlen.
8452 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8453 $additional = $maxlen - $total;
8455 // Make sure we have enough characters to fulfill
8456 // complexity requirements.
8457 $passworddigits = PASSWORD_DIGITS;
8458 while ($digits > strlen($passworddigits)) {
8459 $passworddigits .= PASSWORD_DIGITS;
8461 $passwordlower = PASSWORD_LOWER;
8462 while ($lower > strlen($passwordlower)) {
8463 $passwordlower .= PASSWORD_LOWER;
8465 $passwordupper = PASSWORD_UPPER;
8466 while ($upper > strlen($passwordupper)) {
8467 $passwordupper .= PASSWORD_UPPER;
8469 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8470 while ($nonalphanum > strlen($passwordnonalphanum)) {
8471 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8474 // Now mix and shuffle it all.
8475 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8476 substr(str_shuffle ($passwordupper), 0, $upper) .
8477 substr(str_shuffle ($passworddigits), 0, $digits) .
8478 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8479 substr(str_shuffle ($passwordlower .
8480 $passwordupper .
8481 $passworddigits .
8482 $passwordnonalphanum), 0 , $additional));
8485 return substr ($password, 0, $maxlen);
8489 * Given a float, prints it nicely.
8490 * Localized floats must not be used in calculations!
8492 * The stripzeros feature is intended for making numbers look nicer in small
8493 * areas where it is not necessary to indicate the degree of accuracy by showing
8494 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8495 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8497 * @param float $float The float to print
8498 * @param int $decimalpoints The number of decimal places to print.
8499 * @param bool $localized use localized decimal separator
8500 * @param bool $stripzeros If true, removes final zeros after decimal point
8501 * @return string locale float
8503 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8504 if (is_null($float)) {
8505 return '';
8507 if ($localized) {
8508 $separator = get_string('decsep', 'langconfig');
8509 } else {
8510 $separator = '.';
8512 $result = number_format($float, $decimalpoints, $separator, '');
8513 if ($stripzeros) {
8514 // Remove zeros and final dot if not needed.
8515 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8517 return $result;
8521 * Converts locale specific floating point/comma number back to standard PHP float value
8522 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8524 * @param string $localefloat locale aware float representation
8525 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8526 * @return mixed float|bool - false or the parsed float.
8528 function unformat_float($localefloat, $strict = false) {
8529 $localefloat = trim($localefloat);
8531 if ($localefloat == '') {
8532 return null;
8535 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8536 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8538 if ($strict && !is_numeric($localefloat)) {
8539 return false;
8542 return (float)$localefloat;
8546 * Given a simple array, this shuffles it up just like shuffle()
8547 * Unlike PHP's shuffle() this function works on any machine.
8549 * @param array $array The array to be rearranged
8550 * @return array
8552 function swapshuffle($array) {
8554 $last = count($array) - 1;
8555 for ($i = 0; $i <= $last; $i++) {
8556 $from = rand(0, $last);
8557 $curr = $array[$i];
8558 $array[$i] = $array[$from];
8559 $array[$from] = $curr;
8561 return $array;
8565 * Like {@link swapshuffle()}, but works on associative arrays
8567 * @param array $array The associative array to be rearranged
8568 * @return array
8570 function swapshuffle_assoc($array) {
8572 $newarray = array();
8573 $newkeys = swapshuffle(array_keys($array));
8575 foreach ($newkeys as $newkey) {
8576 $newarray[$newkey] = $array[$newkey];
8578 return $newarray;
8582 * Given an arbitrary array, and a number of draws,
8583 * this function returns an array with that amount
8584 * of items. The indexes are retained.
8586 * @todo Finish documenting this function
8588 * @param array $array
8589 * @param int $draws
8590 * @return array
8592 function draw_rand_array($array, $draws) {
8594 $return = array();
8596 $last = count($array);
8598 if ($draws > $last) {
8599 $draws = $last;
8602 while ($draws > 0) {
8603 $last--;
8605 $keys = array_keys($array);
8606 $rand = rand(0, $last);
8608 $return[$keys[$rand]] = $array[$keys[$rand]];
8609 unset($array[$keys[$rand]]);
8611 $draws--;
8614 return $return;
8618 * Calculate the difference between two microtimes
8620 * @param string $a The first Microtime
8621 * @param string $b The second Microtime
8622 * @return string
8624 function microtime_diff($a, $b) {
8625 list($adec, $asec) = explode(' ', $a);
8626 list($bdec, $bsec) = explode(' ', $b);
8627 return $bsec - $asec + $bdec - $adec;
8631 * Given a list (eg a,b,c,d,e) this function returns
8632 * an array of 1->a, 2->b, 3->c etc
8634 * @param string $list The string to explode into array bits
8635 * @param string $separator The separator used within the list string
8636 * @return array The now assembled array
8638 function make_menu_from_list($list, $separator=',') {
8640 $array = array_reverse(explode($separator, $list), true);
8641 foreach ($array as $key => $item) {
8642 $outarray[$key+1] = trim($item);
8644 return $outarray;
8648 * Creates an array that represents all the current grades that
8649 * can be chosen using the given grading type.
8651 * Negative numbers
8652 * are scales, zero is no grade, and positive numbers are maximum
8653 * grades.
8655 * @todo Finish documenting this function or better deprecated this completely!
8657 * @param int $gradingtype
8658 * @return array
8660 function make_grades_menu($gradingtype) {
8661 global $DB;
8663 $grades = array();
8664 if ($gradingtype < 0) {
8665 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8666 return make_menu_from_list($scale->scale);
8668 } else if ($gradingtype > 0) {
8669 for ($i=$gradingtype; $i>=0; $i--) {
8670 $grades[$i] = $i .' / '. $gradingtype;
8672 return $grades;
8674 return $grades;
8678 * make_unique_id_code
8680 * @todo Finish documenting this function
8682 * @uses $_SERVER
8683 * @param string $extra Extra string to append to the end of the code
8684 * @return string
8686 function make_unique_id_code($extra = '') {
8688 $hostname = 'unknownhost';
8689 if (!empty($_SERVER['HTTP_HOST'])) {
8690 $hostname = $_SERVER['HTTP_HOST'];
8691 } else if (!empty($_ENV['HTTP_HOST'])) {
8692 $hostname = $_ENV['HTTP_HOST'];
8693 } else if (!empty($_SERVER['SERVER_NAME'])) {
8694 $hostname = $_SERVER['SERVER_NAME'];
8695 } else if (!empty($_ENV['SERVER_NAME'])) {
8696 $hostname = $_ENV['SERVER_NAME'];
8699 $date = gmdate("ymdHis");
8701 $random = random_string(6);
8703 if ($extra) {
8704 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8705 } else {
8706 return $hostname .'+'. $date .'+'. $random;
8712 * Function to check the passed address is within the passed subnet
8714 * The parameter is a comma separated string of subnet definitions.
8715 * Subnet strings can be in one of three formats:
8716 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8717 * 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)
8718 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8719 * Code for type 1 modified from user posted comments by mediator at
8720 * {@link http://au.php.net/manual/en/function.ip2long.php}
8722 * @param string $addr The address you are checking
8723 * @param string $subnetstr The string of subnet addresses
8724 * @return bool
8726 function address_in_subnet($addr, $subnetstr) {
8728 if ($addr == '0.0.0.0') {
8729 return false;
8731 $subnets = explode(',', $subnetstr);
8732 $found = false;
8733 $addr = trim($addr);
8734 $addr = cleanremoteaddr($addr, false); // Normalise.
8735 if ($addr === null) {
8736 return false;
8738 $addrparts = explode(':', $addr);
8740 $ipv6 = strpos($addr, ':');
8742 foreach ($subnets as $subnet) {
8743 $subnet = trim($subnet);
8744 if ($subnet === '') {
8745 continue;
8748 if (strpos($subnet, '/') !== false) {
8749 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8750 list($ip, $mask) = explode('/', $subnet);
8751 $mask = trim($mask);
8752 if (!is_number($mask)) {
8753 continue; // Incorect mask number, eh?
8755 $ip = cleanremoteaddr($ip, false); // Normalise.
8756 if ($ip === null) {
8757 continue;
8759 if (strpos($ip, ':') !== false) {
8760 // IPv6.
8761 if (!$ipv6) {
8762 continue;
8764 if ($mask > 128 or $mask < 0) {
8765 continue; // Nonsense.
8767 if ($mask == 0) {
8768 return true; // Any address.
8770 if ($mask == 128) {
8771 if ($ip === $addr) {
8772 return true;
8774 continue;
8776 $ipparts = explode(':', $ip);
8777 $modulo = $mask % 16;
8778 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8779 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8780 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8781 if ($modulo == 0) {
8782 return true;
8784 $pos = ($mask-$modulo)/16;
8785 $ipnet = hexdec($ipparts[$pos]);
8786 $addrnet = hexdec($addrparts[$pos]);
8787 $mask = 0xffff << (16 - $modulo);
8788 if (($addrnet & $mask) == ($ipnet & $mask)) {
8789 return true;
8793 } else {
8794 // IPv4.
8795 if ($ipv6) {
8796 continue;
8798 if ($mask > 32 or $mask < 0) {
8799 continue; // Nonsense.
8801 if ($mask == 0) {
8802 return true;
8804 if ($mask == 32) {
8805 if ($ip === $addr) {
8806 return true;
8808 continue;
8810 $mask = 0xffffffff << (32 - $mask);
8811 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8812 return true;
8816 } else if (strpos($subnet, '-') !== false) {
8817 // 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.
8818 $parts = explode('-', $subnet);
8819 if (count($parts) != 2) {
8820 continue;
8823 if (strpos($subnet, ':') !== false) {
8824 // IPv6.
8825 if (!$ipv6) {
8826 continue;
8828 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8829 if ($ipstart === null) {
8830 continue;
8832 $ipparts = explode(':', $ipstart);
8833 $start = hexdec(array_pop($ipparts));
8834 $ipparts[] = trim($parts[1]);
8835 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8836 if ($ipend === null) {
8837 continue;
8839 $ipparts[7] = '';
8840 $ipnet = implode(':', $ipparts);
8841 if (strpos($addr, $ipnet) !== 0) {
8842 continue;
8844 $ipparts = explode(':', $ipend);
8845 $end = hexdec($ipparts[7]);
8847 $addrend = hexdec($addrparts[7]);
8849 if (($addrend >= $start) and ($addrend <= $end)) {
8850 return true;
8853 } else {
8854 // IPv4.
8855 if ($ipv6) {
8856 continue;
8858 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8859 if ($ipstart === null) {
8860 continue;
8862 $ipparts = explode('.', $ipstart);
8863 $ipparts[3] = trim($parts[1]);
8864 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8865 if ($ipend === null) {
8866 continue;
8869 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8870 return true;
8874 } else {
8875 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8876 if (strpos($subnet, ':') !== false) {
8877 // IPv6.
8878 if (!$ipv6) {
8879 continue;
8881 $parts = explode(':', $subnet);
8882 $count = count($parts);
8883 if ($parts[$count-1] === '') {
8884 unset($parts[$count-1]); // Trim trailing :'s.
8885 $count--;
8886 $subnet = implode('.', $parts);
8888 $isip = cleanremoteaddr($subnet, false); // Normalise.
8889 if ($isip !== null) {
8890 if ($isip === $addr) {
8891 return true;
8893 continue;
8894 } else if ($count > 8) {
8895 continue;
8897 $zeros = array_fill(0, 8-$count, '0');
8898 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8899 if (address_in_subnet($addr, $subnet)) {
8900 return true;
8903 } else {
8904 // IPv4.
8905 if ($ipv6) {
8906 continue;
8908 $parts = explode('.', $subnet);
8909 $count = count($parts);
8910 if ($parts[$count-1] === '') {
8911 unset($parts[$count-1]); // Trim trailing .
8912 $count--;
8913 $subnet = implode('.', $parts);
8915 if ($count == 4) {
8916 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8917 if ($subnet === $addr) {
8918 return true;
8920 continue;
8921 } else if ($count > 4) {
8922 continue;
8924 $zeros = array_fill(0, 4-$count, '0');
8925 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8926 if (address_in_subnet($addr, $subnet)) {
8927 return true;
8933 return false;
8937 * For outputting debugging info
8939 * @param string $string The string to write
8940 * @param string $eol The end of line char(s) to use
8941 * @param string $sleep Period to make the application sleep
8942 * This ensures any messages have time to display before redirect
8944 function mtrace($string, $eol="\n", $sleep=0) {
8945 global $CFG;
8947 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
8948 $fn = $CFG->mtrace_wrapper;
8949 $fn($string, $eol);
8950 return;
8951 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
8952 fwrite(STDOUT, $string.$eol);
8953 } else {
8954 echo $string . $eol;
8957 flush();
8959 // Delay to keep message on user's screen in case of subsequent redirect.
8960 if ($sleep) {
8961 sleep($sleep);
8966 * Replace 1 or more slashes or backslashes to 1 slash
8968 * @param string $path The path to strip
8969 * @return string the path with double slashes removed
8971 function cleardoubleslashes ($path) {
8972 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8976 * Is the current ip in a given list?
8978 * @param string $list
8979 * @return bool
8981 function remoteip_in_list($list) {
8982 $inlist = false;
8983 $clientip = getremoteaddr(null);
8985 if (!$clientip) {
8986 // Ensure access on cli.
8987 return true;
8990 $list = explode("\n", $list);
8991 foreach ($list as $line) {
8992 $tokens = explode('#', $line);
8993 $subnet = trim($tokens[0]);
8994 if (address_in_subnet($clientip, $subnet)) {
8995 $inlist = true;
8996 break;
8999 return $inlist;
9003 * Returns most reliable client address
9005 * @param string $default If an address can't be determined, then return this
9006 * @return string The remote IP address
9008 function getremoteaddr($default='0.0.0.0') {
9009 global $CFG;
9011 if (empty($CFG->getremoteaddrconf)) {
9012 // This will happen, for example, before just after the upgrade, as the
9013 // user is redirected to the admin screen.
9014 $variablestoskip = 0;
9015 } else {
9016 $variablestoskip = $CFG->getremoteaddrconf;
9018 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
9019 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9020 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9021 return $address ? $address : $default;
9024 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
9025 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9026 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9027 $address = $forwardedaddresses[0];
9029 if (substr_count($address, ":") > 1) {
9030 // Remove port and brackets from IPv6.
9031 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9032 $address = $matches[1];
9034 } else {
9035 // Remove port from IPv4.
9036 if (substr_count($address, ":") == 1) {
9037 $parts = explode(":", $address);
9038 $address = $parts[0];
9042 $address = cleanremoteaddr($address);
9043 return $address ? $address : $default;
9046 if (!empty($_SERVER['REMOTE_ADDR'])) {
9047 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9048 return $address ? $address : $default;
9049 } else {
9050 return $default;
9055 * Cleans an ip address. Internal addresses are now allowed.
9056 * (Originally local addresses were not allowed.)
9058 * @param string $addr IPv4 or IPv6 address
9059 * @param bool $compress use IPv6 address compression
9060 * @return string normalised ip address string, null if error
9062 function cleanremoteaddr($addr, $compress=false) {
9063 $addr = trim($addr);
9065 if (strpos($addr, ':') !== false) {
9066 // Can be only IPv6.
9067 $parts = explode(':', $addr);
9068 $count = count($parts);
9070 if (strpos($parts[$count-1], '.') !== false) {
9071 // Legacy ipv4 notation.
9072 $last = array_pop($parts);
9073 $ipv4 = cleanremoteaddr($last, true);
9074 if ($ipv4 === null) {
9075 return null;
9077 $bits = explode('.', $ipv4);
9078 $parts[] = dechex($bits[0]).dechex($bits[1]);
9079 $parts[] = dechex($bits[2]).dechex($bits[3]);
9080 $count = count($parts);
9081 $addr = implode(':', $parts);
9084 if ($count < 3 or $count > 8) {
9085 return null; // Severly malformed.
9088 if ($count != 8) {
9089 if (strpos($addr, '::') === false) {
9090 return null; // Malformed.
9092 // Uncompress.
9093 $insertat = array_search('', $parts, true);
9094 $missing = array_fill(0, 1 + 8 - $count, '0');
9095 array_splice($parts, $insertat, 1, $missing);
9096 foreach ($parts as $key => $part) {
9097 if ($part === '') {
9098 $parts[$key] = '0';
9103 $adr = implode(':', $parts);
9104 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9105 return null; // Incorrect format - sorry.
9108 // Normalise 0s and case.
9109 $parts = array_map('hexdec', $parts);
9110 $parts = array_map('dechex', $parts);
9112 $result = implode(':', $parts);
9114 if (!$compress) {
9115 return $result;
9118 if ($result === '0:0:0:0:0:0:0:0') {
9119 return '::'; // All addresses.
9122 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9123 if ($compressed !== $result) {
9124 return $compressed;
9127 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9128 if ($compressed !== $result) {
9129 return $compressed;
9132 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9133 if ($compressed !== $result) {
9134 return $compressed;
9137 return $result;
9140 // First get all things that look like IPv4 addresses.
9141 $parts = array();
9142 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9143 return null;
9145 unset($parts[0]);
9147 foreach ($parts as $key => $match) {
9148 if ($match > 255) {
9149 return null;
9151 $parts[$key] = (int)$match; // Normalise 0s.
9154 return implode('.', $parts);
9159 * Is IP address a public address?
9161 * @param string $ip The ip to check
9162 * @return bool true if the ip is public
9164 function ip_is_public($ip) {
9165 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9169 * This function will make a complete copy of anything it's given,
9170 * regardless of whether it's an object or not.
9172 * @param mixed $thing Something you want cloned
9173 * @return mixed What ever it is you passed it
9175 function fullclone($thing) {
9176 return unserialize(serialize($thing));
9180 * Used to make sure that $min <= $value <= $max
9182 * Make sure that value is between min, and max
9184 * @param int $min The minimum value
9185 * @param int $value The value to check
9186 * @param int $max The maximum value
9187 * @return int
9189 function bounded_number($min, $value, $max) {
9190 if ($value < $min) {
9191 return $min;
9193 if ($value > $max) {
9194 return $max;
9196 return $value;
9200 * Check if there is a nested array within the passed array
9202 * @param array $array
9203 * @return bool true if there is a nested array false otherwise
9205 function array_is_nested($array) {
9206 foreach ($array as $value) {
9207 if (is_array($value)) {
9208 return true;
9211 return false;
9215 * get_performance_info() pairs up with init_performance_info()
9216 * loaded in setup.php. Returns an array with 'html' and 'txt'
9217 * values ready for use, and each of the individual stats provided
9218 * separately as well.
9220 * @return array
9222 function get_performance_info() {
9223 global $CFG, $PERF, $DB, $PAGE;
9225 $info = array();
9226 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9228 $info['html'] = '';
9229 if (!empty($CFG->themedesignermode)) {
9230 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9231 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9233 $info['html'] .= '<ul class="list-unstyled m-l-1 row">'; // Holds userfriendly HTML representation.
9235 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9237 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9238 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9240 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9241 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9243 if (function_exists('memory_get_usage')) {
9244 $info['memory_total'] = memory_get_usage();
9245 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9246 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9247 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9248 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9251 if (function_exists('memory_get_peak_usage')) {
9252 $info['memory_peak'] = memory_get_peak_usage();
9253 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9254 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9257 $info['html'] .= '</ul><ul class="list-unstyled m-l-1 row">';
9258 $inc = get_included_files();
9259 $info['includecount'] = count($inc);
9260 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9261 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9263 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9264 // We can not track more performance before installation or before PAGE init, sorry.
9265 return $info;
9268 $filtermanager = filter_manager::instance();
9269 if (method_exists($filtermanager, 'get_performance_summary')) {
9270 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9271 $info = array_merge($filterinfo, $info);
9272 foreach ($filterinfo as $key => $value) {
9273 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9274 $info['txt'] .= "$key: $value ";
9278 $stringmanager = get_string_manager();
9279 if (method_exists($stringmanager, 'get_performance_summary')) {
9280 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9281 $info = array_merge($filterinfo, $info);
9282 foreach ($filterinfo as $key => $value) {
9283 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9284 $info['txt'] .= "$key: $value ";
9288 if (!empty($PERF->logwrites)) {
9289 $info['logwrites'] = $PERF->logwrites;
9290 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9291 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9294 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9295 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9296 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9298 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9299 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9300 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9302 if (function_exists('posix_times')) {
9303 $ptimes = posix_times();
9304 if (is_array($ptimes)) {
9305 foreach ($ptimes as $key => $val) {
9306 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9308 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9309 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9310 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9314 // Grab the load average for the last minute.
9315 // /proc will only work under some linux configurations
9316 // while uptime is there under MacOSX/Darwin and other unices.
9317 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9318 list($serverload) = explode(' ', $loadavg[0]);
9319 unset($loadavg);
9320 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9321 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9322 $serverload = $matches[1];
9323 } else {
9324 trigger_error('Could not parse uptime output!');
9327 if (!empty($serverload)) {
9328 $info['serverload'] = $serverload;
9329 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9330 $info['txt'] .= "serverload: {$info['serverload']} ";
9333 // Display size of session if session started.
9334 if ($si = \core\session\manager::get_performance_info()) {
9335 $info['sessionsize'] = $si['size'];
9336 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9337 $info['txt'] .= $si['txt'];
9340 $info['html'] .= '</ul>';
9341 if ($stats = cache_helper::get_stats()) {
9342 $html = '<ul class="cachesused list-unstyled m-l-1 row">';
9343 $html .= '<li class="cache-stats-heading font-weight-bold">Caches used (hits/misses/sets)</li>';
9344 $html .= '</ul><ul class="cachesused list-unstyled m-l-1">';
9345 $text = 'Caches used (hits/misses/sets): ';
9346 $hits = 0;
9347 $misses = 0;
9348 $sets = 0;
9349 foreach ($stats as $definition => $details) {
9350 switch ($details['mode']) {
9351 case cache_store::MODE_APPLICATION:
9352 $modeclass = 'application';
9353 $mode = ' <span title="application cache">[a]</span>';
9354 break;
9355 case cache_store::MODE_SESSION:
9356 $modeclass = 'session';
9357 $mode = ' <span title="session cache">[s]</span>';
9358 break;
9359 case cache_store::MODE_REQUEST:
9360 $modeclass = 'request';
9361 $mode = ' <span title="request cache">[r]</span>';
9362 break;
9364 $html .= '<ul class="cache-definition-stats list-unstyled m-l-1 m-b-1 cache-mode-'.$modeclass.' card d-inline-block">';
9365 $html .= '<li class="cache-definition-stats-heading p-t-1 card-header bg-dark bg-inverse font-weight-bold">' .
9366 $definition . $mode.'</li>';
9367 $text .= "$definition {";
9368 foreach ($details['stores'] as $store => $data) {
9369 $hits += $data['hits'];
9370 $misses += $data['misses'];
9371 $sets += $data['sets'];
9372 if ($data['hits'] == 0 and $data['misses'] > 0) {
9373 $cachestoreclass = 'nohits text-danger';
9374 } else if ($data['hits'] < $data['misses']) {
9375 $cachestoreclass = 'lowhits text-warning';
9376 } else {
9377 $cachestoreclass = 'hihits text-success';
9379 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9380 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">" .
9381 "$store: $data[hits] / $data[misses] / $data[sets]</li>";
9382 // This makes boxes of same sizes.
9383 if (count($details['stores']) == 1) {
9384 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">&nbsp;</li>";
9387 $html .= '</ul>';
9388 $text .= '} ';
9390 $html .= '</ul> ';
9391 $html .= "<div class='cache-total-stats row'>Total: $hits / $misses / $sets</div>";
9392 $info['cachesused'] = "$hits / $misses / $sets";
9393 $info['html'] .= $html;
9394 $info['txt'] .= $text.'. ';
9395 } else {
9396 $info['cachesused'] = '0 / 0 / 0';
9397 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9398 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9401 $info['html'] = '<div class="performanceinfo siteinfo container-fluid">'.$info['html'].'</div>';
9402 return $info;
9406 * Delete directory or only its content
9408 * @param string $dir directory path
9409 * @param bool $contentonly
9410 * @return bool success, true also if dir does not exist
9412 function remove_dir($dir, $contentonly=false) {
9413 if (!file_exists($dir)) {
9414 // Nothing to do.
9415 return true;
9417 if (!$handle = opendir($dir)) {
9418 return false;
9420 $result = true;
9421 while (false!==($item = readdir($handle))) {
9422 if ($item != '.' && $item != '..') {
9423 if (is_dir($dir.'/'.$item)) {
9424 $result = remove_dir($dir.'/'.$item) && $result;
9425 } else {
9426 $result = unlink($dir.'/'.$item) && $result;
9430 closedir($handle);
9431 if ($contentonly) {
9432 clearstatcache(); // Make sure file stat cache is properly invalidated.
9433 return $result;
9435 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9436 clearstatcache(); // Make sure file stat cache is properly invalidated.
9437 return $result;
9441 * Detect if an object or a class contains a given property
9442 * will take an actual object or the name of a class
9444 * @param mix $obj Name of class or real object to test
9445 * @param string $property name of property to find
9446 * @return bool true if property exists
9448 function object_property_exists( $obj, $property ) {
9449 if (is_string( $obj )) {
9450 $properties = get_class_vars( $obj );
9451 } else {
9452 $properties = get_object_vars( $obj );
9454 return array_key_exists( $property, $properties );
9458 * Converts an object into an associative array
9460 * This function converts an object into an associative array by iterating
9461 * over its public properties. Because this function uses the foreach
9462 * construct, Iterators are respected. It works recursively on arrays of objects.
9463 * Arrays and simple values are returned as is.
9465 * If class has magic properties, it can implement IteratorAggregate
9466 * and return all available properties in getIterator()
9468 * @param mixed $var
9469 * @return array
9471 function convert_to_array($var) {
9472 $result = array();
9474 // Loop over elements/properties.
9475 foreach ($var as $key => $value) {
9476 // Recursively convert objects.
9477 if (is_object($value) || is_array($value)) {
9478 $result[$key] = convert_to_array($value);
9479 } else {
9480 // Simple values are untouched.
9481 $result[$key] = $value;
9484 return $result;
9488 * Detect a custom script replacement in the data directory that will
9489 * replace an existing moodle script
9491 * @return string|bool full path name if a custom script exists, false if no custom script exists
9493 function custom_script_path() {
9494 global $CFG, $SCRIPT;
9496 if ($SCRIPT === null) {
9497 // Probably some weird external script.
9498 return false;
9501 $scriptpath = $CFG->customscripts . $SCRIPT;
9503 // Check the custom script exists.
9504 if (file_exists($scriptpath) and is_file($scriptpath)) {
9505 return $scriptpath;
9506 } else {
9507 return false;
9512 * Returns whether or not the user object is a remote MNET user. This function
9513 * is in moodlelib because it does not rely on loading any of the MNET code.
9515 * @param object $user A valid user object
9516 * @return bool True if the user is from a remote Moodle.
9518 function is_mnet_remote_user($user) {
9519 global $CFG;
9521 if (!isset($CFG->mnet_localhost_id)) {
9522 include_once($CFG->dirroot . '/mnet/lib.php');
9523 $env = new mnet_environment();
9524 $env->init();
9525 unset($env);
9528 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9532 * This function will search for browser prefereed languages, setting Moodle
9533 * to use the best one available if $SESSION->lang is undefined
9535 function setup_lang_from_browser() {
9536 global $CFG, $SESSION, $USER;
9538 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9539 // Lang is defined in session or user profile, nothing to do.
9540 return;
9543 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9544 return;
9547 // Extract and clean langs from headers.
9548 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9549 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9550 $rawlangs = explode(',', $rawlangs); // Convert to array.
9551 $langs = array();
9553 $order = 1.0;
9554 foreach ($rawlangs as $lang) {
9555 if (strpos($lang, ';') === false) {
9556 $langs[(string)$order] = $lang;
9557 $order = $order-0.01;
9558 } else {
9559 $parts = explode(';', $lang);
9560 $pos = strpos($parts[1], '=');
9561 $langs[substr($parts[1], $pos+1)] = $parts[0];
9564 krsort($langs, SORT_NUMERIC);
9566 // Look for such langs under standard locations.
9567 foreach ($langs as $lang) {
9568 // Clean it properly for include.
9569 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9570 if (get_string_manager()->translation_exists($lang, false)) {
9571 // Lang exists, set it in session.
9572 $SESSION->lang = $lang;
9573 // We have finished. Go out.
9574 break;
9577 return;
9581 * Check if $url matches anything in proxybypass list
9583 * Any errors just result in the proxy being used (least bad)
9585 * @param string $url url to check
9586 * @return boolean true if we should bypass the proxy
9588 function is_proxybypass( $url ) {
9589 global $CFG;
9591 // Sanity check.
9592 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9593 return false;
9596 // Get the host part out of the url.
9597 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9598 return false;
9601 // Get the possible bypass hosts into an array.
9602 $matches = explode( ',', $CFG->proxybypass );
9604 // Check for a match.
9605 // (IPs need to match the left hand side and hosts the right of the url,
9606 // but we can recklessly check both as there can't be a false +ve).
9607 foreach ($matches as $match) {
9608 $match = trim($match);
9610 // Try for IP match (Left side).
9611 $lhs = substr($host, 0, strlen($match));
9612 if (strcasecmp($match, $lhs)==0) {
9613 return true;
9616 // Try for host match (Right side).
9617 $rhs = substr($host, -strlen($match));
9618 if (strcasecmp($match, $rhs)==0) {
9619 return true;
9623 // Nothing matched.
9624 return false;
9628 * Check if the passed navigation is of the new style
9630 * @param mixed $navigation
9631 * @return bool true for yes false for no
9633 function is_newnav($navigation) {
9634 if (is_array($navigation) && !empty($navigation['newnav'])) {
9635 return true;
9636 } else {
9637 return false;
9642 * Checks whether the given variable name is defined as a variable within the given object.
9644 * This will NOT work with stdClass objects, which have no class variables.
9646 * @param string $var The variable name
9647 * @param object $object The object to check
9648 * @return boolean
9650 function in_object_vars($var, $object) {
9651 $classvars = get_class_vars(get_class($object));
9652 $classvars = array_keys($classvars);
9653 return in_array($var, $classvars);
9657 * Returns an array without repeated objects.
9658 * This function is similar to array_unique, but for arrays that have objects as values
9660 * @param array $array
9661 * @param bool $keepkeyassoc
9662 * @return array
9664 function object_array_unique($array, $keepkeyassoc = true) {
9665 $duplicatekeys = array();
9666 $tmp = array();
9668 foreach ($array as $key => $val) {
9669 // Convert objects to arrays, in_array() does not support objects.
9670 if (is_object($val)) {
9671 $val = (array)$val;
9674 if (!in_array($val, $tmp)) {
9675 $tmp[] = $val;
9676 } else {
9677 $duplicatekeys[] = $key;
9681 foreach ($duplicatekeys as $key) {
9682 unset($array[$key]);
9685 return $keepkeyassoc ? $array : array_values($array);
9689 * Is a userid the primary administrator?
9691 * @param int $userid int id of user to check
9692 * @return boolean
9694 function is_primary_admin($userid) {
9695 $primaryadmin = get_admin();
9697 if ($userid == $primaryadmin->id) {
9698 return true;
9699 } else {
9700 return false;
9705 * Returns the site identifier
9707 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9709 function get_site_identifier() {
9710 global $CFG;
9711 // Check to see if it is missing. If so, initialise it.
9712 if (empty($CFG->siteidentifier)) {
9713 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9715 // Return it.
9716 return $CFG->siteidentifier;
9720 * Check whether the given password has no more than the specified
9721 * number of consecutive identical characters.
9723 * @param string $password password to be checked against the password policy
9724 * @param integer $maxchars maximum number of consecutive identical characters
9725 * @return bool
9727 function check_consecutive_identical_characters($password, $maxchars) {
9729 if ($maxchars < 1) {
9730 return true; // Zero 0 is to disable this check.
9732 if (strlen($password) <= $maxchars) {
9733 return true; // Too short to fail this test.
9736 $previouschar = '';
9737 $consecutivecount = 1;
9738 foreach (str_split($password) as $char) {
9739 if ($char != $previouschar) {
9740 $consecutivecount = 1;
9741 } else {
9742 $consecutivecount++;
9743 if ($consecutivecount > $maxchars) {
9744 return false; // Check failed already.
9748 $previouschar = $char;
9751 return true;
9755 * Helper function to do partial function binding.
9756 * so we can use it for preg_replace_callback, for example
9757 * this works with php functions, user functions, static methods and class methods
9758 * it returns you a callback that you can pass on like so:
9760 * $callback = partial('somefunction', $arg1, $arg2);
9761 * or
9762 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9763 * or even
9764 * $obj = new someclass();
9765 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9767 * and then the arguments that are passed through at calltime are appended to the argument list.
9769 * @param mixed $function a php callback
9770 * @param mixed $arg1,... $argv arguments to partially bind with
9771 * @return array Array callback
9773 function partial() {
9774 if (!class_exists('partial')) {
9776 * Used to manage function binding.
9777 * @copyright 2009 Penny Leach
9778 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9780 class partial{
9781 /** @var array */
9782 public $values = array();
9783 /** @var string The function to call as a callback. */
9784 public $func;
9786 * Constructor
9787 * @param string $func
9788 * @param array $args
9790 public function __construct($func, $args) {
9791 $this->values = $args;
9792 $this->func = $func;
9795 * Calls the callback function.
9796 * @return mixed
9798 public function method() {
9799 $args = func_get_args();
9800 return call_user_func_array($this->func, array_merge($this->values, $args));
9804 $args = func_get_args();
9805 $func = array_shift($args);
9806 $p = new partial($func, $args);
9807 return array($p, 'method');
9811 * helper function to load up and initialise the mnet environment
9812 * this must be called before you use mnet functions.
9814 * @return mnet_environment the equivalent of old $MNET global
9816 function get_mnet_environment() {
9817 global $CFG;
9818 require_once($CFG->dirroot . '/mnet/lib.php');
9819 static $instance = null;
9820 if (empty($instance)) {
9821 $instance = new mnet_environment();
9822 $instance->init();
9824 return $instance;
9828 * during xmlrpc server code execution, any code wishing to access
9829 * information about the remote peer must use this to get it.
9831 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9833 function get_mnet_remote_client() {
9834 if (!defined('MNET_SERVER')) {
9835 debugging(get_string('notinxmlrpcserver', 'mnet'));
9836 return false;
9838 global $MNET_REMOTE_CLIENT;
9839 if (isset($MNET_REMOTE_CLIENT)) {
9840 return $MNET_REMOTE_CLIENT;
9842 return false;
9846 * during the xmlrpc server code execution, this will be called
9847 * to setup the object returned by {@link get_mnet_remote_client}
9849 * @param mnet_remote_client $client the client to set up
9850 * @throws moodle_exception
9852 function set_mnet_remote_client($client) {
9853 if (!defined('MNET_SERVER')) {
9854 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9856 global $MNET_REMOTE_CLIENT;
9857 $MNET_REMOTE_CLIENT = $client;
9861 * return the jump url for a given remote user
9862 * this is used for rewriting forum post links in emails, etc
9864 * @param stdclass $user the user to get the idp url for
9866 function mnet_get_idp_jump_url($user) {
9867 global $CFG;
9869 static $mnetjumps = array();
9870 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9871 $idp = mnet_get_peer_host($user->mnethostid);
9872 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9873 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9875 return $mnetjumps[$user->mnethostid];
9879 * Gets the homepage to use for the current user
9881 * @return int One of HOMEPAGE_*
9883 function get_home_page() {
9884 global $CFG;
9886 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9887 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9888 return HOMEPAGE_MY;
9889 } else {
9890 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9893 return HOMEPAGE_SITE;
9897 * Gets the name of a course to be displayed when showing a list of courses.
9898 * By default this is just $course->fullname but user can configure it. The
9899 * result of this function should be passed through print_string.
9900 * @param stdClass|core_course_list_element $course Moodle course object
9901 * @return string Display name of course (either fullname or short + fullname)
9903 function get_course_display_name_for_list($course) {
9904 global $CFG;
9905 if (!empty($CFG->courselistshortnames)) {
9906 if (!($course instanceof stdClass)) {
9907 $course = (object)convert_to_array($course);
9909 return get_string('courseextendednamedisplay', '', $course);
9910 } else {
9911 return $course->fullname;
9916 * Safe analogue of unserialize() that can only parse arrays
9918 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
9919 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
9920 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
9922 * @param string $expression
9923 * @return array|bool either parsed array or false if parsing was impossible.
9925 function unserialize_array($expression) {
9926 $subs = [];
9927 // Find nested arrays, parse them and store in $subs , substitute with special string.
9928 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
9929 $key = '--SUB' . count($subs) . '--';
9930 $subs[$key] = unserialize_array($matches[2]);
9931 if ($subs[$key] === false) {
9932 return false;
9934 $expression = str_replace($matches[2], $key . ';', $expression);
9937 // Check the expression is an array.
9938 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
9939 return false;
9941 // Get the size and elements of an array (key;value;key;value;....).
9942 $parts = explode(';', $matches1[2]);
9943 $size = intval($matches1[1]);
9944 if (count($parts) < $size * 2 + 1) {
9945 return false;
9947 // Analyze each part and make sure it is an integer or string or a substitute.
9948 $value = [];
9949 for ($i = 0; $i < $size * 2; $i++) {
9950 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
9951 $parts[$i] = (int)$matches2[1];
9952 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
9953 $parts[$i] = $matches3[2];
9954 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
9955 $parts[$i] = $subs[$parts[$i]];
9956 } else {
9957 return false;
9960 // Combine keys and values.
9961 for ($i = 0; $i < $size * 2; $i += 2) {
9962 $value[$parts[$i]] = $parts[$i+1];
9964 return $value;
9968 * The lang_string class
9970 * This special class is used to create an object representation of a string request.
9971 * It is special because processing doesn't occur until the object is first used.
9972 * The class was created especially to aid performance in areas where strings were
9973 * required to be generated but were not necessarily used.
9974 * As an example the admin tree when generated uses over 1500 strings, of which
9975 * normally only 1/3 are ever actually printed at any time.
9976 * The performance advantage is achieved by not actually processing strings that
9977 * arn't being used, as such reducing the processing required for the page.
9979 * How to use the lang_string class?
9980 * There are two methods of using the lang_string class, first through the
9981 * forth argument of the get_string function, and secondly directly.
9982 * The following are examples of both.
9983 * 1. Through get_string calls e.g.
9984 * $string = get_string($identifier, $component, $a, true);
9985 * $string = get_string('yes', 'moodle', null, true);
9986 * 2. Direct instantiation
9987 * $string = new lang_string($identifier, $component, $a, $lang);
9988 * $string = new lang_string('yes');
9990 * How do I use a lang_string object?
9991 * The lang_string object makes use of a magic __toString method so that you
9992 * are able to use the object exactly as you would use a string in most cases.
9993 * This means you are able to collect it into a variable and then directly
9994 * echo it, or concatenate it into another string, or similar.
9995 * The other thing you can do is manually get the string by calling the
9996 * lang_strings out method e.g.
9997 * $string = new lang_string('yes');
9998 * $string->out();
9999 * Also worth noting is that the out method can take one argument, $lang which
10000 * allows the developer to change the language on the fly.
10002 * When should I use a lang_string object?
10003 * The lang_string object is designed to be used in any situation where a
10004 * string may not be needed, but needs to be generated.
10005 * The admin tree is a good example of where lang_string objects should be
10006 * used.
10007 * A more practical example would be any class that requries strings that may
10008 * not be printed (after all classes get renderer by renderers and who knows
10009 * what they will do ;))
10011 * When should I not use a lang_string object?
10012 * Don't use lang_strings when you are going to use a string immediately.
10013 * There is no need as it will be processed immediately and there will be no
10014 * advantage, and in fact perhaps a negative hit as a class has to be
10015 * instantiated for a lang_string object, however get_string won't require
10016 * that.
10018 * Limitations:
10019 * 1. You cannot use a lang_string object as an array offset. Doing so will
10020 * result in PHP throwing an error. (You can use it as an object property!)
10022 * @package core
10023 * @category string
10024 * @copyright 2011 Sam Hemelryk
10025 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10027 class lang_string {
10029 /** @var string The strings identifier */
10030 protected $identifier;
10031 /** @var string The strings component. Default '' */
10032 protected $component = '';
10033 /** @var array|stdClass Any arguments required for the string. Default null */
10034 protected $a = null;
10035 /** @var string The language to use when processing the string. Default null */
10036 protected $lang = null;
10038 /** @var string The processed string (once processed) */
10039 protected $string = null;
10042 * A special boolean. If set to true then the object has been woken up and
10043 * cannot be regenerated. If this is set then $this->string MUST be used.
10044 * @var bool
10046 protected $forcedstring = false;
10049 * Constructs a lang_string object
10051 * This function should do as little processing as possible to ensure the best
10052 * performance for strings that won't be used.
10054 * @param string $identifier The strings identifier
10055 * @param string $component The strings component
10056 * @param stdClass|array $a Any arguments the string requires
10057 * @param string $lang The language to use when processing the string.
10058 * @throws coding_exception
10060 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10061 if (empty($component)) {
10062 $component = 'moodle';
10065 $this->identifier = $identifier;
10066 $this->component = $component;
10067 $this->lang = $lang;
10069 // We MUST duplicate $a to ensure that it if it changes by reference those
10070 // changes are not carried across.
10071 // To do this we always ensure $a or its properties/values are strings
10072 // and that any properties/values that arn't convertable are forgotten.
10073 if (!empty($a)) {
10074 if (is_scalar($a)) {
10075 $this->a = $a;
10076 } else if ($a instanceof lang_string) {
10077 $this->a = $a->out();
10078 } else if (is_object($a) or is_array($a)) {
10079 $a = (array)$a;
10080 $this->a = array();
10081 foreach ($a as $key => $value) {
10082 // Make sure conversion errors don't get displayed (results in '').
10083 if (is_array($value)) {
10084 $this->a[$key] = '';
10085 } else if (is_object($value)) {
10086 if (method_exists($value, '__toString')) {
10087 $this->a[$key] = $value->__toString();
10088 } else {
10089 $this->a[$key] = '';
10091 } else {
10092 $this->a[$key] = (string)$value;
10098 if (debugging(false, DEBUG_DEVELOPER)) {
10099 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10100 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10102 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10103 throw new coding_exception('Invalid string compontent. Please check your string definition');
10105 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10106 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10112 * Processes the string.
10114 * This function actually processes the string, stores it in the string property
10115 * and then returns it.
10116 * You will notice that this function is VERY similar to the get_string method.
10117 * That is because it is pretty much doing the same thing.
10118 * However as this function is an upgrade it isn't as tolerant to backwards
10119 * compatibility.
10121 * @return string
10122 * @throws coding_exception
10124 protected function get_string() {
10125 global $CFG;
10127 // Check if we need to process the string.
10128 if ($this->string === null) {
10129 // Check the quality of the identifier.
10130 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10131 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);
10134 // Process the string.
10135 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10136 // Debugging feature lets you display string identifier and component.
10137 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10138 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10141 // Return the string.
10142 return $this->string;
10146 * Returns the string
10148 * @param string $lang The langauge to use when processing the string
10149 * @return string
10151 public function out($lang = null) {
10152 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10153 if ($this->forcedstring) {
10154 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10155 return $this->get_string();
10157 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10158 return $translatedstring->out();
10160 return $this->get_string();
10164 * Magic __toString method for printing a string
10166 * @return string
10168 public function __toString() {
10169 return $this->get_string();
10173 * Magic __set_state method used for var_export
10175 * @return string
10177 public function __set_state() {
10178 return $this->get_string();
10182 * Prepares the lang_string for sleep and stores only the forcedstring and
10183 * string properties... the string cannot be regenerated so we need to ensure
10184 * it is generated for this.
10186 * @return string
10188 public function __sleep() {
10189 $this->get_string();
10190 $this->forcedstring = true;
10191 return array('forcedstring', 'string', 'lang');
10195 * Returns the identifier.
10197 * @return string
10199 public function get_identifier() {
10200 return $this->identifier;
10204 * Returns the component.
10206 * @return string
10208 public function get_component() {
10209 return $this->component;
10214 * Get human readable name describing the given callable.
10216 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10217 * It does not check if the callable actually exists.
10219 * @param callable|string|array $callable
10220 * @return string|bool Human readable name of callable, or false if not a valid callable.
10222 function get_callable_name($callable) {
10224 if (!is_callable($callable, true, $name)) {
10225 return false;
10227 } else {
10228 return $name;