MDL-62781 question/privacy: fix tests with CodeRunner is installed
[moodle.git] / lib / moodlelib.php
blob47cf0b1068fb72caefe5619eae2824ce4c979e85
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 * Return this from modname_get_types callback to use default display in activity chooser.
458 * Deprecated, will be removed in 3.5, TODO MDL-53697.
459 * @deprecated since Moodle 3.1
461 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
464 * Security token used for allowing access
465 * from external application such as web services.
466 * Scripts do not use any session, performance is relatively
467 * low because we need to load access info in each request.
468 * Scripts are executed in parallel.
470 define('EXTERNAL_TOKEN_PERMANENT', 0);
473 * Security token used for allowing access
474 * of embedded applications, the code is executed in the
475 * active user session. Token is invalidated after user logs out.
476 * Scripts are executed serially - normal session locking is used.
478 define('EXTERNAL_TOKEN_EMBEDDED', 1);
481 * The home page should be the site home
483 define('HOMEPAGE_SITE', 0);
485 * The home page should be the users my page
487 define('HOMEPAGE_MY', 1);
489 * The home page can be chosen by the user
491 define('HOMEPAGE_USER', 2);
494 * Hub directory url (should be moodle.org)
496 define('HUB_HUBDIRECTORYURL', "https://hubdirectory.moodle.org");
500 * Moodle.net url (should be moodle.net)
502 define('HUB_MOODLEORGHUBURL', "https://moodle.net");
503 define('HUB_OLDMOODLEORGHUBURL', "http://hub.moodle.org");
506 * Moodle mobile app service name
508 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
511 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
513 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
516 * Course display settings: display all sections on one page.
518 define('COURSE_DISPLAY_SINGLEPAGE', 0);
520 * Course display settings: split pages into a page per section.
522 define('COURSE_DISPLAY_MULTIPAGE', 1);
525 * Authentication constant: String used in password field when password is not stored.
527 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
530 * Email from header to never include via information.
532 define('EMAIL_VIA_NEVER', 0);
535 * Email from header to always include via information.
537 define('EMAIL_VIA_ALWAYS', 1);
540 * Email from header to only include via information if the address is no-reply.
542 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
544 // PARAMETER HANDLING.
547 * Returns a particular value for the named variable, taken from
548 * POST or GET. If the parameter doesn't exist then an error is
549 * thrown because we require this variable.
551 * This function should be used to initialise all required values
552 * in a script that are based on parameters. Usually it will be
553 * used like this:
554 * $id = required_param('id', PARAM_INT);
556 * Please note the $type parameter is now required and the value can not be array.
558 * @param string $parname the name of the page parameter we want
559 * @param string $type expected type of parameter
560 * @return mixed
561 * @throws coding_exception
563 function required_param($parname, $type) {
564 if (func_num_args() != 2 or empty($parname) or empty($type)) {
565 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
567 // POST has precedence.
568 if (isset($_POST[$parname])) {
569 $param = $_POST[$parname];
570 } else if (isset($_GET[$parname])) {
571 $param = $_GET[$parname];
572 } else {
573 print_error('missingparam', '', '', $parname);
576 if (is_array($param)) {
577 debugging('Invalid array parameter detected in required_param(): '.$parname);
578 // TODO: switch to fatal error in Moodle 2.3.
579 return required_param_array($parname, $type);
582 return clean_param($param, $type);
586 * Returns a particular array value for the named variable, taken from
587 * POST or GET. If the parameter doesn't exist then an error is
588 * thrown because we require this variable.
590 * This function should be used to initialise all required values
591 * in a script that are based on parameters. Usually it will be
592 * used like this:
593 * $ids = required_param_array('ids', PARAM_INT);
595 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
597 * @param string $parname the name of the page parameter we want
598 * @param string $type expected type of parameter
599 * @return array
600 * @throws coding_exception
602 function required_param_array($parname, $type) {
603 if (func_num_args() != 2 or empty($parname) or empty($type)) {
604 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
606 // POST has precedence.
607 if (isset($_POST[$parname])) {
608 $param = $_POST[$parname];
609 } else if (isset($_GET[$parname])) {
610 $param = $_GET[$parname];
611 } else {
612 print_error('missingparam', '', '', $parname);
614 if (!is_array($param)) {
615 print_error('missingparam', '', '', $parname);
618 $result = array();
619 foreach ($param as $key => $value) {
620 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
621 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
622 continue;
624 $result[$key] = clean_param($value, $type);
627 return $result;
631 * Returns a particular value for the named variable, taken from
632 * POST or GET, otherwise returning a given default.
634 * This function should be used to initialise all optional values
635 * in a script that are based on parameters. Usually it will be
636 * used like this:
637 * $name = optional_param('name', 'Fred', PARAM_TEXT);
639 * Please note the $type parameter is now required and the value can not be array.
641 * @param string $parname the name of the page parameter we want
642 * @param mixed $default the default value to return if nothing is found
643 * @param string $type expected type of parameter
644 * @return mixed
645 * @throws coding_exception
647 function optional_param($parname, $default, $type) {
648 if (func_num_args() != 3 or empty($parname) or empty($type)) {
649 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
652 // POST has precedence.
653 if (isset($_POST[$parname])) {
654 $param = $_POST[$parname];
655 } else if (isset($_GET[$parname])) {
656 $param = $_GET[$parname];
657 } else {
658 return $default;
661 if (is_array($param)) {
662 debugging('Invalid array parameter detected in required_param(): '.$parname);
663 // TODO: switch to $default in Moodle 2.3.
664 return optional_param_array($parname, $default, $type);
667 return clean_param($param, $type);
671 * Returns a particular array value for the named variable, taken from
672 * POST or GET, otherwise returning a given default.
674 * This function should be used to initialise all optional values
675 * in a script that are based on parameters. Usually it will be
676 * used like this:
677 * $ids = optional_param('id', array(), PARAM_INT);
679 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
681 * @param string $parname the name of the page parameter we want
682 * @param mixed $default the default value to return if nothing is found
683 * @param string $type expected type of parameter
684 * @return array
685 * @throws coding_exception
687 function optional_param_array($parname, $default, $type) {
688 if (func_num_args() != 3 or empty($parname) or empty($type)) {
689 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
692 // POST has precedence.
693 if (isset($_POST[$parname])) {
694 $param = $_POST[$parname];
695 } else if (isset($_GET[$parname])) {
696 $param = $_GET[$parname];
697 } else {
698 return $default;
700 if (!is_array($param)) {
701 debugging('optional_param_array() expects array parameters only: '.$parname);
702 return $default;
705 $result = array();
706 foreach ($param as $key => $value) {
707 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
708 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
709 continue;
711 $result[$key] = clean_param($value, $type);
714 return $result;
718 * Strict validation of parameter values, the values are only converted
719 * to requested PHP type. Internally it is using clean_param, the values
720 * before and after cleaning must be equal - otherwise
721 * an invalid_parameter_exception is thrown.
722 * Objects and classes are not accepted.
724 * @param mixed $param
725 * @param string $type PARAM_ constant
726 * @param bool $allownull are nulls valid value?
727 * @param string $debuginfo optional debug information
728 * @return mixed the $param value converted to PHP type
729 * @throws invalid_parameter_exception if $param is not of given type
731 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
732 if (is_null($param)) {
733 if ($allownull == NULL_ALLOWED) {
734 return null;
735 } else {
736 throw new invalid_parameter_exception($debuginfo);
739 if (is_array($param) or is_object($param)) {
740 throw new invalid_parameter_exception($debuginfo);
743 $cleaned = clean_param($param, $type);
745 if ($type == PARAM_FLOAT) {
746 // Do not detect precision loss here.
747 if (is_float($param) or is_int($param)) {
748 // These always fit.
749 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
750 throw new invalid_parameter_exception($debuginfo);
752 } else if ((string)$param !== (string)$cleaned) {
753 // Conversion to string is usually lossless.
754 throw new invalid_parameter_exception($debuginfo);
757 return $cleaned;
761 * Makes sure array contains only the allowed types, this function does not validate array key names!
763 * <code>
764 * $options = clean_param($options, PARAM_INT);
765 * </code>
767 * @param array $param the variable array we are cleaning
768 * @param string $type expected format of param after cleaning.
769 * @param bool $recursive clean recursive arrays
770 * @return array
771 * @throws coding_exception
773 function clean_param_array(array $param = null, $type, $recursive = false) {
774 // Convert null to empty array.
775 $param = (array)$param;
776 foreach ($param as $key => $value) {
777 if (is_array($value)) {
778 if ($recursive) {
779 $param[$key] = clean_param_array($value, $type, true);
780 } else {
781 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
783 } else {
784 $param[$key] = clean_param($value, $type);
787 return $param;
791 * Used by {@link optional_param()} and {@link required_param()} to
792 * clean the variables and/or cast to specific types, based on
793 * an options field.
794 * <code>
795 * $course->format = clean_param($course->format, PARAM_ALPHA);
796 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
797 * </code>
799 * @param mixed $param the variable we are cleaning
800 * @param string $type expected format of param after cleaning.
801 * @return mixed
802 * @throws coding_exception
804 function clean_param($param, $type) {
805 global $CFG;
807 if (is_array($param)) {
808 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
809 } else if (is_object($param)) {
810 if (method_exists($param, '__toString')) {
811 $param = $param->__toString();
812 } else {
813 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
817 switch ($type) {
818 case PARAM_RAW:
819 // No cleaning at all.
820 $param = fix_utf8($param);
821 return $param;
823 case PARAM_RAW_TRIMMED:
824 // No cleaning, but strip leading and trailing whitespace.
825 $param = fix_utf8($param);
826 return trim($param);
828 case PARAM_CLEAN:
829 // General HTML cleaning, try to use more specific type if possible this is deprecated!
830 // Please use more specific type instead.
831 if (is_numeric($param)) {
832 return $param;
834 $param = fix_utf8($param);
835 // Sweep for scripts, etc.
836 return clean_text($param);
838 case PARAM_CLEANHTML:
839 // Clean html fragment.
840 $param = fix_utf8($param);
841 // Sweep for scripts, etc.
842 $param = clean_text($param, FORMAT_HTML);
843 return trim($param);
845 case PARAM_INT:
846 // Convert to integer.
847 return (int)$param;
849 case PARAM_FLOAT:
850 // Convert to float.
851 return (float)$param;
853 case PARAM_ALPHA:
854 // Remove everything not `a-z`.
855 return preg_replace('/[^a-zA-Z]/i', '', $param);
857 case PARAM_ALPHAEXT:
858 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
859 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
861 case PARAM_ALPHANUM:
862 // Remove everything not `a-zA-Z0-9`.
863 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
865 case PARAM_ALPHANUMEXT:
866 // Remove everything not `a-zA-Z0-9_-`.
867 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
869 case PARAM_SEQUENCE:
870 // Remove everything not `0-9,`.
871 return preg_replace('/[^0-9,]/i', '', $param);
873 case PARAM_BOOL:
874 // Convert to 1 or 0.
875 $tempstr = strtolower($param);
876 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
877 $param = 1;
878 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
879 $param = 0;
880 } else {
881 $param = empty($param) ? 0 : 1;
883 return $param;
885 case PARAM_NOTAGS:
886 // Strip all tags.
887 $param = fix_utf8($param);
888 return strip_tags($param);
890 case PARAM_TEXT:
891 // Leave only tags needed for multilang.
892 $param = fix_utf8($param);
893 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
894 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
895 do {
896 if (strpos($param, '</lang>') !== false) {
897 // Old and future mutilang syntax.
898 $param = strip_tags($param, '<lang>');
899 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
900 break;
902 $open = false;
903 foreach ($matches[0] as $match) {
904 if ($match === '</lang>') {
905 if ($open) {
906 $open = false;
907 continue;
908 } else {
909 break 2;
912 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
913 break 2;
914 } else {
915 $open = true;
918 if ($open) {
919 break;
921 return $param;
923 } else if (strpos($param, '</span>') !== false) {
924 // Current problematic multilang syntax.
925 $param = strip_tags($param, '<span>');
926 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
927 break;
929 $open = false;
930 foreach ($matches[0] as $match) {
931 if ($match === '</span>') {
932 if ($open) {
933 $open = false;
934 continue;
935 } else {
936 break 2;
939 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
940 break 2;
941 } else {
942 $open = true;
945 if ($open) {
946 break;
948 return $param;
950 } while (false);
951 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
952 return strip_tags($param);
954 case PARAM_COMPONENT:
955 // We do not want any guessing here, either the name is correct or not
956 // please note only normalised component names are accepted.
957 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
958 return '';
960 if (strpos($param, '__') !== false) {
961 return '';
963 if (strpos($param, 'mod_') === 0) {
964 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
965 if (substr_count($param, '_') != 1) {
966 return '';
969 return $param;
971 case PARAM_PLUGIN:
972 case PARAM_AREA:
973 // We do not want any guessing here, either the name is correct or not.
974 if (!is_valid_plugin_name($param)) {
975 return '';
977 return $param;
979 case PARAM_SAFEDIR:
980 // Remove everything not a-zA-Z0-9_- .
981 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
983 case PARAM_SAFEPATH:
984 // Remove everything not a-zA-Z0-9/_- .
985 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
987 case PARAM_FILE:
988 // Strip all suspicious characters from filename.
989 $param = fix_utf8($param);
990 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
991 if ($param === '.' || $param === '..') {
992 $param = '';
994 return $param;
996 case PARAM_PATH:
997 // Strip all suspicious characters from file path.
998 $param = fix_utf8($param);
999 $param = str_replace('\\', '/', $param);
1001 // Explode the path and clean each element using the PARAM_FILE rules.
1002 $breadcrumb = explode('/', $param);
1003 foreach ($breadcrumb as $key => $crumb) {
1004 if ($crumb === '.' && $key === 0) {
1005 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1006 } else {
1007 $crumb = clean_param($crumb, PARAM_FILE);
1009 $breadcrumb[$key] = $crumb;
1011 $param = implode('/', $breadcrumb);
1013 // Remove multiple current path (./././) and multiple slashes (///).
1014 $param = preg_replace('~//+~', '/', $param);
1015 $param = preg_replace('~/(\./)+~', '/', $param);
1016 return $param;
1018 case PARAM_HOST:
1019 // Allow FQDN or IPv4 dotted quad.
1020 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1021 // Match ipv4 dotted quad.
1022 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1023 // Confirm values are ok.
1024 if ( $match[0] > 255
1025 || $match[1] > 255
1026 || $match[3] > 255
1027 || $match[4] > 255 ) {
1028 // Hmmm, what kind of dotted quad is this?
1029 $param = '';
1031 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1032 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1033 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1035 // All is ok - $param is respected.
1036 } else {
1037 // All is not ok...
1038 $param='';
1040 return $param;
1042 case PARAM_URL:
1043 // Allow safe urls.
1044 $param = fix_utf8($param);
1045 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1046 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1047 // All is ok, param is respected.
1048 } else {
1049 // Not really ok.
1050 $param ='';
1052 return $param;
1054 case PARAM_LOCALURL:
1055 // Allow http absolute, root relative and relative URLs within wwwroot.
1056 $param = clean_param($param, PARAM_URL);
1057 if (!empty($param)) {
1059 if ($param === $CFG->wwwroot) {
1060 // Exact match;
1061 } else if (preg_match(':^/:', $param)) {
1062 // Root-relative, ok!
1063 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1064 // Absolute, and matches our wwwroot.
1065 } else {
1066 // Relative - let's make sure there are no tricks.
1067 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1068 // Looks ok.
1069 } else {
1070 $param = '';
1074 return $param;
1076 case PARAM_PEM:
1077 $param = trim($param);
1078 // PEM formatted strings may contain letters/numbers and the symbols:
1079 // forward slash: /
1080 // plus sign: +
1081 // equal sign: =
1082 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1083 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1084 list($wholething, $body) = $matches;
1085 unset($wholething, $matches);
1086 $b64 = clean_param($body, PARAM_BASE64);
1087 if (!empty($b64)) {
1088 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1089 } else {
1090 return '';
1093 return '';
1095 case PARAM_BASE64:
1096 if (!empty($param)) {
1097 // PEM formatted strings may contain letters/numbers and the symbols
1098 // forward slash: /
1099 // plus sign: +
1100 // equal sign: =.
1101 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1102 return '';
1104 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1105 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1106 // than (or equal to) 64 characters long.
1107 for ($i=0, $j=count($lines); $i < $j; $i++) {
1108 if ($i + 1 == $j) {
1109 if (64 < strlen($lines[$i])) {
1110 return '';
1112 continue;
1115 if (64 != strlen($lines[$i])) {
1116 return '';
1119 return implode("\n", $lines);
1120 } else {
1121 return '';
1124 case PARAM_TAG:
1125 $param = fix_utf8($param);
1126 // Please note it is not safe to use the tag name directly anywhere,
1127 // it must be processed with s(), urlencode() before embedding anywhere.
1128 // Remove some nasties.
1129 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1130 // Convert many whitespace chars into one.
1131 $param = preg_replace('/\s+/u', ' ', $param);
1132 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1133 return $param;
1135 case PARAM_TAGLIST:
1136 $param = fix_utf8($param);
1137 $tags = explode(',', $param);
1138 $result = array();
1139 foreach ($tags as $tag) {
1140 $res = clean_param($tag, PARAM_TAG);
1141 if ($res !== '') {
1142 $result[] = $res;
1145 if ($result) {
1146 return implode(',', $result);
1147 } else {
1148 return '';
1151 case PARAM_CAPABILITY:
1152 if (get_capability_info($param)) {
1153 return $param;
1154 } else {
1155 return '';
1158 case PARAM_PERMISSION:
1159 $param = (int)$param;
1160 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1161 return $param;
1162 } else {
1163 return CAP_INHERIT;
1166 case PARAM_AUTH:
1167 $param = clean_param($param, PARAM_PLUGIN);
1168 if (empty($param)) {
1169 return '';
1170 } else if (exists_auth_plugin($param)) {
1171 return $param;
1172 } else {
1173 return '';
1176 case PARAM_LANG:
1177 $param = clean_param($param, PARAM_SAFEDIR);
1178 if (get_string_manager()->translation_exists($param)) {
1179 return $param;
1180 } else {
1181 // Specified language is not installed or param malformed.
1182 return '';
1185 case PARAM_THEME:
1186 $param = clean_param($param, PARAM_PLUGIN);
1187 if (empty($param)) {
1188 return '';
1189 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1190 return $param;
1191 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1192 return $param;
1193 } else {
1194 // Specified theme is not installed.
1195 return '';
1198 case PARAM_USERNAME:
1199 $param = fix_utf8($param);
1200 $param = trim($param);
1201 // Convert uppercase to lowercase MDL-16919.
1202 $param = core_text::strtolower($param);
1203 if (empty($CFG->extendedusernamechars)) {
1204 $param = str_replace(" " , "", $param);
1205 // Regular expression, eliminate all chars EXCEPT:
1206 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1207 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1209 return $param;
1211 case PARAM_EMAIL:
1212 $param = fix_utf8($param);
1213 if (validate_email($param)) {
1214 return $param;
1215 } else {
1216 return '';
1219 case PARAM_STRINGID:
1220 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1221 return $param;
1222 } else {
1223 return '';
1226 case PARAM_TIMEZONE:
1227 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1228 $param = fix_utf8($param);
1229 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1230 if (preg_match($timezonepattern, $param)) {
1231 return $param;
1232 } else {
1233 return '';
1236 default:
1237 // Doh! throw error, switched parameters in optional_param or another serious problem.
1238 print_error("unknownparamtype", '', '', $type);
1243 * Whether the PARAM_* type is compatible in RTL.
1245 * Being compatible with RTL means that the data they contain can flow
1246 * from right-to-left or left-to-right without compromising the user experience.
1248 * Take URLs for example, they are not RTL compatible as they should always
1249 * flow from the left to the right. This also applies to numbers, email addresses,
1250 * configuration snippets, base64 strings, etc...
1252 * This function tries to best guess which parameters can contain localised strings.
1254 * @param string $paramtype Constant PARAM_*.
1255 * @return bool
1257 function is_rtl_compatible($paramtype) {
1258 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1262 * Makes sure the data is using valid utf8, invalid characters are discarded.
1264 * Note: this function is not intended for full objects with methods and private properties.
1266 * @param mixed $value
1267 * @return mixed with proper utf-8 encoding
1269 function fix_utf8($value) {
1270 if (is_null($value) or $value === '') {
1271 return $value;
1273 } else if (is_string($value)) {
1274 if ((string)(int)$value === $value) {
1275 // Shortcut.
1276 return $value;
1278 // No null bytes expected in our data, so let's remove it.
1279 $value = str_replace("\0", '', $value);
1281 // Note: this duplicates min_fix_utf8() intentionally.
1282 static $buggyiconv = null;
1283 if ($buggyiconv === null) {
1284 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1287 if ($buggyiconv) {
1288 if (function_exists('mb_convert_encoding')) {
1289 $subst = mb_substitute_character();
1290 mb_substitute_character('');
1291 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1292 mb_substitute_character($subst);
1294 } else {
1295 // Warn admins on admin/index.php page.
1296 $result = $value;
1299 } else {
1300 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1303 return $result;
1305 } else if (is_array($value)) {
1306 foreach ($value as $k => $v) {
1307 $value[$k] = fix_utf8($v);
1309 return $value;
1311 } else if (is_object($value)) {
1312 // Do not modify original.
1313 $value = clone($value);
1314 foreach ($value as $k => $v) {
1315 $value->$k = fix_utf8($v);
1317 return $value;
1319 } else {
1320 // This is some other type, no utf-8 here.
1321 return $value;
1326 * Return true if given value is integer or string with integer value
1328 * @param mixed $value String or Int
1329 * @return bool true if number, false if not
1331 function is_number($value) {
1332 if (is_int($value)) {
1333 return true;
1334 } else if (is_string($value)) {
1335 return ((string)(int)$value) === $value;
1336 } else {
1337 return false;
1342 * Returns host part from url.
1344 * @param string $url full url
1345 * @return string host, null if not found
1347 function get_host_from_url($url) {
1348 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1349 if ($matches) {
1350 return $matches[1];
1352 return null;
1356 * Tests whether anything was returned by text editor
1358 * This function is useful for testing whether something you got back from
1359 * the HTML editor actually contains anything. Sometimes the HTML editor
1360 * appear to be empty, but actually you get back a <br> tag or something.
1362 * @param string $string a string containing HTML.
1363 * @return boolean does the string contain any actual content - that is text,
1364 * images, objects, etc.
1366 function html_is_blank($string) {
1367 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1371 * Set a key in global configuration
1373 * Set a key/value pair in both this session's {@link $CFG} global variable
1374 * and in the 'config' database table for future sessions.
1376 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1377 * In that case it doesn't affect $CFG.
1379 * A NULL value will delete the entry.
1381 * NOTE: this function is called from lib/db/upgrade.php
1383 * @param string $name the key to set
1384 * @param string $value the value to set (without magic quotes)
1385 * @param string $plugin (optional) the plugin scope, default null
1386 * @return bool true or exception
1388 function set_config($name, $value, $plugin=null) {
1389 global $CFG, $DB;
1391 if (empty($plugin)) {
1392 if (!array_key_exists($name, $CFG->config_php_settings)) {
1393 // So it's defined for this invocation at least.
1394 if (is_null($value)) {
1395 unset($CFG->$name);
1396 } else {
1397 // Settings from db are always strings.
1398 $CFG->$name = (string)$value;
1402 if ($DB->get_field('config', 'name', array('name' => $name))) {
1403 if ($value === null) {
1404 $DB->delete_records('config', array('name' => $name));
1405 } else {
1406 $DB->set_field('config', 'value', $value, array('name' => $name));
1408 } else {
1409 if ($value !== null) {
1410 $config = new stdClass();
1411 $config->name = $name;
1412 $config->value = $value;
1413 $DB->insert_record('config', $config, false);
1416 if ($name === 'siteidentifier') {
1417 cache_helper::update_site_identifier($value);
1419 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1420 } else {
1421 // Plugin scope.
1422 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1423 if ($value===null) {
1424 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1425 } else {
1426 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1428 } else {
1429 if ($value !== null) {
1430 $config = new stdClass();
1431 $config->plugin = $plugin;
1432 $config->name = $name;
1433 $config->value = $value;
1434 $DB->insert_record('config_plugins', $config, false);
1437 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1440 return true;
1444 * Get configuration values from the global config table
1445 * or the config_plugins table.
1447 * If called with one parameter, it will load all the config
1448 * variables for one plugin, and return them as an object.
1450 * If called with 2 parameters it will return a string single
1451 * value or false if the value is not found.
1453 * NOTE: this function is called from lib/db/upgrade.php
1455 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1456 * that we need only fetch it once per request.
1457 * @param string $plugin full component name
1458 * @param string $name default null
1459 * @return mixed hash-like object or single value, return false no config found
1460 * @throws dml_exception
1462 function get_config($plugin, $name = null) {
1463 global $CFG, $DB;
1465 static $siteidentifier = null;
1467 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1468 $forced =& $CFG->config_php_settings;
1469 $iscore = true;
1470 $plugin = 'core';
1471 } else {
1472 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1473 $forced =& $CFG->forced_plugin_settings[$plugin];
1474 } else {
1475 $forced = array();
1477 $iscore = false;
1480 if ($siteidentifier === null) {
1481 try {
1482 // This may fail during installation.
1483 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1484 // install the database.
1485 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1486 } catch (dml_exception $ex) {
1487 // Set siteidentifier to false. We don't want to trip this continually.
1488 $siteidentifier = false;
1489 throw $ex;
1493 if (!empty($name)) {
1494 if (array_key_exists($name, $forced)) {
1495 return (string)$forced[$name];
1496 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1497 return $siteidentifier;
1501 $cache = cache::make('core', 'config');
1502 $result = $cache->get($plugin);
1503 if ($result === false) {
1504 // The user is after a recordset.
1505 if (!$iscore) {
1506 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1507 } else {
1508 // This part is not really used any more, but anyway...
1509 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1511 $cache->set($plugin, $result);
1514 if (!empty($name)) {
1515 if (array_key_exists($name, $result)) {
1516 return $result[$name];
1518 return false;
1521 if ($plugin === 'core') {
1522 $result['siteidentifier'] = $siteidentifier;
1525 foreach ($forced as $key => $value) {
1526 if (is_null($value) or is_array($value) or is_object($value)) {
1527 // We do not want any extra mess here, just real settings that could be saved in db.
1528 unset($result[$key]);
1529 } else {
1530 // Convert to string as if it went through the DB.
1531 $result[$key] = (string)$value;
1535 return (object)$result;
1539 * Removes a key from global configuration.
1541 * NOTE: this function is called from lib/db/upgrade.php
1543 * @param string $name the key to set
1544 * @param string $plugin (optional) the plugin scope
1545 * @return boolean whether the operation succeeded.
1547 function unset_config($name, $plugin=null) {
1548 global $CFG, $DB;
1550 if (empty($plugin)) {
1551 unset($CFG->$name);
1552 $DB->delete_records('config', array('name' => $name));
1553 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1554 } else {
1555 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1556 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1559 return true;
1563 * Remove all the config variables for a given plugin.
1565 * NOTE: this function is called from lib/db/upgrade.php
1567 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1568 * @return boolean whether the operation succeeded.
1570 function unset_all_config_for_plugin($plugin) {
1571 global $DB;
1572 // Delete from the obvious config_plugins first.
1573 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1574 // Next delete any suspect settings from config.
1575 $like = $DB->sql_like('name', '?', true, true, false, '|');
1576 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1577 $DB->delete_records_select('config', $like, $params);
1578 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1579 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1581 return true;
1585 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1587 * All users are verified if they still have the necessary capability.
1589 * @param string $value the value of the config setting.
1590 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1591 * @param bool $includeadmins include administrators.
1592 * @return array of user objects.
1594 function get_users_from_config($value, $capability, $includeadmins = true) {
1595 if (empty($value) or $value === '$@NONE@$') {
1596 return array();
1599 // We have to make sure that users still have the necessary capability,
1600 // it should be faster to fetch them all first and then test if they are present
1601 // instead of validating them one-by-one.
1602 $users = get_users_by_capability(context_system::instance(), $capability);
1603 if ($includeadmins) {
1604 $admins = get_admins();
1605 foreach ($admins as $admin) {
1606 $users[$admin->id] = $admin;
1610 if ($value === '$@ALL@$') {
1611 return $users;
1614 $result = array(); // Result in correct order.
1615 $allowed = explode(',', $value);
1616 foreach ($allowed as $uid) {
1617 if (isset($users[$uid])) {
1618 $user = $users[$uid];
1619 $result[$user->id] = $user;
1623 return $result;
1628 * Invalidates browser caches and cached data in temp.
1630 * @return void
1632 function purge_all_caches() {
1633 purge_caches();
1637 * Selectively invalidate different types of cache.
1639 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1640 * areas alone or in combination.
1642 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1643 * 'muc' Purge MUC caches?
1644 * 'theme' Purge theme cache?
1645 * 'lang' Purge language string cache?
1646 * 'js' Purge javascript cache?
1647 * 'filter' Purge text filter cache?
1648 * 'other' Purge all other caches?
1650 function purge_caches($options = []) {
1651 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'filter', 'other'], false);
1652 if (empty(array_filter($options))) {
1653 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1654 } else {
1655 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1657 if ($options['muc']) {
1658 cache_helper::purge_all();
1660 if ($options['theme']) {
1661 theme_reset_all_caches();
1663 if ($options['lang']) {
1664 get_string_manager()->reset_caches();
1666 if ($options['js']) {
1667 js_reset_all_caches();
1669 if ($options['filter']) {
1670 reset_text_filters_cache();
1672 if ($options['other']) {
1673 purge_other_caches();
1678 * Purge all non-MUC caches not otherwise purged in purge_caches.
1680 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1681 * {@link phpunit_util::reset_dataroot()}
1683 function purge_other_caches() {
1684 global $DB, $CFG;
1685 core_text::reset_caches();
1686 if (class_exists('core_plugin_manager')) {
1687 core_plugin_manager::reset_caches();
1690 // Bump up cacherev field for all courses.
1691 try {
1692 increment_revision_number('course', 'cacherev', '');
1693 } catch (moodle_exception $e) {
1694 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1697 $DB->reset_caches();
1699 // Purge all other caches: rss, simplepie, etc.
1700 clearstatcache();
1701 remove_dir($CFG->cachedir.'', true);
1703 // Make sure cache dir is writable, throws exception if not.
1704 make_cache_directory('');
1706 // This is the only place where we purge local caches, we are only adding files there.
1707 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1708 remove_dir($CFG->localcachedir, true);
1709 set_config('localcachedirpurged', time());
1710 make_localcache_directory('', true);
1711 \core\task\manager::clear_static_caches();
1715 * Get volatile flags
1717 * @param string $type
1718 * @param int $changedsince default null
1719 * @return array records array
1721 function get_cache_flags($type, $changedsince = null) {
1722 global $DB;
1724 $params = array('type' => $type, 'expiry' => time());
1725 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1726 if ($changedsince !== null) {
1727 $params['changedsince'] = $changedsince;
1728 $sqlwhere .= " AND timemodified > :changedsince";
1730 $cf = array();
1731 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1732 foreach ($flags as $flag) {
1733 $cf[$flag->name] = $flag->value;
1736 return $cf;
1740 * Get volatile flags
1742 * @param string $type
1743 * @param string $name
1744 * @param int $changedsince default null
1745 * @return string|false The cache flag value or false
1747 function get_cache_flag($type, $name, $changedsince=null) {
1748 global $DB;
1750 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1752 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1753 if ($changedsince !== null) {
1754 $params['changedsince'] = $changedsince;
1755 $sqlwhere .= " AND timemodified > :changedsince";
1758 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1762 * Set a volatile flag
1764 * @param string $type the "type" namespace for the key
1765 * @param string $name the key to set
1766 * @param string $value the value to set (without magic quotes) - null will remove the flag
1767 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1768 * @return bool Always returns true
1770 function set_cache_flag($type, $name, $value, $expiry = null) {
1771 global $DB;
1773 $timemodified = time();
1774 if ($expiry === null || $expiry < $timemodified) {
1775 $expiry = $timemodified + 24 * 60 * 60;
1776 } else {
1777 $expiry = (int)$expiry;
1780 if ($value === null) {
1781 unset_cache_flag($type, $name);
1782 return true;
1785 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1786 // This is a potential problem in DEBUG_DEVELOPER.
1787 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1788 return true; // No need to update.
1790 $f->value = $value;
1791 $f->expiry = $expiry;
1792 $f->timemodified = $timemodified;
1793 $DB->update_record('cache_flags', $f);
1794 } else {
1795 $f = new stdClass();
1796 $f->flagtype = $type;
1797 $f->name = $name;
1798 $f->value = $value;
1799 $f->expiry = $expiry;
1800 $f->timemodified = $timemodified;
1801 $DB->insert_record('cache_flags', $f);
1803 return true;
1807 * Removes a single volatile flag
1809 * @param string $type the "type" namespace for the key
1810 * @param string $name the key to set
1811 * @return bool
1813 function unset_cache_flag($type, $name) {
1814 global $DB;
1815 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1816 return true;
1820 * Garbage-collect volatile flags
1822 * @return bool Always returns true
1824 function gc_cache_flags() {
1825 global $DB;
1826 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1827 return true;
1830 // USER PREFERENCE API.
1833 * Refresh user preference cache. This is used most often for $USER
1834 * object that is stored in session, but it also helps with performance in cron script.
1836 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1838 * @package core
1839 * @category preference
1840 * @access public
1841 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1842 * @param int $cachelifetime Cache life time on the current page (in seconds)
1843 * @throws coding_exception
1844 * @return null
1846 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1847 global $DB;
1848 // Static cache, we need to check on each page load, not only every 2 minutes.
1849 static $loadedusers = array();
1851 if (!isset($user->id)) {
1852 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1855 if (empty($user->id) or isguestuser($user->id)) {
1856 // No permanent storage for not-logged-in users and guest.
1857 if (!isset($user->preference)) {
1858 $user->preference = array();
1860 return;
1863 $timenow = time();
1865 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1866 // Already loaded at least once on this page. Are we up to date?
1867 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1868 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1869 return;
1871 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1872 // No change since the lastcheck on this page.
1873 $user->preference['_lastloaded'] = $timenow;
1874 return;
1878 // OK, so we have to reload all preferences.
1879 $loadedusers[$user->id] = true;
1880 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1881 $user->preference['_lastloaded'] = $timenow;
1885 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1887 * NOTE: internal function, do not call from other code.
1889 * @package core
1890 * @access private
1891 * @param integer $userid the user whose prefs were changed.
1893 function mark_user_preferences_changed($userid) {
1894 global $CFG;
1896 if (empty($userid) or isguestuser($userid)) {
1897 // No cache flags for guest and not-logged-in users.
1898 return;
1901 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1905 * Sets a preference for the specified user.
1907 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1909 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1911 * @package core
1912 * @category preference
1913 * @access public
1914 * @param string $name The key to set as preference for the specified user
1915 * @param string $value The value to set for the $name key in the specified user's
1916 * record, null means delete current value.
1917 * @param stdClass|int|null $user A moodle user object or id, null means current user
1918 * @throws coding_exception
1919 * @return bool Always true or exception
1921 function set_user_preference($name, $value, $user = null) {
1922 global $USER, $DB;
1924 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1925 throw new coding_exception('Invalid preference name in set_user_preference() call');
1928 if (is_null($value)) {
1929 // Null means delete current.
1930 return unset_user_preference($name, $user);
1931 } else if (is_object($value)) {
1932 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1933 } else if (is_array($value)) {
1934 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1936 // Value column maximum length is 1333 characters.
1937 $value = (string)$value;
1938 if (core_text::strlen($value) > 1333) {
1939 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1942 if (is_null($user)) {
1943 $user = $USER;
1944 } else if (isset($user->id)) {
1945 // It is a valid object.
1946 } else if (is_numeric($user)) {
1947 $user = (object)array('id' => (int)$user);
1948 } else {
1949 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1952 check_user_preferences_loaded($user);
1954 if (empty($user->id) or isguestuser($user->id)) {
1955 // No permanent storage for not-logged-in users and guest.
1956 $user->preference[$name] = $value;
1957 return true;
1960 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1961 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1962 // Preference already set to this value.
1963 return true;
1965 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1967 } else {
1968 $preference = new stdClass();
1969 $preference->userid = $user->id;
1970 $preference->name = $name;
1971 $preference->value = $value;
1972 $DB->insert_record('user_preferences', $preference);
1975 // Update value in cache.
1976 $user->preference[$name] = $value;
1977 // Update the $USER in case where we've not a direct reference to $USER.
1978 if ($user !== $USER && $user->id == $USER->id) {
1979 $USER->preference[$name] = $value;
1982 // Set reload flag for other sessions.
1983 mark_user_preferences_changed($user->id);
1985 return true;
1989 * Sets a whole array of preferences for the current user
1991 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1993 * @package core
1994 * @category preference
1995 * @access public
1996 * @param array $prefarray An array of key/value pairs to be set
1997 * @param stdClass|int|null $user A moodle user object or id, null means current user
1998 * @return bool Always true or exception
2000 function set_user_preferences(array $prefarray, $user = null) {
2001 foreach ($prefarray as $name => $value) {
2002 set_user_preference($name, $value, $user);
2004 return true;
2008 * Unsets a preference completely by deleting it from the database
2010 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2012 * @package core
2013 * @category preference
2014 * @access public
2015 * @param string $name The key to unset as preference for the specified user
2016 * @param stdClass|int|null $user A moodle user object or id, null means current user
2017 * @throws coding_exception
2018 * @return bool Always true or exception
2020 function unset_user_preference($name, $user = null) {
2021 global $USER, $DB;
2023 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2024 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2027 if (is_null($user)) {
2028 $user = $USER;
2029 } else if (isset($user->id)) {
2030 // It is a valid object.
2031 } else if (is_numeric($user)) {
2032 $user = (object)array('id' => (int)$user);
2033 } else {
2034 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2037 check_user_preferences_loaded($user);
2039 if (empty($user->id) or isguestuser($user->id)) {
2040 // No permanent storage for not-logged-in user and guest.
2041 unset($user->preference[$name]);
2042 return true;
2045 // Delete from DB.
2046 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2048 // Delete the preference from cache.
2049 unset($user->preference[$name]);
2050 // Update the $USER in case where we've not a direct reference to $USER.
2051 if ($user !== $USER && $user->id == $USER->id) {
2052 unset($USER->preference[$name]);
2055 // Set reload flag for other sessions.
2056 mark_user_preferences_changed($user->id);
2058 return true;
2062 * Used to fetch user preference(s)
2064 * If no arguments are supplied this function will return
2065 * all of the current user preferences as an array.
2067 * If a name is specified then this function
2068 * attempts to return that particular preference value. If
2069 * none is found, then the optional value $default is returned,
2070 * otherwise null.
2072 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2074 * @package core
2075 * @category preference
2076 * @access public
2077 * @param string $name Name of the key to use in finding a preference value
2078 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2079 * @param stdClass|int|null $user A moodle user object or id, null means current user
2080 * @throws coding_exception
2081 * @return string|mixed|null A string containing the value of a single preference. An
2082 * array with all of the preferences or null
2084 function get_user_preferences($name = null, $default = null, $user = null) {
2085 global $USER;
2087 if (is_null($name)) {
2088 // All prefs.
2089 } else if (is_numeric($name) or $name === '_lastloaded') {
2090 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2093 if (is_null($user)) {
2094 $user = $USER;
2095 } else if (isset($user->id)) {
2096 // Is a valid object.
2097 } else if (is_numeric($user)) {
2098 $user = (object)array('id' => (int)$user);
2099 } else {
2100 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2103 check_user_preferences_loaded($user);
2105 if (empty($name)) {
2106 // All values.
2107 return $user->preference;
2108 } else if (isset($user->preference[$name])) {
2109 // The single string value.
2110 return $user->preference[$name];
2111 } else {
2112 // Default value (null if not specified).
2113 return $default;
2117 // FUNCTIONS FOR HANDLING TIME.
2120 * Given Gregorian date parts in user time produce a GMT timestamp.
2122 * @package core
2123 * @category time
2124 * @param int $year The year part to create timestamp of
2125 * @param int $month The month part to create timestamp of
2126 * @param int $day The day part to create timestamp of
2127 * @param int $hour The hour part to create timestamp of
2128 * @param int $minute The minute part to create timestamp of
2129 * @param int $second The second part to create timestamp of
2130 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2131 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2132 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2133 * applied only if timezone is 99 or string.
2134 * @return int GMT timestamp
2136 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2137 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2138 $date->setDate((int)$year, (int)$month, (int)$day);
2139 $date->setTime((int)$hour, (int)$minute, (int)$second);
2141 $time = $date->getTimestamp();
2143 if ($time === false) {
2144 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2145 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2148 // Moodle BC DST stuff.
2149 if (!$applydst) {
2150 $time += dst_offset_on($time, $timezone);
2153 return $time;
2158 * Format a date/time (seconds) as weeks, days, hours etc as needed
2160 * Given an amount of time in seconds, returns string
2161 * formatted nicely as years, days, hours etc as needed
2163 * @package core
2164 * @category time
2165 * @uses MINSECS
2166 * @uses HOURSECS
2167 * @uses DAYSECS
2168 * @uses YEARSECS
2169 * @param int $totalsecs Time in seconds
2170 * @param stdClass $str Should be a time object
2171 * @return string A nicely formatted date/time string
2173 function format_time($totalsecs, $str = null) {
2175 $totalsecs = abs($totalsecs);
2177 if (!$str) {
2178 // Create the str structure the slow way.
2179 $str = new stdClass();
2180 $str->day = get_string('day');
2181 $str->days = get_string('days');
2182 $str->hour = get_string('hour');
2183 $str->hours = get_string('hours');
2184 $str->min = get_string('min');
2185 $str->mins = get_string('mins');
2186 $str->sec = get_string('sec');
2187 $str->secs = get_string('secs');
2188 $str->year = get_string('year');
2189 $str->years = get_string('years');
2192 $years = floor($totalsecs/YEARSECS);
2193 $remainder = $totalsecs - ($years*YEARSECS);
2194 $days = floor($remainder/DAYSECS);
2195 $remainder = $totalsecs - ($days*DAYSECS);
2196 $hours = floor($remainder/HOURSECS);
2197 $remainder = $remainder - ($hours*HOURSECS);
2198 $mins = floor($remainder/MINSECS);
2199 $secs = $remainder - ($mins*MINSECS);
2201 $ss = ($secs == 1) ? $str->sec : $str->secs;
2202 $sm = ($mins == 1) ? $str->min : $str->mins;
2203 $sh = ($hours == 1) ? $str->hour : $str->hours;
2204 $sd = ($days == 1) ? $str->day : $str->days;
2205 $sy = ($years == 1) ? $str->year : $str->years;
2207 $oyears = '';
2208 $odays = '';
2209 $ohours = '';
2210 $omins = '';
2211 $osecs = '';
2213 if ($years) {
2214 $oyears = $years .' '. $sy;
2216 if ($days) {
2217 $odays = $days .' '. $sd;
2219 if ($hours) {
2220 $ohours = $hours .' '. $sh;
2222 if ($mins) {
2223 $omins = $mins .' '. $sm;
2225 if ($secs) {
2226 $osecs = $secs .' '. $ss;
2229 if ($years) {
2230 return trim($oyears .' '. $odays);
2232 if ($days) {
2233 return trim($odays .' '. $ohours);
2235 if ($hours) {
2236 return trim($ohours .' '. $omins);
2238 if ($mins) {
2239 return trim($omins .' '. $osecs);
2241 if ($secs) {
2242 return $osecs;
2244 return get_string('now');
2248 * Returns a formatted string that represents a date in user time.
2250 * @package core
2251 * @category time
2252 * @param int $date the timestamp in UTC, as obtained from the database.
2253 * @param string $format strftime format. You should probably get this using
2254 * get_string('strftime...', 'langconfig');
2255 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2256 * not 99 then daylight saving will not be added.
2257 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2258 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2259 * If false then the leading zero is maintained.
2260 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2261 * @return string the formatted date/time.
2263 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2264 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2265 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2269 * Returns a formatted date ensuring it is UTF-8.
2271 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2272 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2274 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2275 * @param string $format strftime format.
2276 * @param int|float|string $tz the user timezone
2277 * @return string the formatted date/time.
2278 * @since Moodle 2.3.3
2280 function date_format_string($date, $format, $tz = 99) {
2281 global $CFG;
2283 $localewincharset = null;
2284 // Get the calendar type user is using.
2285 if ($CFG->ostype == 'WINDOWS') {
2286 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2287 $localewincharset = $calendartype->locale_win_charset();
2290 if ($localewincharset) {
2291 $format = core_text::convert($format, 'utf-8', $localewincharset);
2294 date_default_timezone_set(core_date::get_user_timezone($tz));
2295 $datestring = strftime($format, $date);
2296 core_date::set_default_server_timezone();
2298 if ($localewincharset) {
2299 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2302 return $datestring;
2306 * Given a $time timestamp in GMT (seconds since epoch),
2307 * returns an array that represents the Gregorian date in user time
2309 * @package core
2310 * @category time
2311 * @param int $time Timestamp in GMT
2312 * @param float|int|string $timezone user timezone
2313 * @return array An array that represents the date in user time
2315 function usergetdate($time, $timezone=99) {
2316 date_default_timezone_set(core_date::get_user_timezone($timezone));
2317 $result = getdate($time);
2318 core_date::set_default_server_timezone();
2320 return $result;
2324 * Given a GMT timestamp (seconds since epoch), offsets it by
2325 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2327 * NOTE: this function does not include DST properly,
2328 * you should use the PHP date stuff instead!
2330 * @package core
2331 * @category time
2332 * @param int $date Timestamp in GMT
2333 * @param float|int|string $timezone user timezone
2334 * @return int
2336 function usertime($date, $timezone=99) {
2337 $userdate = new DateTime('@' . $date);
2338 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2339 $dst = dst_offset_on($date, $timezone);
2341 return $date - $userdate->getOffset() + $dst;
2345 * Given a time, return the GMT timestamp of the most recent midnight
2346 * for the current user.
2348 * @package core
2349 * @category time
2350 * @param int $date Timestamp in GMT
2351 * @param float|int|string $timezone user timezone
2352 * @return int Returns a GMT timestamp
2354 function usergetmidnight($date, $timezone=99) {
2356 $userdate = usergetdate($date, $timezone);
2358 // Time of midnight of this user's day, in GMT.
2359 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2364 * Returns a string that prints the user's timezone
2366 * @package core
2367 * @category time
2368 * @param float|int|string $timezone user timezone
2369 * @return string
2371 function usertimezone($timezone=99) {
2372 $tz = core_date::get_user_timezone($timezone);
2373 return core_date::get_localised_timezone($tz);
2377 * Returns a float or a string which denotes the user's timezone
2378 * 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)
2379 * means that for this timezone there are also DST rules to be taken into account
2380 * Checks various settings and picks the most dominant of those which have a value
2382 * @package core
2383 * @category time
2384 * @param float|int|string $tz timezone to calculate GMT time offset before
2385 * calculating user timezone, 99 is default user timezone
2386 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2387 * @return float|string
2389 function get_user_timezone($tz = 99) {
2390 global $USER, $CFG;
2392 $timezones = array(
2393 $tz,
2394 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2395 isset($USER->timezone) ? $USER->timezone : 99,
2396 isset($CFG->timezone) ? $CFG->timezone : 99,
2399 $tz = 99;
2401 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2402 foreach ($timezones as $nextvalue) {
2403 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2404 $tz = $nextvalue;
2407 return is_numeric($tz) ? (float) $tz : $tz;
2411 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2412 * - Note: Daylight saving only works for string timezones and not for float.
2414 * @package core
2415 * @category time
2416 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2417 * @param int|float|string $strtimezone user timezone
2418 * @return int
2420 function dst_offset_on($time, $strtimezone = null) {
2421 $tz = core_date::get_user_timezone($strtimezone);
2422 $date = new DateTime('@' . $time);
2423 $date->setTimezone(new DateTimeZone($tz));
2424 if ($date->format('I') == '1') {
2425 if ($tz === 'Australia/Lord_Howe') {
2426 return 1800;
2428 return 3600;
2430 return 0;
2434 * Calculates when the day appears in specific month
2436 * @package core
2437 * @category time
2438 * @param int $startday starting day of the month
2439 * @param int $weekday The day when week starts (normally taken from user preferences)
2440 * @param int $month The month whose day is sought
2441 * @param int $year The year of the month whose day is sought
2442 * @return int
2444 function find_day_in_month($startday, $weekday, $month, $year) {
2445 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2447 $daysinmonth = days_in_month($month, $year);
2448 $daysinweek = count($calendartype->get_weekdays());
2450 if ($weekday == -1) {
2451 // Don't care about weekday, so return:
2452 // abs($startday) if $startday != -1
2453 // $daysinmonth otherwise.
2454 return ($startday == -1) ? $daysinmonth : abs($startday);
2457 // From now on we 're looking for a specific weekday.
2458 // Give "end of month" its actual value, since we know it.
2459 if ($startday == -1) {
2460 $startday = -1 * $daysinmonth;
2463 // Starting from day $startday, the sign is the direction.
2464 if ($startday < 1) {
2465 $startday = abs($startday);
2466 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2468 // This is the last such weekday of the month.
2469 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2470 if ($lastinmonth > $daysinmonth) {
2471 $lastinmonth -= $daysinweek;
2474 // Find the first such weekday <= $startday.
2475 while ($lastinmonth > $startday) {
2476 $lastinmonth -= $daysinweek;
2479 return $lastinmonth;
2480 } else {
2481 $indexweekday = dayofweek($startday, $month, $year);
2483 $diff = $weekday - $indexweekday;
2484 if ($diff < 0) {
2485 $diff += $daysinweek;
2488 // This is the first such weekday of the month equal to or after $startday.
2489 $firstfromindex = $startday + $diff;
2491 return $firstfromindex;
2496 * Calculate the number of days in a given month
2498 * @package core
2499 * @category time
2500 * @param int $month The month whose day count is sought
2501 * @param int $year The year of the month whose day count is sought
2502 * @return int
2504 function days_in_month($month, $year) {
2505 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2506 return $calendartype->get_num_days_in_month($year, $month);
2510 * Calculate the position in the week of a specific calendar day
2512 * @package core
2513 * @category time
2514 * @param int $day The day of the date whose position in the week is sought
2515 * @param int $month The month of the date whose position in the week is sought
2516 * @param int $year The year of the date whose position in the week is sought
2517 * @return int
2519 function dayofweek($day, $month, $year) {
2520 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2521 return $calendartype->get_weekday($year, $month, $day);
2524 // USER AUTHENTICATION AND LOGIN.
2527 * Returns full login url.
2529 * @return string login url
2531 function get_login_url() {
2532 global $CFG;
2534 return "$CFG->wwwroot/login/index.php";
2538 * This function checks that the current user is logged in and has the
2539 * required privileges
2541 * This function checks that the current user is logged in, and optionally
2542 * whether they are allowed to be in a particular course and view a particular
2543 * course module.
2544 * If they are not logged in, then it redirects them to the site login unless
2545 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2546 * case they are automatically logged in as guests.
2547 * If $courseid is given and the user is not enrolled in that course then the
2548 * user is redirected to the course enrolment page.
2549 * If $cm is given and the course module is hidden and the user is not a teacher
2550 * in the course then the user is redirected to the course home page.
2552 * When $cm parameter specified, this function sets page layout to 'module'.
2553 * You need to change it manually later if some other layout needed.
2555 * @package core_access
2556 * @category access
2558 * @param mixed $courseorid id of the course or course object
2559 * @param bool $autologinguest default true
2560 * @param object $cm course module object
2561 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2562 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2563 * in order to keep redirects working properly. MDL-14495
2564 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2565 * @return mixed Void, exit, and die depending on path
2566 * @throws coding_exception
2567 * @throws require_login_exception
2568 * @throws moodle_exception
2570 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2571 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2573 // Must not redirect when byteserving already started.
2574 if (!empty($_SERVER['HTTP_RANGE'])) {
2575 $preventredirect = true;
2578 if (AJAX_SCRIPT) {
2579 // We cannot redirect for AJAX scripts either.
2580 $preventredirect = true;
2583 // Setup global $COURSE, themes, language and locale.
2584 if (!empty($courseorid)) {
2585 if (is_object($courseorid)) {
2586 $course = $courseorid;
2587 } else if ($courseorid == SITEID) {
2588 $course = clone($SITE);
2589 } else {
2590 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2592 if ($cm) {
2593 if ($cm->course != $course->id) {
2594 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2596 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2597 if (!($cm instanceof cm_info)) {
2598 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2599 // db queries so this is not really a performance concern, however it is obviously
2600 // better if you use get_fast_modinfo to get the cm before calling this.
2601 $modinfo = get_fast_modinfo($course);
2602 $cm = $modinfo->get_cm($cm->id);
2605 } else {
2606 // Do not touch global $COURSE via $PAGE->set_course(),
2607 // the reasons is we need to be able to call require_login() at any time!!
2608 $course = $SITE;
2609 if ($cm) {
2610 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2614 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2615 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2616 // risk leading the user back to the AJAX request URL.
2617 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2618 $setwantsurltome = false;
2621 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2622 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2623 if ($preventredirect) {
2624 throw new require_login_session_timeout_exception();
2625 } else {
2626 if ($setwantsurltome) {
2627 $SESSION->wantsurl = qualified_me();
2629 redirect(get_login_url());
2633 // If the user is not even logged in yet then make sure they are.
2634 if (!isloggedin()) {
2635 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2636 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2637 // Misconfigured site guest, just redirect to login page.
2638 redirect(get_login_url());
2639 exit; // Never reached.
2641 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2642 complete_user_login($guest);
2643 $USER->autologinguest = true;
2644 $SESSION->lang = $lang;
2645 } else {
2646 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2647 if ($preventredirect) {
2648 throw new require_login_exception('You are not logged in');
2651 if ($setwantsurltome) {
2652 $SESSION->wantsurl = qualified_me();
2655 $referer = get_local_referer(false);
2656 if (!empty($referer)) {
2657 $SESSION->fromurl = $referer;
2660 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2661 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2662 foreach($authsequence as $authname) {
2663 $authplugin = get_auth_plugin($authname);
2664 $authplugin->pre_loginpage_hook();
2665 if (isloggedin()) {
2666 break;
2670 // If we're still not logged in then go to the login page
2671 if (!isloggedin()) {
2672 redirect(get_login_url());
2673 exit; // Never reached.
2678 // Loginas as redirection if needed.
2679 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2680 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2681 if ($USER->loginascontext->instanceid != $course->id) {
2682 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2687 // Check whether the user should be changing password (but only if it is REALLY them).
2688 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2689 $userauth = get_auth_plugin($USER->auth);
2690 if ($userauth->can_change_password() and !$preventredirect) {
2691 if ($setwantsurltome) {
2692 $SESSION->wantsurl = qualified_me();
2694 if ($changeurl = $userauth->change_password_url()) {
2695 // Use plugin custom url.
2696 redirect($changeurl);
2697 } else {
2698 // Use moodle internal method.
2699 redirect($CFG->wwwroot .'/login/change_password.php');
2701 } else if ($userauth->can_change_password()) {
2702 throw new moodle_exception('forcepasswordchangenotice');
2703 } else {
2704 throw new moodle_exception('nopasswordchangeforced', 'auth');
2708 // Check that the user account is properly set up. If we can't redirect to
2709 // edit their profile and this is not a WS request, perform just the lax check.
2710 // It will allow them to use filepicker on the profile edit page.
2712 if ($preventredirect && !WS_SERVER) {
2713 $usernotfullysetup = user_not_fully_set_up($USER, false);
2714 } else {
2715 $usernotfullysetup = user_not_fully_set_up($USER, true);
2718 if ($usernotfullysetup) {
2719 if ($preventredirect) {
2720 throw new moodle_exception('usernotfullysetup');
2722 if ($setwantsurltome) {
2723 $SESSION->wantsurl = qualified_me();
2725 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2728 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2729 sesskey();
2731 // Do not bother admins with any formalities, except for activities pending deletion.
2732 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2733 // Set the global $COURSE.
2734 if ($cm) {
2735 $PAGE->set_cm($cm, $course);
2736 $PAGE->set_pagelayout('incourse');
2737 } else if (!empty($courseorid)) {
2738 $PAGE->set_course($course);
2740 // Set accesstime or the user will appear offline which messes up messaging.
2741 user_accesstime_log($course->id);
2742 return;
2745 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2746 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2747 if (!defined('NO_SITEPOLICY_CHECK')) {
2748 define('NO_SITEPOLICY_CHECK', false);
2751 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2752 // Do not test if the script explicitly asked for skipping the site policies check.
2753 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2754 $manager = new \core_privacy\local\sitepolicy\manager();
2755 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2756 if ($preventredirect) {
2757 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2759 if ($setwantsurltome) {
2760 $SESSION->wantsurl = qualified_me();
2762 redirect($policyurl);
2766 // Fetch the system context, the course context, and prefetch its child contexts.
2767 $sysctx = context_system::instance();
2768 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2769 if ($cm) {
2770 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2771 } else {
2772 $cmcontext = null;
2775 // If the site is currently under maintenance, then print a message.
2776 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2777 if ($preventredirect) {
2778 throw new require_login_exception('Maintenance in progress');
2780 $PAGE->set_context(null);
2781 print_maintenance_message();
2784 // Make sure the course itself is not hidden.
2785 if ($course->id == SITEID) {
2786 // Frontpage can not be hidden.
2787 } else {
2788 if (is_role_switched($course->id)) {
2789 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2790 } else {
2791 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2792 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2793 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2794 if ($preventredirect) {
2795 throw new require_login_exception('Course is hidden');
2797 $PAGE->set_context(null);
2798 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2799 // the navigation will mess up when trying to find it.
2800 navigation_node::override_active_url(new moodle_url('/'));
2801 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2806 // Is the user enrolled?
2807 if ($course->id == SITEID) {
2808 // Everybody is enrolled on the frontpage.
2809 } else {
2810 if (\core\session\manager::is_loggedinas()) {
2811 // Make sure the REAL person can access this course first.
2812 $realuser = \core\session\manager::get_realuser();
2813 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2814 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2815 if ($preventredirect) {
2816 throw new require_login_exception('Invalid course login-as access');
2818 $PAGE->set_context(null);
2819 echo $OUTPUT->header();
2820 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2824 $access = false;
2826 if (is_role_switched($course->id)) {
2827 // Ok, user had to be inside this course before the switch.
2828 $access = true;
2830 } else if (is_viewing($coursecontext, $USER)) {
2831 // Ok, no need to mess with enrol.
2832 $access = true;
2834 } else {
2835 if (isset($USER->enrol['enrolled'][$course->id])) {
2836 if ($USER->enrol['enrolled'][$course->id] > time()) {
2837 $access = true;
2838 if (isset($USER->enrol['tempguest'][$course->id])) {
2839 unset($USER->enrol['tempguest'][$course->id]);
2840 remove_temp_course_roles($coursecontext);
2842 } else {
2843 // Expired.
2844 unset($USER->enrol['enrolled'][$course->id]);
2847 if (isset($USER->enrol['tempguest'][$course->id])) {
2848 if ($USER->enrol['tempguest'][$course->id] == 0) {
2849 $access = true;
2850 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2851 $access = true;
2852 } else {
2853 // Expired.
2854 unset($USER->enrol['tempguest'][$course->id]);
2855 remove_temp_course_roles($coursecontext);
2859 if (!$access) {
2860 // Cache not ok.
2861 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2862 if ($until !== false) {
2863 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2864 if ($until == 0) {
2865 $until = ENROL_MAX_TIMESTAMP;
2867 $USER->enrol['enrolled'][$course->id] = $until;
2868 $access = true;
2870 } else {
2871 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2872 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2873 $enrols = enrol_get_plugins(true);
2874 // First ask all enabled enrol instances in course if they want to auto enrol user.
2875 foreach ($instances as $instance) {
2876 if (!isset($enrols[$instance->enrol])) {
2877 continue;
2879 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2880 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2881 if ($until !== false) {
2882 if ($until == 0) {
2883 $until = ENROL_MAX_TIMESTAMP;
2885 $USER->enrol['enrolled'][$course->id] = $until;
2886 $access = true;
2887 break;
2890 // If not enrolled yet try to gain temporary guest access.
2891 if (!$access) {
2892 foreach ($instances as $instance) {
2893 if (!isset($enrols[$instance->enrol])) {
2894 continue;
2896 // Get a duration for the guest access, a timestamp in the future or false.
2897 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2898 if ($until !== false and $until > time()) {
2899 $USER->enrol['tempguest'][$course->id] = $until;
2900 $access = true;
2901 break;
2909 if (!$access) {
2910 if ($preventredirect) {
2911 throw new require_login_exception('Not enrolled');
2913 if ($setwantsurltome) {
2914 $SESSION->wantsurl = qualified_me();
2916 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2920 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
2921 if ($cm && $cm->deletioninprogress) {
2922 if ($preventredirect) {
2923 throw new moodle_exception('activityisscheduledfordeletion');
2925 require_once($CFG->dirroot . '/course/lib.php');
2926 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
2929 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2930 if ($cm && !$cm->uservisible) {
2931 if ($preventredirect) {
2932 throw new require_login_exception('Activity is hidden');
2934 // Get the error message that activity is not available and why (if explanation can be shown to the user).
2935 $PAGE->set_course($course);
2936 $renderer = $PAGE->get_renderer('course');
2937 $message = $renderer->course_section_cm_unavailable_error_message($cm);
2938 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
2941 // Set the global $COURSE.
2942 if ($cm) {
2943 $PAGE->set_cm($cm, $course);
2944 $PAGE->set_pagelayout('incourse');
2945 } else if (!empty($courseorid)) {
2946 $PAGE->set_course($course);
2949 // Finally access granted, update lastaccess times.
2950 user_accesstime_log($course->id);
2955 * This function just makes sure a user is logged out.
2957 * @package core_access
2958 * @category access
2960 function require_logout() {
2961 global $USER, $DB;
2963 if (!isloggedin()) {
2964 // This should not happen often, no need for hooks or events here.
2965 \core\session\manager::terminate_current();
2966 return;
2969 // Execute hooks before action.
2970 $authplugins = array();
2971 $authsequence = get_enabled_auth_plugins();
2972 foreach ($authsequence as $authname) {
2973 $authplugins[$authname] = get_auth_plugin($authname);
2974 $authplugins[$authname]->prelogout_hook();
2977 // Store info that gets removed during logout.
2978 $sid = session_id();
2979 $event = \core\event\user_loggedout::create(
2980 array(
2981 'userid' => $USER->id,
2982 'objectid' => $USER->id,
2983 'other' => array('sessionid' => $sid),
2986 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2987 $event->add_record_snapshot('sessions', $session);
2990 // Clone of $USER object to be used by auth plugins.
2991 $user = fullclone($USER);
2993 // Delete session record and drop $_SESSION content.
2994 \core\session\manager::terminate_current();
2996 // Trigger event AFTER action.
2997 $event->trigger();
2999 // Hook to execute auth plugins redirection after event trigger.
3000 foreach ($authplugins as $authplugin) {
3001 $authplugin->postlogout_hook($user);
3006 * Weaker version of require_login()
3008 * This is a weaker version of {@link require_login()} which only requires login
3009 * when called from within a course rather than the site page, unless
3010 * the forcelogin option is turned on.
3011 * @see require_login()
3013 * @package core_access
3014 * @category access
3016 * @param mixed $courseorid The course object or id in question
3017 * @param bool $autologinguest Allow autologin guests if that is wanted
3018 * @param object $cm Course activity module if known
3019 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3020 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3021 * in order to keep redirects working properly. MDL-14495
3022 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3023 * @return void
3024 * @throws coding_exception
3026 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3027 global $CFG, $PAGE, $SITE;
3028 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3029 or (!is_object($courseorid) and $courseorid == SITEID));
3030 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3031 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3032 // db queries so this is not really a performance concern, however it is obviously
3033 // better if you use get_fast_modinfo to get the cm before calling this.
3034 if (is_object($courseorid)) {
3035 $course = $courseorid;
3036 } else {
3037 $course = clone($SITE);
3039 $modinfo = get_fast_modinfo($course);
3040 $cm = $modinfo->get_cm($cm->id);
3042 if (!empty($CFG->forcelogin)) {
3043 // Login required for both SITE and courses.
3044 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3046 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3047 // Always login for hidden activities.
3048 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3050 } else if (isloggedin() && !isguestuser()) {
3051 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3052 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3054 } else if ($issite) {
3055 // Login for SITE not required.
3056 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3057 if (!empty($courseorid)) {
3058 if (is_object($courseorid)) {
3059 $course = $courseorid;
3060 } else {
3061 $course = clone $SITE;
3063 if ($cm) {
3064 if ($cm->course != $course->id) {
3065 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3067 $PAGE->set_cm($cm, $course);
3068 $PAGE->set_pagelayout('incourse');
3069 } else {
3070 $PAGE->set_course($course);
3072 } else {
3073 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3074 $PAGE->set_course($PAGE->course);
3076 user_accesstime_log(SITEID);
3077 return;
3079 } else {
3080 // Course login always required.
3081 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3086 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3088 * @param string $keyvalue the key value
3089 * @param string $script unique script identifier
3090 * @param int $instance instance id
3091 * @return stdClass the key entry in the user_private_key table
3092 * @since Moodle 3.2
3093 * @throws moodle_exception
3095 function validate_user_key($keyvalue, $script, $instance) {
3096 global $DB;
3098 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3099 print_error('invalidkey');
3102 if (!empty($key->validuntil) and $key->validuntil < time()) {
3103 print_error('expiredkey');
3106 if ($key->iprestriction) {
3107 $remoteaddr = getremoteaddr(null);
3108 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3109 print_error('ipmismatch');
3112 return $key;
3116 * Require key login. Function terminates with error if key not found or incorrect.
3118 * @uses NO_MOODLE_COOKIES
3119 * @uses PARAM_ALPHANUM
3120 * @param string $script unique script identifier
3121 * @param int $instance optional instance id
3122 * @return int Instance ID
3124 function require_user_key_login($script, $instance=null) {
3125 global $DB;
3127 if (!NO_MOODLE_COOKIES) {
3128 print_error('sessioncookiesdisable');
3131 // Extra safety.
3132 \core\session\manager::write_close();
3134 $keyvalue = required_param('key', PARAM_ALPHANUM);
3136 $key = validate_user_key($keyvalue, $script, $instance);
3138 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3139 print_error('invaliduserid');
3142 // Emulate normal session.
3143 enrol_check_plugins($user);
3144 \core\session\manager::set_user($user);
3146 // Note we are not using normal login.
3147 if (!defined('USER_KEY_LOGIN')) {
3148 define('USER_KEY_LOGIN', true);
3151 // Return instance id - it might be empty.
3152 return $key->instance;
3156 * Creates a new private user access key.
3158 * @param string $script unique target identifier
3159 * @param int $userid
3160 * @param int $instance optional instance id
3161 * @param string $iprestriction optional ip restricted access
3162 * @param int $validuntil key valid only until given data
3163 * @return string access key value
3165 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3166 global $DB;
3168 $key = new stdClass();
3169 $key->script = $script;
3170 $key->userid = $userid;
3171 $key->instance = $instance;
3172 $key->iprestriction = $iprestriction;
3173 $key->validuntil = $validuntil;
3174 $key->timecreated = time();
3176 // Something long and unique.
3177 $key->value = md5($userid.'_'.time().random_string(40));
3178 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3179 // Must be unique.
3180 $key->value = md5($userid.'_'.time().random_string(40));
3182 $DB->insert_record('user_private_key', $key);
3183 return $key->value;
3187 * Delete the user's new private user access keys for a particular script.
3189 * @param string $script unique target identifier
3190 * @param int $userid
3191 * @return void
3193 function delete_user_key($script, $userid) {
3194 global $DB;
3195 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3199 * Gets a private user access key (and creates one if one doesn't exist).
3201 * @param string $script unique target identifier
3202 * @param int $userid
3203 * @param int $instance optional instance id
3204 * @param string $iprestriction optional ip restricted access
3205 * @param int $validuntil key valid only until given date
3206 * @return string access key value
3208 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3209 global $DB;
3211 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3212 'instance' => $instance, 'iprestriction' => $iprestriction,
3213 'validuntil' => $validuntil))) {
3214 return $key->value;
3215 } else {
3216 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3222 * Modify the user table by setting the currently logged in user's last login to now.
3224 * @return bool Always returns true
3226 function update_user_login_times() {
3227 global $USER, $DB;
3229 if (isguestuser()) {
3230 // Do not update guest access times/ips for performance.
3231 return true;
3234 $now = time();
3236 $user = new stdClass();
3237 $user->id = $USER->id;
3239 // Make sure all users that logged in have some firstaccess.
3240 if ($USER->firstaccess == 0) {
3241 $USER->firstaccess = $user->firstaccess = $now;
3244 // Store the previous current as lastlogin.
3245 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3247 $USER->currentlogin = $user->currentlogin = $now;
3249 // Function user_accesstime_log() may not update immediately, better do it here.
3250 $USER->lastaccess = $user->lastaccess = $now;
3251 $USER->lastip = $user->lastip = getremoteaddr();
3253 // Note: do not call user_update_user() here because this is part of the login process,
3254 // the login event means that these fields were updated.
3255 $DB->update_record('user', $user);
3256 return true;
3260 * Determines if a user has completed setting up their account.
3262 * The lax mode (with $strict = false) has been introduced for special cases
3263 * only where we want to skip certain checks intentionally. This is valid in
3264 * certain mnet or ajax scenarios when the user cannot / should not be
3265 * redirected to edit their profile. In most cases, you should perform the
3266 * strict check.
3268 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3269 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3270 * @return bool
3272 function user_not_fully_set_up($user, $strict = true) {
3273 global $CFG;
3274 require_once($CFG->dirroot.'/user/profile/lib.php');
3276 if (isguestuser($user)) {
3277 return false;
3280 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3281 return true;
3284 if ($strict) {
3285 if (empty($user->id)) {
3286 // Strict mode can be used with existing accounts only.
3287 return true;
3289 if (!profile_has_required_custom_fields_set($user->id)) {
3290 return true;
3294 return false;
3298 * Check whether the user has exceeded the bounce threshold
3300 * @param stdClass $user A {@link $USER} object
3301 * @return bool true => User has exceeded bounce threshold
3303 function over_bounce_threshold($user) {
3304 global $CFG, $DB;
3306 if (empty($CFG->handlebounces)) {
3307 return false;
3310 if (empty($user->id)) {
3311 // No real (DB) user, nothing to do here.
3312 return false;
3315 // Set sensible defaults.
3316 if (empty($CFG->minbounces)) {
3317 $CFG->minbounces = 10;
3319 if (empty($CFG->bounceratio)) {
3320 $CFG->bounceratio = .20;
3322 $bouncecount = 0;
3323 $sendcount = 0;
3324 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3325 $bouncecount = $bounce->value;
3327 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3328 $sendcount = $send->value;
3330 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3334 * Used to increment or reset email sent count
3336 * @param stdClass $user object containing an id
3337 * @param bool $reset will reset the count to 0
3338 * @return void
3340 function set_send_count($user, $reset=false) {
3341 global $DB;
3343 if (empty($user->id)) {
3344 // No real (DB) user, nothing to do here.
3345 return;
3348 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3349 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3350 $DB->update_record('user_preferences', $pref);
3351 } else if (!empty($reset)) {
3352 // If it's not there and we're resetting, don't bother. Make a new one.
3353 $pref = new stdClass();
3354 $pref->name = 'email_send_count';
3355 $pref->value = 1;
3356 $pref->userid = $user->id;
3357 $DB->insert_record('user_preferences', $pref, false);
3362 * Increment or reset user's email bounce count
3364 * @param stdClass $user object containing an id
3365 * @param bool $reset will reset the count to 0
3367 function set_bounce_count($user, $reset=false) {
3368 global $DB;
3370 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3371 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3372 $DB->update_record('user_preferences', $pref);
3373 } else if (!empty($reset)) {
3374 // If it's not there and we're resetting, don't bother. Make a new one.
3375 $pref = new stdClass();
3376 $pref->name = 'email_bounce_count';
3377 $pref->value = 1;
3378 $pref->userid = $user->id;
3379 $DB->insert_record('user_preferences', $pref, false);
3384 * Determines if the logged in user is currently moving an activity
3386 * @param int $courseid The id of the course being tested
3387 * @return bool
3389 function ismoving($courseid) {
3390 global $USER;
3392 if (!empty($USER->activitycopy)) {
3393 return ($USER->activitycopycourse == $courseid);
3395 return false;
3399 * Returns a persons full name
3401 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3402 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3403 * specify one.
3405 * @param stdClass $user A {@link $USER} object to get full name of.
3406 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3407 * @return string
3409 function fullname($user, $override=false) {
3410 global $CFG, $SESSION;
3412 if (!isset($user->firstname) and !isset($user->lastname)) {
3413 return '';
3416 // Get all of the name fields.
3417 $allnames = get_all_user_name_fields();
3418 if ($CFG->debugdeveloper) {
3419 foreach ($allnames as $allname) {
3420 if (!property_exists($user, $allname)) {
3421 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3422 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3423 // Message has been sent, no point in sending the message multiple times.
3424 break;
3429 if (!$override) {
3430 if (!empty($CFG->forcefirstname)) {
3431 $user->firstname = $CFG->forcefirstname;
3433 if (!empty($CFG->forcelastname)) {
3434 $user->lastname = $CFG->forcelastname;
3438 if (!empty($SESSION->fullnamedisplay)) {
3439 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3442 $template = null;
3443 // If the fullnamedisplay setting is available, set the template to that.
3444 if (isset($CFG->fullnamedisplay)) {
3445 $template = $CFG->fullnamedisplay;
3447 // If the template is empty, or set to language, return the language string.
3448 if ((empty($template) || $template == 'language') && !$override) {
3449 return get_string('fullnamedisplay', null, $user);
3452 // Check to see if we are displaying according to the alternative full name format.
3453 if ($override) {
3454 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3455 // Default to show just the user names according to the fullnamedisplay string.
3456 return get_string('fullnamedisplay', null, $user);
3457 } else {
3458 // If the override is true, then change the template to use the complete name.
3459 $template = $CFG->alternativefullnameformat;
3463 $requirednames = array();
3464 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3465 foreach ($allnames as $allname) {
3466 if (strpos($template, $allname) !== false) {
3467 $requirednames[] = $allname;
3471 $displayname = $template;
3472 // Switch in the actual data into the template.
3473 foreach ($requirednames as $altname) {
3474 if (isset($user->$altname)) {
3475 // Using empty() on the below if statement causes breakages.
3476 if ((string)$user->$altname == '') {
3477 $displayname = str_replace($altname, 'EMPTY', $displayname);
3478 } else {
3479 $displayname = str_replace($altname, $user->$altname, $displayname);
3481 } else {
3482 $displayname = str_replace($altname, 'EMPTY', $displayname);
3485 // Tidy up any misc. characters (Not perfect, but gets most characters).
3486 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3487 // katakana and parenthesis.
3488 $patterns = array();
3489 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3490 // filled in by a user.
3491 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3492 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3493 // This regular expression is to remove any double spaces in the display name.
3494 $patterns[] = '/\s{2,}/u';
3495 foreach ($patterns as $pattern) {
3496 $displayname = preg_replace($pattern, ' ', $displayname);
3499 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3500 $displayname = trim($displayname);
3501 if (empty($displayname)) {
3502 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3503 // people in general feel is a good setting to fall back on.
3504 $displayname = $user->firstname;
3506 return $displayname;
3510 * A centralised location for the all name fields. Returns an array / sql string snippet.
3512 * @param bool $returnsql True for an sql select field snippet.
3513 * @param string $tableprefix table query prefix to use in front of each field.
3514 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3515 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3516 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3517 * @return array|string All name fields.
3519 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3520 // This array is provided in this order because when called by fullname() (above) if firstname is before
3521 // firstnamephonetic str_replace() will change the wrong placeholder.
3522 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3523 'lastnamephonetic' => 'lastnamephonetic',
3524 'middlename' => 'middlename',
3525 'alternatename' => 'alternatename',
3526 'firstname' => 'firstname',
3527 'lastname' => 'lastname');
3529 // Let's add a prefix to the array of user name fields if provided.
3530 if ($prefix) {
3531 foreach ($alternatenames as $key => $altname) {
3532 $alternatenames[$key] = $prefix . $altname;
3536 // If we want the end result to have firstname and lastname at the front / top of the result.
3537 if ($order) {
3538 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3539 for ($i = 0; $i < 2; $i++) {
3540 // Get the last element.
3541 $lastelement = end($alternatenames);
3542 // Remove it from the array.
3543 unset($alternatenames[$lastelement]);
3544 // Put the element back on the top of the array.
3545 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3549 // Create an sql field snippet if requested.
3550 if ($returnsql) {
3551 if ($tableprefix) {
3552 if ($fieldprefix) {
3553 foreach ($alternatenames as $key => $altname) {
3554 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3556 } else {
3557 foreach ($alternatenames as $key => $altname) {
3558 $alternatenames[$key] = $tableprefix . '.' . $altname;
3562 $alternatenames = implode(',', $alternatenames);
3564 return $alternatenames;
3568 * Reduces lines of duplicated code for getting user name fields.
3570 * See also {@link user_picture::unalias()}
3572 * @param object $addtoobject Object to add user name fields to.
3573 * @param object $secondobject Object that contains user name field information.
3574 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3575 * @param array $additionalfields Additional fields to be matched with data in the second object.
3576 * The key can be set to the user table field name.
3577 * @return object User name fields.
3579 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3580 $fields = get_all_user_name_fields(false, null, $prefix);
3581 if ($additionalfields) {
3582 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3583 // the key is a number and then sets the key to the array value.
3584 foreach ($additionalfields as $key => $value) {
3585 if (is_numeric($key)) {
3586 $additionalfields[$value] = $prefix . $value;
3587 unset($additionalfields[$key]);
3588 } else {
3589 $additionalfields[$key] = $prefix . $value;
3592 $fields = array_merge($fields, $additionalfields);
3594 foreach ($fields as $key => $field) {
3595 // Important that we have all of the user name fields present in the object that we are sending back.
3596 $addtoobject->$key = '';
3597 if (isset($secondobject->$field)) {
3598 $addtoobject->$key = $secondobject->$field;
3601 return $addtoobject;
3605 * Returns an array of values in order of occurance in a provided string.
3606 * The key in the result is the character postion in the string.
3608 * @param array $values Values to be found in the string format
3609 * @param string $stringformat The string which may contain values being searched for.
3610 * @return array An array of values in order according to placement in the string format.
3612 function order_in_string($values, $stringformat) {
3613 $valuearray = array();
3614 foreach ($values as $value) {
3615 $pattern = "/$value\b/";
3616 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3617 if (preg_match($pattern, $stringformat)) {
3618 $replacement = "thing";
3619 // Replace the value with something more unique to ensure we get the right position when using strpos().
3620 $newformat = preg_replace($pattern, $replacement, $stringformat);
3621 $position = strpos($newformat, $replacement);
3622 $valuearray[$position] = $value;
3625 ksort($valuearray);
3626 return $valuearray;
3630 * Checks if current user is shown any extra fields when listing users.
3632 * @param object $context Context
3633 * @param array $already Array of fields that we're going to show anyway
3634 * so don't bother listing them
3635 * @return array Array of field names from user table, not including anything
3636 * listed in $already
3638 function get_extra_user_fields($context, $already = array()) {
3639 global $CFG;
3641 // Only users with permission get the extra fields.
3642 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3643 return array();
3646 // Split showuseridentity on comma.
3647 if (empty($CFG->showuseridentity)) {
3648 // Explode gives wrong result with empty string.
3649 $extra = array();
3650 } else {
3651 $extra = explode(',', $CFG->showuseridentity);
3653 $renumber = false;
3654 foreach ($extra as $key => $field) {
3655 if (in_array($field, $already)) {
3656 unset($extra[$key]);
3657 $renumber = true;
3660 if ($renumber) {
3661 // For consistency, if entries are removed from array, renumber it
3662 // so they are numbered as you would expect.
3663 $extra = array_merge($extra);
3665 return $extra;
3669 * If the current user is to be shown extra user fields when listing or
3670 * selecting users, returns a string suitable for including in an SQL select
3671 * clause to retrieve those fields.
3673 * @param context $context Context
3674 * @param string $alias Alias of user table, e.g. 'u' (default none)
3675 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3676 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3677 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3679 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3680 $fields = get_extra_user_fields($context, $already);
3681 $result = '';
3682 // Add punctuation for alias.
3683 if ($alias !== '') {
3684 $alias .= '.';
3686 foreach ($fields as $field) {
3687 $result .= ', ' . $alias . $field;
3688 if ($prefix) {
3689 $result .= ' AS ' . $prefix . $field;
3692 return $result;
3696 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3697 * @param string $field Field name, e.g. 'phone1'
3698 * @return string Text description taken from language file, e.g. 'Phone number'
3700 function get_user_field_name($field) {
3701 // Some fields have language strings which are not the same as field name.
3702 switch ($field) {
3703 case 'url' : {
3704 return get_string('webpage');
3706 case 'icq' : {
3707 return get_string('icqnumber');
3709 case 'skype' : {
3710 return get_string('skypeid');
3712 case 'aim' : {
3713 return get_string('aimid');
3715 case 'yahoo' : {
3716 return get_string('yahooid');
3718 case 'msn' : {
3719 return get_string('msnid');
3721 case 'picture' : {
3722 return get_string('pictureofuser');
3725 // Otherwise just use the same lang string.
3726 return get_string($field);
3730 * Returns whether a given authentication plugin exists.
3732 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3733 * @return boolean Whether the plugin is available.
3735 function exists_auth_plugin($auth) {
3736 global $CFG;
3738 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3739 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3741 return false;
3745 * Checks if a given plugin is in the list of enabled authentication plugins.
3747 * @param string $auth Authentication plugin.
3748 * @return boolean Whether the plugin is enabled.
3750 function is_enabled_auth($auth) {
3751 if (empty($auth)) {
3752 return false;
3755 $enabled = get_enabled_auth_plugins();
3757 return in_array($auth, $enabled);
3761 * Returns an authentication plugin instance.
3763 * @param string $auth name of authentication plugin
3764 * @return auth_plugin_base An instance of the required authentication plugin.
3766 function get_auth_plugin($auth) {
3767 global $CFG;
3769 // Check the plugin exists first.
3770 if (! exists_auth_plugin($auth)) {
3771 print_error('authpluginnotfound', 'debug', '', $auth);
3774 // Return auth plugin instance.
3775 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3776 $class = "auth_plugin_$auth";
3777 return new $class;
3781 * Returns array of active auth plugins.
3783 * @param bool $fix fix $CFG->auth if needed
3784 * @return array
3786 function get_enabled_auth_plugins($fix=false) {
3787 global $CFG;
3789 $default = array('manual', 'nologin');
3791 if (empty($CFG->auth)) {
3792 $auths = array();
3793 } else {
3794 $auths = explode(',', $CFG->auth);
3797 if ($fix) {
3798 $auths = array_unique($auths);
3799 foreach ($auths as $k => $authname) {
3800 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3801 unset($auths[$k]);
3804 $newconfig = implode(',', $auths);
3805 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3806 set_config('auth', $newconfig);
3810 return (array_merge($default, $auths));
3814 * Returns true if an internal authentication method is being used.
3815 * if method not specified then, global default is assumed
3817 * @param string $auth Form of authentication required
3818 * @return bool
3820 function is_internal_auth($auth) {
3821 // Throws error if bad $auth.
3822 $authplugin = get_auth_plugin($auth);
3823 return $authplugin->is_internal();
3827 * Returns true if the user is a 'restored' one.
3829 * Used in the login process to inform the user and allow him/her to reset the password
3831 * @param string $username username to be checked
3832 * @return bool
3834 function is_restored_user($username) {
3835 global $CFG, $DB;
3837 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3841 * Returns an array of user fields
3843 * @return array User field/column names
3845 function get_user_fieldnames() {
3846 global $DB;
3848 $fieldarray = $DB->get_columns('user');
3849 unset($fieldarray['id']);
3850 $fieldarray = array_keys($fieldarray);
3852 return $fieldarray;
3856 * Creates a bare-bones user record
3858 * @todo Outline auth types and provide code example
3860 * @param string $username New user's username to add to record
3861 * @param string $password New user's password to add to record
3862 * @param string $auth Form of authentication required
3863 * @return stdClass A complete user object
3865 function create_user_record($username, $password, $auth = 'manual') {
3866 global $CFG, $DB;
3867 require_once($CFG->dirroot.'/user/profile/lib.php');
3868 require_once($CFG->dirroot.'/user/lib.php');
3870 // Just in case check text case.
3871 $username = trim(core_text::strtolower($username));
3873 $authplugin = get_auth_plugin($auth);
3874 $customfields = $authplugin->get_custom_user_profile_fields();
3875 $newuser = new stdClass();
3876 if ($newinfo = $authplugin->get_userinfo($username)) {
3877 $newinfo = truncate_userinfo($newinfo);
3878 foreach ($newinfo as $key => $value) {
3879 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3880 $newuser->$key = $value;
3885 if (!empty($newuser->email)) {
3886 if (email_is_not_allowed($newuser->email)) {
3887 unset($newuser->email);
3891 if (!isset($newuser->city)) {
3892 $newuser->city = '';
3895 $newuser->auth = $auth;
3896 $newuser->username = $username;
3898 // Fix for MDL-8480
3899 // user CFG lang for user if $newuser->lang is empty
3900 // or $user->lang is not an installed language.
3901 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3902 $newuser->lang = $CFG->lang;
3904 $newuser->confirmed = 1;
3905 $newuser->lastip = getremoteaddr();
3906 $newuser->timecreated = time();
3907 $newuser->timemodified = $newuser->timecreated;
3908 $newuser->mnethostid = $CFG->mnet_localhost_id;
3910 $newuser->id = user_create_user($newuser, false, false);
3912 // Save user profile data.
3913 profile_save_data($newuser);
3915 $user = get_complete_user_data('id', $newuser->id);
3916 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3917 set_user_preference('auth_forcepasswordchange', 1, $user);
3919 // Set the password.
3920 update_internal_user_password($user, $password);
3922 // Trigger event.
3923 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3925 return $user;
3929 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3931 * @param string $username user's username to update the record
3932 * @return stdClass A complete user object
3934 function update_user_record($username) {
3935 global $DB, $CFG;
3936 // Just in case check text case.
3937 $username = trim(core_text::strtolower($username));
3939 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3940 return update_user_record_by_id($oldinfo->id);
3944 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3946 * @param int $id user id
3947 * @return stdClass A complete user object
3949 function update_user_record_by_id($id) {
3950 global $DB, $CFG;
3951 require_once($CFG->dirroot."/user/profile/lib.php");
3952 require_once($CFG->dirroot.'/user/lib.php');
3954 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3955 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3957 $newuser = array();
3958 $userauth = get_auth_plugin($oldinfo->auth);
3960 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3961 $newinfo = truncate_userinfo($newinfo);
3962 $customfields = $userauth->get_custom_user_profile_fields();
3964 foreach ($newinfo as $key => $value) {
3965 $iscustom = in_array($key, $customfields);
3966 if (!$iscustom) {
3967 $key = strtolower($key);
3969 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3970 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3971 // Unknown or must not be changed.
3972 continue;
3974 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
3975 continue;
3977 $confval = $userauth->config->{'field_updatelocal_' . $key};
3978 $lockval = $userauth->config->{'field_lock_' . $key};
3979 if ($confval === 'onlogin') {
3980 // MDL-4207 Don't overwrite modified user profile values with
3981 // empty LDAP values when 'unlocked if empty' is set. The purpose
3982 // of the setting 'unlocked if empty' is to allow the user to fill
3983 // in a value for the selected field _if LDAP is giving
3984 // nothing_ for this field. Thus it makes sense to let this value
3985 // stand in until LDAP is giving a value for this field.
3986 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3987 if ($iscustom || (in_array($key, $userauth->userfields) &&
3988 ((string)$oldinfo->$key !== (string)$value))) {
3989 $newuser[$key] = (string)$value;
3994 if ($newuser) {
3995 $newuser['id'] = $oldinfo->id;
3996 $newuser['timemodified'] = time();
3997 user_update_user((object) $newuser, false, false);
3999 // Save user profile data.
4000 profile_save_data((object) $newuser);
4002 // Trigger event.
4003 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4007 return get_complete_user_data('id', $oldinfo->id);
4011 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4013 * @param array $info Array of user properties to truncate if needed
4014 * @return array The now truncated information that was passed in
4016 function truncate_userinfo(array $info) {
4017 // Define the limits.
4018 $limit = array(
4019 'username' => 100,
4020 'idnumber' => 255,
4021 'firstname' => 100,
4022 'lastname' => 100,
4023 'email' => 100,
4024 'icq' => 15,
4025 'phone1' => 20,
4026 'phone2' => 20,
4027 'institution' => 255,
4028 'department' => 255,
4029 'address' => 255,
4030 'city' => 120,
4031 'country' => 2,
4032 'url' => 255,
4035 // Apply where needed.
4036 foreach (array_keys($info) as $key) {
4037 if (!empty($limit[$key])) {
4038 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4042 return $info;
4046 * Marks user deleted in internal user database and notifies the auth plugin.
4047 * Also unenrols user from all roles and does other cleanup.
4049 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4051 * @param stdClass $user full user object before delete
4052 * @return boolean success
4053 * @throws coding_exception if invalid $user parameter detected
4055 function delete_user(stdClass $user) {
4056 global $CFG, $DB;
4057 require_once($CFG->libdir.'/grouplib.php');
4058 require_once($CFG->libdir.'/gradelib.php');
4059 require_once($CFG->dirroot.'/message/lib.php');
4060 require_once($CFG->dirroot.'/user/lib.php');
4062 // Make sure nobody sends bogus record type as parameter.
4063 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4064 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4067 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4068 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4069 debugging('Attempt to delete unknown user account.');
4070 return false;
4073 // There must be always exactly one guest record, originally the guest account was identified by username only,
4074 // now we use $CFG->siteguest for performance reasons.
4075 if ($user->username === 'guest' or isguestuser($user)) {
4076 debugging('Guest user account can not be deleted.');
4077 return false;
4080 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4081 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4082 if ($user->auth === 'manual' and is_siteadmin($user)) {
4083 debugging('Local administrator accounts can not be deleted.');
4084 return false;
4087 // Allow plugins to use this user object before we completely delete it.
4088 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4089 foreach ($pluginsfunction as $plugintype => $plugins) {
4090 foreach ($plugins as $pluginfunction) {
4091 $pluginfunction($user);
4096 // Keep user record before updating it, as we have to pass this to user_deleted event.
4097 $olduser = clone $user;
4099 // Keep a copy of user context, we need it for event.
4100 $usercontext = context_user::instance($user->id);
4102 // Delete all grades - backup is kept in grade_grades_history table.
4103 grade_user_delete($user->id);
4105 // TODO: remove from cohorts using standard API here.
4107 // Remove user tags.
4108 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4110 // Unconditionally unenrol from all courses.
4111 enrol_user_delete($user);
4113 // Unenrol from all roles in all contexts.
4114 // This might be slow but it is really needed - modules might do some extra cleanup!
4115 role_unassign_all(array('userid' => $user->id));
4117 // Now do a brute force cleanup.
4119 // Remove from all cohorts.
4120 $DB->delete_records('cohort_members', array('userid' => $user->id));
4122 // Remove from all groups.
4123 $DB->delete_records('groups_members', array('userid' => $user->id));
4125 // Brute force unenrol from all courses.
4126 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4128 // Purge user preferences.
4129 $DB->delete_records('user_preferences', array('userid' => $user->id));
4131 // Purge user extra profile info.
4132 $DB->delete_records('user_info_data', array('userid' => $user->id));
4134 // Purge log of previous password hashes.
4135 $DB->delete_records('user_password_history', array('userid' => $user->id));
4137 // Last course access not necessary either.
4138 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4139 // Remove all user tokens.
4140 $DB->delete_records('external_tokens', array('userid' => $user->id));
4142 // Unauthorise the user for all services.
4143 $DB->delete_records('external_services_users', array('userid' => $user->id));
4145 // Remove users private keys.
4146 $DB->delete_records('user_private_key', array('userid' => $user->id));
4148 // Remove users customised pages.
4149 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4151 // Force logout - may fail if file based sessions used, sorry.
4152 \core\session\manager::kill_user_sessions($user->id);
4154 // Generate username from email address, or a fake email.
4155 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4156 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
4158 // Workaround for bulk deletes of users with the same email address.
4159 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4160 $delname++;
4163 // Mark internal user record as "deleted".
4164 $updateuser = new stdClass();
4165 $updateuser->id = $user->id;
4166 $updateuser->deleted = 1;
4167 $updateuser->username = $delname; // Remember it just in case.
4168 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4169 $updateuser->idnumber = ''; // Clear this field to free it up.
4170 $updateuser->picture = 0;
4171 $updateuser->timemodified = time();
4173 // Don't trigger update event, as user is being deleted.
4174 user_update_user($updateuser, false, false);
4176 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4177 context_helper::delete_instance(CONTEXT_USER, $user->id);
4179 // Any plugin that needs to cleanup should register this event.
4180 // Trigger event.
4181 $event = \core\event\user_deleted::create(
4182 array(
4183 'objectid' => $user->id,
4184 'relateduserid' => $user->id,
4185 'context' => $usercontext,
4186 'other' => array(
4187 'username' => $user->username,
4188 'email' => $user->email,
4189 'idnumber' => $user->idnumber,
4190 'picture' => $user->picture,
4191 'mnethostid' => $user->mnethostid
4195 $event->add_record_snapshot('user', $olduser);
4196 $event->trigger();
4198 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4199 // should know about this updated property persisted to the user's table.
4200 $user->timemodified = $updateuser->timemodified;
4202 // Notify auth plugin - do not block the delete even when plugin fails.
4203 $authplugin = get_auth_plugin($user->auth);
4204 $authplugin->user_delete($user);
4206 return true;
4210 * Retrieve the guest user object.
4212 * @return stdClass A {@link $USER} object
4214 function guest_user() {
4215 global $CFG, $DB;
4217 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4218 $newuser->confirmed = 1;
4219 $newuser->lang = $CFG->lang;
4220 $newuser->lastip = getremoteaddr();
4223 return $newuser;
4227 * Authenticates a user against the chosen authentication mechanism
4229 * Given a username and password, this function looks them
4230 * up using the currently selected authentication mechanism,
4231 * and if the authentication is successful, it returns a
4232 * valid $user object from the 'user' table.
4234 * Uses auth_ functions from the currently active auth module
4236 * After authenticate_user_login() returns success, you will need to
4237 * log that the user has logged in, and call complete_user_login() to set
4238 * the session up.
4240 * Note: this function works only with non-mnet accounts!
4242 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4243 * @param string $password User's password
4244 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4245 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4246 * @return stdClass|false A {@link $USER} object or false if error
4248 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4249 global $CFG, $DB;
4250 require_once("$CFG->libdir/authlib.php");
4252 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4253 // we have found the user
4255 } else if (!empty($CFG->authloginviaemail)) {
4256 if ($email = clean_param($username, PARAM_EMAIL)) {
4257 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4258 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4259 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4260 if (count($users) === 1) {
4261 // Use email for login only if unique.
4262 $user = reset($users);
4263 $user = get_complete_user_data('id', $user->id);
4264 $username = $user->username;
4266 unset($users);
4270 $authsenabled = get_enabled_auth_plugins();
4272 if ($user) {
4273 // Use manual if auth not set.
4274 $auth = empty($user->auth) ? 'manual' : $user->auth;
4276 if (in_array($user->auth, $authsenabled)) {
4277 $authplugin = get_auth_plugin($user->auth);
4278 $authplugin->pre_user_login_hook($user);
4281 if (!empty($user->suspended)) {
4282 $failurereason = AUTH_LOGIN_SUSPENDED;
4284 // Trigger login failed event.
4285 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4286 'other' => array('username' => $username, 'reason' => $failurereason)));
4287 $event->trigger();
4288 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4289 return false;
4291 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4292 // Legacy way to suspend user.
4293 $failurereason = AUTH_LOGIN_SUSPENDED;
4295 // Trigger login failed event.
4296 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4297 'other' => array('username' => $username, 'reason' => $failurereason)));
4298 $event->trigger();
4299 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4300 return false;
4302 $auths = array($auth);
4304 } else {
4305 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4306 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4307 $failurereason = AUTH_LOGIN_NOUSER;
4309 // Trigger login failed event.
4310 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4311 'reason' => $failurereason)));
4312 $event->trigger();
4313 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4314 return false;
4317 // User does not exist.
4318 $auths = $authsenabled;
4319 $user = new stdClass();
4320 $user->id = 0;
4323 if ($ignorelockout) {
4324 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4325 // or this function is called from a SSO script.
4326 } else if ($user->id) {
4327 // Verify login lockout after other ways that may prevent user login.
4328 if (login_is_lockedout($user)) {
4329 $failurereason = AUTH_LOGIN_LOCKOUT;
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();
4336 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4337 return false;
4339 } else {
4340 // We can not lockout non-existing accounts.
4343 foreach ($auths as $auth) {
4344 $authplugin = get_auth_plugin($auth);
4346 // On auth fail fall through to the next plugin.
4347 if (!$authplugin->user_login($username, $password)) {
4348 continue;
4351 // Successful authentication.
4352 if ($user->id) {
4353 // User already exists in database.
4354 if (empty($user->auth)) {
4355 // For some reason auth isn't set yet.
4356 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4357 $user->auth = $auth;
4360 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4361 // the current hash algorithm while we have access to the user's password.
4362 update_internal_user_password($user, $password);
4364 if ($authplugin->is_synchronised_with_external()) {
4365 // Update user record from external DB.
4366 $user = update_user_record_by_id($user->id);
4368 } else {
4369 // The user is authenticated but user creation may be disabled.
4370 if (!empty($CFG->authpreventaccountcreation)) {
4371 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4373 // Trigger login failed event.
4374 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4375 'reason' => $failurereason)));
4376 $event->trigger();
4378 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4379 $_SERVER['HTTP_USER_AGENT']);
4380 return false;
4381 } else {
4382 $user = create_user_record($username, $password, $auth);
4386 $authplugin->sync_roles($user);
4388 foreach ($authsenabled as $hau) {
4389 $hauth = get_auth_plugin($hau);
4390 $hauth->user_authenticated_hook($user, $username, $password);
4393 if (empty($user->id)) {
4394 $failurereason = AUTH_LOGIN_NOUSER;
4395 // Trigger login failed event.
4396 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4397 'reason' => $failurereason)));
4398 $event->trigger();
4399 return false;
4402 if (!empty($user->suspended)) {
4403 // Just in case some auth plugin suspended account.
4404 $failurereason = AUTH_LOGIN_SUSPENDED;
4405 // Trigger login failed event.
4406 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4407 'other' => array('username' => $username, 'reason' => $failurereason)));
4408 $event->trigger();
4409 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4410 return false;
4413 login_attempt_valid($user);
4414 $failurereason = AUTH_LOGIN_OK;
4415 return $user;
4418 // Failed if all the plugins have failed.
4419 if (debugging('', DEBUG_ALL)) {
4420 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4423 if ($user->id) {
4424 login_attempt_failed($user);
4425 $failurereason = AUTH_LOGIN_FAILED;
4426 // Trigger login failed event.
4427 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4428 'other' => array('username' => $username, 'reason' => $failurereason)));
4429 $event->trigger();
4430 } else {
4431 $failurereason = AUTH_LOGIN_NOUSER;
4432 // Trigger login failed event.
4433 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4434 'reason' => $failurereason)));
4435 $event->trigger();
4438 return false;
4442 * Call to complete the user login process after authenticate_user_login()
4443 * has succeeded. It will setup the $USER variable and other required bits
4444 * and pieces.
4446 * NOTE:
4447 * - It will NOT log anything -- up to the caller to decide what to log.
4448 * - this function does not set any cookies any more!
4450 * @param stdClass $user
4451 * @return stdClass A {@link $USER} object - BC only, do not use
4453 function complete_user_login($user) {
4454 global $CFG, $DB, $USER, $SESSION;
4456 \core\session\manager::login_user($user);
4458 // Reload preferences from DB.
4459 unset($USER->preference);
4460 check_user_preferences_loaded($USER);
4462 // Update login times.
4463 update_user_login_times();
4465 // Extra session prefs init.
4466 set_login_session_preferences();
4468 // Trigger login event.
4469 $event = \core\event\user_loggedin::create(
4470 array(
4471 'userid' => $USER->id,
4472 'objectid' => $USER->id,
4473 'other' => array('username' => $USER->username),
4476 $event->trigger();
4478 // Queue migrating the messaging data, if we need to.
4479 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4480 // Check if there are any legacy messages to migrate.
4481 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4482 \core_message\task\migrate_message_data::queue_task($USER->id);
4483 } else {
4484 set_user_preference('core_message_migrate_data', true, $USER->id);
4488 if (isguestuser()) {
4489 // No need to continue when user is THE guest.
4490 return $USER;
4493 if (CLI_SCRIPT) {
4494 // We can redirect to password change URL only in browser.
4495 return $USER;
4498 // Select password change url.
4499 $userauth = get_auth_plugin($USER->auth);
4501 // Check whether the user should be changing password.
4502 if (get_user_preferences('auth_forcepasswordchange', false)) {
4503 if ($userauth->can_change_password()) {
4504 if ($changeurl = $userauth->change_password_url()) {
4505 redirect($changeurl);
4506 } else {
4507 require_once($CFG->dirroot . '/login/lib.php');
4508 $SESSION->wantsurl = core_login_get_return_url();
4509 redirect($CFG->wwwroot.'/login/change_password.php');
4511 } else {
4512 print_error('nopasswordchangeforced', 'auth');
4515 return $USER;
4519 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4521 * @param string $password String to check.
4522 * @return boolean True if the $password matches the format of an md5 sum.
4524 function password_is_legacy_hash($password) {
4525 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4529 * Compare password against hash stored in user object to determine if it is valid.
4531 * If necessary it also updates the stored hash to the current format.
4533 * @param stdClass $user (Password property may be updated).
4534 * @param string $password Plain text password.
4535 * @return bool True if password is valid.
4537 function validate_internal_user_password($user, $password) {
4538 global $CFG;
4540 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4541 // Internal password is not used at all, it can not validate.
4542 return false;
4545 // If hash isn't a legacy (md5) hash, validate using the library function.
4546 if (!password_is_legacy_hash($user->password)) {
4547 return password_verify($password, $user->password);
4550 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4551 // is valid we can then update it to the new algorithm.
4553 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4554 $validated = false;
4556 if ($user->password === md5($password.$sitesalt)
4557 or $user->password === md5($password)
4558 or $user->password === md5(addslashes($password).$sitesalt)
4559 or $user->password === md5(addslashes($password))) {
4560 // Note: we are intentionally using the addslashes() here because we
4561 // need to accept old password hashes of passwords with magic quotes.
4562 $validated = true;
4564 } else {
4565 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4566 $alt = 'passwordsaltalt'.$i;
4567 if (!empty($CFG->$alt)) {
4568 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4569 $validated = true;
4570 break;
4576 if ($validated) {
4577 // If the password matches the existing md5 hash, update to the
4578 // current hash algorithm while we have access to the user's password.
4579 update_internal_user_password($user, $password);
4582 return $validated;
4586 * Calculate hash for a plain text password.
4588 * @param string $password Plain text password to be hashed.
4589 * @param bool $fasthash If true, use a low cost factor when generating the hash
4590 * This is much faster to generate but makes the hash
4591 * less secure. It is used when lots of hashes need to
4592 * be generated quickly.
4593 * @return string The hashed password.
4595 * @throws moodle_exception If a problem occurs while generating the hash.
4597 function hash_internal_user_password($password, $fasthash = false) {
4598 global $CFG;
4600 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4601 $options = ($fasthash) ? array('cost' => 4) : array();
4603 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4605 if ($generatedhash === false || $generatedhash === null) {
4606 throw new moodle_exception('Failed to generate password hash.');
4609 return $generatedhash;
4613 * Update password hash in user object (if necessary).
4615 * The password is updated if:
4616 * 1. The password has changed (the hash of $user->password is different
4617 * to the hash of $password).
4618 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4619 * md5 algorithm).
4621 * Updating the password will modify the $user object and the database
4622 * record to use the current hashing algorithm.
4623 * It will remove Web Services user tokens too.
4625 * @param stdClass $user User object (password property may be updated).
4626 * @param string $password Plain text password.
4627 * @param bool $fasthash If true, use a low cost factor when generating the hash
4628 * This is much faster to generate but makes the hash
4629 * less secure. It is used when lots of hashes need to
4630 * be generated quickly.
4631 * @return bool Always returns true.
4633 function update_internal_user_password($user, $password, $fasthash = false) {
4634 global $CFG, $DB;
4636 // Figure out what the hashed password should be.
4637 if (!isset($user->auth)) {
4638 debugging('User record in update_internal_user_password() must include field auth',
4639 DEBUG_DEVELOPER);
4640 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4642 $authplugin = get_auth_plugin($user->auth);
4643 if ($authplugin->prevent_local_passwords()) {
4644 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4645 } else {
4646 $hashedpassword = hash_internal_user_password($password, $fasthash);
4649 $algorithmchanged = false;
4651 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4652 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4653 $passwordchanged = ($user->password !== $hashedpassword);
4655 } else if (isset($user->password)) {
4656 // If verification fails then it means the password has changed.
4657 $passwordchanged = !password_verify($password, $user->password);
4658 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4659 } else {
4660 // While creating new user, password in unset in $user object, to avoid
4661 // saving it with user_create()
4662 $passwordchanged = true;
4665 if ($passwordchanged || $algorithmchanged) {
4666 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4667 $user->password = $hashedpassword;
4669 // Trigger event.
4670 $user = $DB->get_record('user', array('id' => $user->id));
4671 \core\event\user_password_updated::create_from_user($user)->trigger();
4673 // Remove WS user tokens.
4674 if (!empty($CFG->passwordchangetokendeletion)) {
4675 require_once($CFG->dirroot.'/webservice/lib.php');
4676 webservice::delete_user_ws_tokens($user->id);
4680 return true;
4684 * Get a complete user record, which includes all the info in the user record.
4686 * Intended for setting as $USER session variable
4688 * @param string $field The user field to be checked for a given value.
4689 * @param string $value The value to match for $field.
4690 * @param int $mnethostid
4691 * @return mixed False, or A {@link $USER} object.
4693 function get_complete_user_data($field, $value, $mnethostid = null) {
4694 global $CFG, $DB;
4696 if (!$field || !$value) {
4697 return false;
4700 // Build the WHERE clause for an SQL query.
4701 $params = array('fieldval' => $value);
4702 $constraints = "$field = :fieldval AND deleted <> 1";
4704 // If we are loading user data based on anything other than id,
4705 // we must also restrict our search based on mnet host.
4706 if ($field != 'id') {
4707 if (empty($mnethostid)) {
4708 // If empty, we restrict to local users.
4709 $mnethostid = $CFG->mnet_localhost_id;
4712 if (!empty($mnethostid)) {
4713 $params['mnethostid'] = $mnethostid;
4714 $constraints .= " AND mnethostid = :mnethostid";
4717 // Get all the basic user data.
4718 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4719 return false;
4722 // Get various settings and preferences.
4724 // Preload preference cache.
4725 check_user_preferences_loaded($user);
4727 // Load course enrolment related stuff.
4728 $user->lastcourseaccess = array(); // During last session.
4729 $user->currentcourseaccess = array(); // During current session.
4730 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4731 foreach ($lastaccesses as $lastaccess) {
4732 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4736 $sql = "SELECT g.id, g.courseid
4737 FROM {groups} g, {groups_members} gm
4738 WHERE gm.groupid=g.id AND gm.userid=?";
4740 // This is a special hack to speedup calendar display.
4741 $user->groupmember = array();
4742 if (!isguestuser($user)) {
4743 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4744 foreach ($groups as $group) {
4745 if (!array_key_exists($group->courseid, $user->groupmember)) {
4746 $user->groupmember[$group->courseid] = array();
4748 $user->groupmember[$group->courseid][$group->id] = $group->id;
4753 // Add cohort theme.
4754 if (!empty($CFG->allowcohortthemes)) {
4755 require_once($CFG->dirroot . '/cohort/lib.php');
4756 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4757 $user->cohorttheme = $cohorttheme;
4761 // Add the custom profile fields to the user record.
4762 $user->profile = array();
4763 if (!isguestuser($user)) {
4764 require_once($CFG->dirroot.'/user/profile/lib.php');
4765 profile_load_custom_fields($user);
4768 // Rewrite some variables if necessary.
4769 if (!empty($user->description)) {
4770 // No need to cart all of it around.
4771 $user->description = true;
4773 if (isguestuser($user)) {
4774 // Guest language always same as site.
4775 $user->lang = $CFG->lang;
4776 // Name always in current language.
4777 $user->firstname = get_string('guestuser');
4778 $user->lastname = ' ';
4781 return $user;
4785 * Validate a password against the configured password policy
4787 * @param string $password the password to be checked against the password policy
4788 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4789 * @return bool true if the password is valid according to the policy. false otherwise.
4791 function check_password_policy($password, &$errmsg) {
4792 global $CFG;
4794 if (!empty($CFG->passwordpolicy)) {
4795 $errmsg = '';
4796 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4797 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4799 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4800 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4802 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4803 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4805 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4806 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4808 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4809 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4811 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4812 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4816 // Fire any additional password policy functions from plugins.
4817 // Plugin functions should output an error message string or empty string for success.
4818 $pluginsfunction = get_plugins_with_function('check_password_policy');
4819 foreach ($pluginsfunction as $plugintype => $plugins) {
4820 foreach ($plugins as $pluginfunction) {
4821 $pluginerr = $pluginfunction($password);
4822 if ($pluginerr) {
4823 $errmsg .= '<div>'. $pluginerr .'</div>';
4828 if ($errmsg == '') {
4829 return true;
4830 } else {
4831 return false;
4837 * When logging in, this function is run to set certain preferences for the current SESSION.
4839 function set_login_session_preferences() {
4840 global $SESSION;
4842 $SESSION->justloggedin = true;
4844 unset($SESSION->lang);
4845 unset($SESSION->forcelang);
4846 unset($SESSION->load_navigation_admin);
4851 * Delete a course, including all related data from the database, and any associated files.
4853 * @param mixed $courseorid The id of the course or course object to delete.
4854 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4855 * @return bool true if all the removals succeeded. false if there were any failures. If this
4856 * method returns false, some of the removals will probably have succeeded, and others
4857 * failed, but you have no way of knowing which.
4859 function delete_course($courseorid, $showfeedback = true) {
4860 global $DB;
4862 if (is_object($courseorid)) {
4863 $courseid = $courseorid->id;
4864 $course = $courseorid;
4865 } else {
4866 $courseid = $courseorid;
4867 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4868 return false;
4871 $context = context_course::instance($courseid);
4873 // Frontpage course can not be deleted!!
4874 if ($courseid == SITEID) {
4875 return false;
4878 // Allow plugins to use this course before we completely delete it.
4879 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
4880 foreach ($pluginsfunction as $plugintype => $plugins) {
4881 foreach ($plugins as $pluginfunction) {
4882 $pluginfunction($course);
4887 // Make the course completely empty.
4888 remove_course_contents($courseid, $showfeedback);
4890 // Delete the course and related context instance.
4891 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4893 $DB->delete_records("course", array("id" => $courseid));
4894 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4896 // Reset all course related caches here.
4897 if (class_exists('format_base', false)) {
4898 format_base::reset_course_cache($courseid);
4901 // Trigger a course deleted event.
4902 $event = \core\event\course_deleted::create(array(
4903 'objectid' => $course->id,
4904 'context' => $context,
4905 'other' => array(
4906 'shortname' => $course->shortname,
4907 'fullname' => $course->fullname,
4908 'idnumber' => $course->idnumber
4911 $event->add_record_snapshot('course', $course);
4912 $event->trigger();
4914 return true;
4918 * Clear a course out completely, deleting all content but don't delete the course itself.
4920 * This function does not verify any permissions.
4922 * Please note this function also deletes all user enrolments,
4923 * enrolment instances and role assignments by default.
4925 * $options:
4926 * - 'keep_roles_and_enrolments' - false by default
4927 * - 'keep_groups_and_groupings' - false by default
4929 * @param int $courseid The id of the course that is being deleted
4930 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4931 * @param array $options extra options
4932 * @return bool true if all the removals succeeded. false if there were any failures. If this
4933 * method returns false, some of the removals will probably have succeeded, and others
4934 * failed, but you have no way of knowing which.
4936 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4937 global $CFG, $DB, $OUTPUT;
4939 require_once($CFG->libdir.'/badgeslib.php');
4940 require_once($CFG->libdir.'/completionlib.php');
4941 require_once($CFG->libdir.'/questionlib.php');
4942 require_once($CFG->libdir.'/gradelib.php');
4943 require_once($CFG->dirroot.'/group/lib.php');
4944 require_once($CFG->dirroot.'/comment/lib.php');
4945 require_once($CFG->dirroot.'/rating/lib.php');
4946 require_once($CFG->dirroot.'/notes/lib.php');
4948 // Handle course badges.
4949 badges_handle_course_deletion($courseid);
4951 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4952 $strdeleted = get_string('deleted').' - ';
4954 // Some crazy wishlist of stuff we should skip during purging of course content.
4955 $options = (array)$options;
4957 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
4958 $coursecontext = context_course::instance($courseid);
4959 $fs = get_file_storage();
4961 // Delete course completion information, this has to be done before grades and enrols.
4962 $cc = new completion_info($course);
4963 $cc->clear_criteria();
4964 if ($showfeedback) {
4965 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4968 // Remove all data from gradebook - this needs to be done before course modules
4969 // because while deleting this information, the system may need to reference
4970 // the course modules that own the grades.
4971 remove_course_grades($courseid, $showfeedback);
4972 remove_grade_letters($coursecontext, $showfeedback);
4974 // Delete course blocks in any all child contexts,
4975 // they may depend on modules so delete them first.
4976 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4977 foreach ($childcontexts as $childcontext) {
4978 blocks_delete_all_for_context($childcontext->id);
4980 unset($childcontexts);
4981 blocks_delete_all_for_context($coursecontext->id);
4982 if ($showfeedback) {
4983 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4986 // Get the list of all modules that are properly installed.
4987 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
4989 // Delete every instance of every module,
4990 // this has to be done before deleting of course level stuff.
4991 $locations = core_component::get_plugin_list('mod');
4992 foreach ($locations as $modname => $moddir) {
4993 if ($modname === 'NEWMODULE') {
4994 continue;
4996 if (array_key_exists($modname, $allmodules)) {
4997 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
4998 FROM {".$modname."} m
4999 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5000 WHERE m.course = :courseid";
5001 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5002 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5004 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5005 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5006 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
5008 if ($instances) {
5009 foreach ($instances as $cm) {
5010 if ($cm->id) {
5011 // Delete activity context questions and question categories.
5012 question_delete_activity($cm, $showfeedback);
5013 // Notify the competency subsystem.
5014 \core_competency\api::hook_course_module_deleted($cm);
5016 if (function_exists($moddelete)) {
5017 // This purges all module data in related tables, extra user prefs, settings, etc.
5018 $moddelete($cm->modinstance);
5019 } else {
5020 // NOTE: we should not allow installation of modules with missing delete support!
5021 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5022 $DB->delete_records($modname, array('id' => $cm->modinstance));
5025 if ($cm->id) {
5026 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5027 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5028 $DB->delete_records('course_modules', array('id' => $cm->id));
5032 if (function_exists($moddeletecourse)) {
5033 // Execute optional course cleanup callback. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
5034 debugging("Callback delete_course is deprecated. Function $moddeletecourse should be converted " .
5035 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER);
5036 $moddeletecourse($course, $showfeedback);
5038 if ($instances and $showfeedback) {
5039 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5041 } else {
5042 // Ooops, this module is not properly installed, force-delete it in the next block.
5046 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5048 // Delete completion defaults.
5049 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5051 // Remove all data from availability and completion tables that is associated
5052 // with course-modules belonging to this course. Note this is done even if the
5053 // features are not enabled now, in case they were enabled previously.
5054 $DB->delete_records_select('course_modules_completion',
5055 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5056 array($courseid));
5058 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5059 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5060 $allmodulesbyid = array_flip($allmodules);
5061 foreach ($cms as $cm) {
5062 if (array_key_exists($cm->module, $allmodulesbyid)) {
5063 try {
5064 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5065 } catch (Exception $e) {
5066 // Ignore weird or missing table problems.
5069 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5070 $DB->delete_records('course_modules', array('id' => $cm->id));
5073 if ($showfeedback) {
5074 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5077 // Cleanup the rest of plugins. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
5078 $cleanuplugintypes = array('report', 'coursereport', 'format');
5079 $callbacks = get_plugins_with_function('delete_course', 'lib.php');
5080 foreach ($cleanuplugintypes as $type) {
5081 if (!empty($callbacks[$type])) {
5082 foreach ($callbacks[$type] as $pluginfunction) {
5083 debugging("Callback delete_course is deprecated. Function $pluginfunction should be converted " .
5084 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER);
5085 $pluginfunction($course->id, $showfeedback);
5087 if ($showfeedback) {
5088 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5093 // Delete questions and question categories.
5094 question_delete_course($course, $showfeedback);
5095 if ($showfeedback) {
5096 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5099 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5100 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5101 foreach ($childcontexts as $childcontext) {
5102 $childcontext->delete();
5104 unset($childcontexts);
5106 // Remove all roles and enrolments by default.
5107 if (empty($options['keep_roles_and_enrolments'])) {
5108 // This hack is used in restore when deleting contents of existing course.
5109 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5110 enrol_course_delete($course);
5111 if ($showfeedback) {
5112 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5116 // Delete any groups, removing members and grouping/course links first.
5117 if (empty($options['keep_groups_and_groupings'])) {
5118 groups_delete_groupings($course->id, $showfeedback);
5119 groups_delete_groups($course->id, $showfeedback);
5122 // Filters be gone!
5123 filter_delete_all_for_context($coursecontext->id);
5125 // Notes, you shall not pass!
5126 note_delete_all($course->id);
5128 // Die comments!
5129 comment::delete_comments($coursecontext->id);
5131 // Ratings are history too.
5132 $delopt = new stdclass();
5133 $delopt->contextid = $coursecontext->id;
5134 $rm = new rating_manager();
5135 $rm->delete_ratings($delopt);
5137 // Delete course tags.
5138 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5140 // Notify the competency subsystem.
5141 \core_competency\api::hook_course_deleted($course);
5143 // Delete calendar events.
5144 $DB->delete_records('event', array('courseid' => $course->id));
5145 $fs->delete_area_files($coursecontext->id, 'calendar');
5147 // Delete all related records in other core tables that may have a courseid
5148 // This array stores the tables that need to be cleared, as
5149 // table_name => column_name that contains the course id.
5150 $tablestoclear = array(
5151 'backup_courses' => 'courseid', // Scheduled backup stuff.
5152 'user_lastaccess' => 'courseid', // User access info.
5154 foreach ($tablestoclear as $table => $col) {
5155 $DB->delete_records($table, array($col => $course->id));
5158 // Delete all course backup files.
5159 $fs->delete_area_files($coursecontext->id, 'backup');
5161 // Cleanup course record - remove links to deleted stuff.
5162 $oldcourse = new stdClass();
5163 $oldcourse->id = $course->id;
5164 $oldcourse->summary = '';
5165 $oldcourse->cacherev = 0;
5166 $oldcourse->legacyfiles = 0;
5167 if (!empty($options['keep_groups_and_groupings'])) {
5168 $oldcourse->defaultgroupingid = 0;
5170 $DB->update_record('course', $oldcourse);
5172 // Delete course sections.
5173 $DB->delete_records('course_sections', array('course' => $course->id));
5175 // Delete legacy, section and any other course files.
5176 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5178 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5179 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5180 // Easy, do not delete the context itself...
5181 $coursecontext->delete_content();
5182 } else {
5183 // Hack alert!!!!
5184 // We can not drop all context stuff because it would bork enrolments and roles,
5185 // there might be also files used by enrol plugins...
5188 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5189 // also some non-standard unsupported plugins may try to store something there.
5190 fulldelete($CFG->dataroot.'/'.$course->id);
5192 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5193 $cachemodinfo = cache::make('core', 'coursemodinfo');
5194 $cachemodinfo->delete($courseid);
5196 // Trigger a course content deleted event.
5197 $event = \core\event\course_content_deleted::create(array(
5198 'objectid' => $course->id,
5199 'context' => $coursecontext,
5200 'other' => array('shortname' => $course->shortname,
5201 'fullname' => $course->fullname,
5202 'options' => $options) // Passing this for legacy reasons.
5204 $event->add_record_snapshot('course', $course);
5205 $event->trigger();
5207 return true;
5211 * Change dates in module - used from course reset.
5213 * @param string $modname forum, assignment, etc
5214 * @param array $fields array of date fields from mod table
5215 * @param int $timeshift time difference
5216 * @param int $courseid
5217 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5218 * @return bool success
5220 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5221 global $CFG, $DB;
5222 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5224 $return = true;
5225 $params = array($timeshift, $courseid);
5226 foreach ($fields as $field) {
5227 $updatesql = "UPDATE {".$modname."}
5228 SET $field = $field + ?
5229 WHERE course=? AND $field<>0";
5230 if ($modid) {
5231 $updatesql .= ' AND id=?';
5232 $params[] = $modid;
5234 $return = $DB->execute($updatesql, $params) && $return;
5237 return $return;
5241 * This function will empty a course of user data.
5242 * It will retain the activities and the structure of the course.
5244 * @param object $data an object containing all the settings including courseid (without magic quotes)
5245 * @return array status array of array component, item, error
5247 function reset_course_userdata($data) {
5248 global $CFG, $DB;
5249 require_once($CFG->libdir.'/gradelib.php');
5250 require_once($CFG->libdir.'/completionlib.php');
5251 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5252 require_once($CFG->dirroot.'/group/lib.php');
5254 $data->courseid = $data->id;
5255 $context = context_course::instance($data->courseid);
5257 $eventparams = array(
5258 'context' => $context,
5259 'courseid' => $data->id,
5260 'other' => array(
5261 'reset_options' => (array) $data
5264 $event = \core\event\course_reset_started::create($eventparams);
5265 $event->trigger();
5267 // Calculate the time shift of dates.
5268 if (!empty($data->reset_start_date)) {
5269 // Time part of course startdate should be zero.
5270 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5271 } else {
5272 $data->timeshift = 0;
5275 // Result array: component, item, error.
5276 $status = array();
5278 // Start the resetting.
5279 $componentstr = get_string('general');
5281 // Move the course start time.
5282 if (!empty($data->reset_start_date) and $data->timeshift) {
5283 // Change course start data.
5284 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5285 // Update all course and group events - do not move activity events.
5286 $updatesql = "UPDATE {event}
5287 SET timestart = timestart + ?
5288 WHERE courseid=? AND instance=0";
5289 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5291 // Update any date activity restrictions.
5292 if ($CFG->enableavailability) {
5293 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5296 // Update completion expected dates.
5297 if ($CFG->enablecompletion) {
5298 $modinfo = get_fast_modinfo($data->courseid);
5299 $changed = false;
5300 foreach ($modinfo->get_cms() as $cm) {
5301 if ($cm->completion && !empty($cm->completionexpected)) {
5302 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5303 array('id' => $cm->id));
5304 $changed = true;
5308 // Clear course cache if changes made.
5309 if ($changed) {
5310 rebuild_course_cache($data->courseid, true);
5313 // Update course date completion criteria.
5314 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5317 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5320 if (!empty($data->reset_end_date)) {
5321 // If the user set a end date value respect it.
5322 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5323 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5324 // If there is a time shift apply it to the end date as well.
5325 $enddate = $data->reset_end_date_old + $data->timeshift;
5326 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5329 if (!empty($data->reset_events)) {
5330 $DB->delete_records('event', array('courseid' => $data->courseid));
5331 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5334 if (!empty($data->reset_notes)) {
5335 require_once($CFG->dirroot.'/notes/lib.php');
5336 note_delete_all($data->courseid);
5337 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5340 if (!empty($data->delete_blog_associations)) {
5341 require_once($CFG->dirroot.'/blog/lib.php');
5342 blog_remove_associations_for_course($data->courseid);
5343 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5346 if (!empty($data->reset_completion)) {
5347 // Delete course and activity completion information.
5348 $course = $DB->get_record('course', array('id' => $data->courseid));
5349 $cc = new completion_info($course);
5350 $cc->delete_all_completion_data();
5351 $status[] = array('component' => $componentstr,
5352 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5355 if (!empty($data->reset_competency_ratings)) {
5356 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5357 $status[] = array('component' => $componentstr,
5358 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5361 $componentstr = get_string('roles');
5363 if (!empty($data->reset_roles_overrides)) {
5364 $children = $context->get_child_contexts();
5365 foreach ($children as $child) {
5366 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5368 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5369 // Force refresh for logged in users.
5370 $context->mark_dirty();
5371 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5374 if (!empty($data->reset_roles_local)) {
5375 $children = $context->get_child_contexts();
5376 foreach ($children as $child) {
5377 role_unassign_all(array('contextid' => $child->id));
5379 // Force refresh for logged in users.
5380 $context->mark_dirty();
5381 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5384 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5385 $data->unenrolled = array();
5386 if (!empty($data->unenrol_users)) {
5387 $plugins = enrol_get_plugins(true);
5388 $instances = enrol_get_instances($data->courseid, true);
5389 foreach ($instances as $key => $instance) {
5390 if (!isset($plugins[$instance->enrol])) {
5391 unset($instances[$key]);
5392 continue;
5396 foreach ($data->unenrol_users as $withroleid) {
5397 if ($withroleid) {
5398 $sql = "SELECT ue.*
5399 FROM {user_enrolments} ue
5400 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5401 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5402 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5403 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5405 } else {
5406 // Without any role assigned at course context.
5407 $sql = "SELECT ue.*
5408 FROM {user_enrolments} ue
5409 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5410 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5411 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5412 WHERE ra.id IS null";
5413 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5416 $rs = $DB->get_recordset_sql($sql, $params);
5417 foreach ($rs as $ue) {
5418 if (!isset($instances[$ue->enrolid])) {
5419 continue;
5421 $instance = $instances[$ue->enrolid];
5422 $plugin = $plugins[$instance->enrol];
5423 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5424 continue;
5427 $plugin->unenrol_user($instance, $ue->userid);
5428 $data->unenrolled[$ue->userid] = $ue->userid;
5430 $rs->close();
5433 if (!empty($data->unenrolled)) {
5434 $status[] = array(
5435 'component' => $componentstr,
5436 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5437 'error' => false
5441 $componentstr = get_string('groups');
5443 // Remove all group members.
5444 if (!empty($data->reset_groups_members)) {
5445 groups_delete_group_members($data->courseid);
5446 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5449 // Remove all groups.
5450 if (!empty($data->reset_groups_remove)) {
5451 groups_delete_groups($data->courseid, false);
5452 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5455 // Remove all grouping members.
5456 if (!empty($data->reset_groupings_members)) {
5457 groups_delete_groupings_groups($data->courseid, false);
5458 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5461 // Remove all groupings.
5462 if (!empty($data->reset_groupings_remove)) {
5463 groups_delete_groupings($data->courseid, false);
5464 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5467 // Look in every instance of every module for data to delete.
5468 $unsupportedmods = array();
5469 if ($allmods = $DB->get_records('modules') ) {
5470 foreach ($allmods as $mod) {
5471 $modname = $mod->name;
5472 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5473 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5474 if (file_exists($modfile)) {
5475 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5476 continue; // Skip mods with no instances.
5478 include_once($modfile);
5479 if (function_exists($moddeleteuserdata)) {
5480 $modstatus = $moddeleteuserdata($data);
5481 if (is_array($modstatus)) {
5482 $status = array_merge($status, $modstatus);
5483 } else {
5484 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5486 } else {
5487 $unsupportedmods[] = $mod;
5489 } else {
5490 debugging('Missing lib.php in '.$modname.' module!');
5492 // Update calendar events for all modules.
5493 course_module_bulk_update_calendar_events($modname, $data->courseid);
5497 // Mention unsupported mods.
5498 if (!empty($unsupportedmods)) {
5499 foreach ($unsupportedmods as $mod) {
5500 $status[] = array(
5501 'component' => get_string('modulenameplural', $mod->name),
5502 'item' => '',
5503 'error' => get_string('resetnotimplemented')
5508 $componentstr = get_string('gradebook', 'grades');
5509 // Reset gradebook,.
5510 if (!empty($data->reset_gradebook_items)) {
5511 remove_course_grades($data->courseid, false);
5512 grade_grab_course_grades($data->courseid);
5513 grade_regrade_final_grades($data->courseid);
5514 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5516 } else if (!empty($data->reset_gradebook_grades)) {
5517 grade_course_reset($data->courseid);
5518 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5520 // Reset comments.
5521 if (!empty($data->reset_comments)) {
5522 require_once($CFG->dirroot.'/comment/lib.php');
5523 comment::reset_course_page_comments($context);
5526 $event = \core\event\course_reset_ended::create($eventparams);
5527 $event->trigger();
5529 return $status;
5533 * Generate an email processing address.
5535 * @param int $modid
5536 * @param string $modargs
5537 * @return string Returns email processing address
5539 function generate_email_processing_address($modid, $modargs) {
5540 global $CFG;
5542 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5543 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5549 * @todo Finish documenting this function
5551 * @param string $modargs
5552 * @param string $body Currently unused
5554 function moodle_process_email($modargs, $body) {
5555 global $DB;
5557 // The first char should be an unencoded letter. We'll take this as an action.
5558 switch ($modargs{0}) {
5559 case 'B': { // Bounce.
5560 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5561 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5562 // Check the half md5 of their email.
5563 $md5check = substr(md5($user->email), 0, 16);
5564 if ($md5check == substr($modargs, -16)) {
5565 set_bounce_count($user);
5567 // Else maybe they've already changed it?
5570 break;
5571 // Maybe more later?
5575 // CORRESPONDENCE.
5578 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5580 * @param string $action 'get', 'buffer', 'close' or 'flush'
5581 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5583 function get_mailer($action='get') {
5584 global $CFG;
5586 /** @var moodle_phpmailer $mailer */
5587 static $mailer = null;
5588 static $counter = 0;
5590 if (!isset($CFG->smtpmaxbulk)) {
5591 $CFG->smtpmaxbulk = 1;
5594 if ($action == 'get') {
5595 $prevkeepalive = false;
5597 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5598 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5599 $counter++;
5600 // Reset the mailer.
5601 $mailer->Priority = 3;
5602 $mailer->CharSet = 'UTF-8'; // Our default.
5603 $mailer->ContentType = "text/plain";
5604 $mailer->Encoding = "8bit";
5605 $mailer->From = "root@localhost";
5606 $mailer->FromName = "Root User";
5607 $mailer->Sender = "";
5608 $mailer->Subject = "";
5609 $mailer->Body = "";
5610 $mailer->AltBody = "";
5611 $mailer->ConfirmReadingTo = "";
5613 $mailer->clearAllRecipients();
5614 $mailer->clearReplyTos();
5615 $mailer->clearAttachments();
5616 $mailer->clearCustomHeaders();
5617 return $mailer;
5620 $prevkeepalive = $mailer->SMTPKeepAlive;
5621 get_mailer('flush');
5624 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5625 $mailer = new moodle_phpmailer();
5627 $counter = 1;
5629 if ($CFG->smtphosts == 'qmail') {
5630 // Use Qmail system.
5631 $mailer->isQmail();
5633 } else if (empty($CFG->smtphosts)) {
5634 // Use PHP mail() = sendmail.
5635 $mailer->isMail();
5637 } else {
5638 // Use SMTP directly.
5639 $mailer->isSMTP();
5640 if (!empty($CFG->debugsmtp)) {
5641 $mailer->SMTPDebug = 3;
5643 // Specify main and backup servers.
5644 $mailer->Host = $CFG->smtphosts;
5645 // Specify secure connection protocol.
5646 $mailer->SMTPSecure = $CFG->smtpsecure;
5647 // Use previous keepalive.
5648 $mailer->SMTPKeepAlive = $prevkeepalive;
5650 if ($CFG->smtpuser) {
5651 // Use SMTP authentication.
5652 $mailer->SMTPAuth = true;
5653 $mailer->Username = $CFG->smtpuser;
5654 $mailer->Password = $CFG->smtppass;
5658 return $mailer;
5661 $nothing = null;
5663 // Keep smtp session open after sending.
5664 if ($action == 'buffer') {
5665 if (!empty($CFG->smtpmaxbulk)) {
5666 get_mailer('flush');
5667 $m = get_mailer();
5668 if ($m->Mailer == 'smtp') {
5669 $m->SMTPKeepAlive = true;
5672 return $nothing;
5675 // Close smtp session, but continue buffering.
5676 if ($action == 'flush') {
5677 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5678 if (!empty($mailer->SMTPDebug)) {
5679 echo '<pre>'."\n";
5681 $mailer->SmtpClose();
5682 if (!empty($mailer->SMTPDebug)) {
5683 echo '</pre>';
5686 return $nothing;
5689 // Close smtp session, do not buffer anymore.
5690 if ($action == 'close') {
5691 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5692 get_mailer('flush');
5693 $mailer->SMTPKeepAlive = false;
5695 $mailer = null; // Better force new instance.
5696 return $nothing;
5701 * A helper function to test for email diversion
5703 * @param string $email
5704 * @return bool Returns true if the email should be diverted
5706 function email_should_be_diverted($email) {
5707 global $CFG;
5709 if (empty($CFG->divertallemailsto)) {
5710 return false;
5713 if (empty($CFG->divertallemailsexcept)) {
5714 return true;
5717 $patterns = array_map('trim', explode(',', $CFG->divertallemailsexcept));
5718 foreach ($patterns as $pattern) {
5719 if (preg_match("/$pattern/", $email)) {
5720 return false;
5724 return true;
5728 * Generate a unique email Message-ID using the moodle domain and install path
5730 * @param string $localpart An optional unique message id prefix.
5731 * @return string The formatted ID ready for appending to the email headers.
5733 function generate_email_messageid($localpart = null) {
5734 global $CFG;
5736 $urlinfo = parse_url($CFG->wwwroot);
5737 $base = '@' . $urlinfo['host'];
5739 // If multiple moodles are on the same domain we want to tell them
5740 // apart so we add the install path to the local part. This means
5741 // that the id local part should never contain a / character so
5742 // we can correctly parse the id to reassemble the wwwroot.
5743 if (isset($urlinfo['path'])) {
5744 $base = $urlinfo['path'] . $base;
5747 if (empty($localpart)) {
5748 $localpart = uniqid('', true);
5751 // Because we may have an option /installpath suffix to the local part
5752 // of the id we need to escape any / chars which are in the $localpart.
5753 $localpart = str_replace('/', '%2F', $localpart);
5755 return '<' . $localpart . $base . '>';
5759 * Send an email to a specified user
5761 * @param stdClass $user A {@link $USER} object
5762 * @param stdClass $from A {@link $USER} object
5763 * @param string $subject plain text subject line of the email
5764 * @param string $messagetext plain text version of the message
5765 * @param string $messagehtml complete html version of the message (optional)
5766 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5767 * @param string $attachname the name of the file (extension indicates MIME)
5768 * @param bool $usetrueaddress determines whether $from email address should
5769 * be sent out. Will be overruled by user profile setting for maildisplay
5770 * @param string $replyto Email address to reply to
5771 * @param string $replytoname Name of reply to recipient
5772 * @param int $wordwrapwidth custom word wrap width, default 79
5773 * @return bool Returns true if mail was sent OK and false if there was an error.
5775 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5776 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5778 global $CFG, $PAGE, $SITE;
5780 if (empty($user) or empty($user->id)) {
5781 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5782 return false;
5785 if (empty($user->email)) {
5786 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5787 return false;
5790 if (!empty($user->deleted)) {
5791 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5792 return false;
5795 if (defined('BEHAT_SITE_RUNNING')) {
5796 // Fake email sending in behat.
5797 return true;
5800 if (!empty($CFG->noemailever)) {
5801 // Hidden setting for development sites, set in config.php if needed.
5802 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5803 return true;
5806 if (email_should_be_diverted($user->email)) {
5807 $subject = "[DIVERTED {$user->email}] $subject";
5808 $user = clone($user);
5809 $user->email = $CFG->divertallemailsto;
5812 // Skip mail to suspended users.
5813 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5814 return true;
5817 if (!validate_email($user->email)) {
5818 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5819 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5820 return false;
5823 if (over_bounce_threshold($user)) {
5824 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5825 return false;
5828 // TLD .invalid is specifically reserved for invalid domain names.
5829 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5830 if (substr($user->email, -8) == '.invalid') {
5831 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5832 return true; // This is not an error.
5835 // If the user is a remote mnet user, parse the email text for URL to the
5836 // wwwroot and modify the url to direct the user's browser to login at their
5837 // home site (identity provider - idp) before hitting the link itself.
5838 if (is_mnet_remote_user($user)) {
5839 require_once($CFG->dirroot.'/mnet/lib.php');
5841 $jumpurl = mnet_get_idp_jump_url($user);
5842 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5844 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5845 $callback,
5846 $messagetext);
5847 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5848 $callback,
5849 $messagehtml);
5851 $mail = get_mailer();
5853 if (!empty($mail->SMTPDebug)) {
5854 echo '<pre>' . "\n";
5857 $temprecipients = array();
5858 $tempreplyto = array();
5860 // Make sure that we fall back onto some reasonable no-reply address.
5861 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
5862 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
5864 if (!validate_email($noreplyaddress)) {
5865 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
5866 $noreplyaddress = $noreplyaddressdefault;
5869 // Make up an email address for handling bounces.
5870 if (!empty($CFG->handlebounces)) {
5871 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5872 $mail->Sender = generate_email_processing_address(0, $modargs);
5873 } else {
5874 $mail->Sender = $noreplyaddress;
5877 // Make sure that the explicit replyto is valid, fall back to the implicit one.
5878 if (!empty($replyto) && !validate_email($replyto)) {
5879 debugging('email_to_user: Invalid replyto-email '.s($replyto));
5880 $replyto = $noreplyaddress;
5883 if (is_string($from)) { // So we can pass whatever we want if there is need.
5884 $mail->From = $noreplyaddress;
5885 $mail->FromName = $from;
5886 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
5887 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
5888 // in a course with the sender.
5889 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
5890 if (!validate_email($from->email)) {
5891 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
5892 // Better not to use $noreplyaddress in this case.
5893 return false;
5895 $mail->From = $from->email;
5896 $fromdetails = new stdClass();
5897 $fromdetails->name = fullname($from);
5898 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5899 $fromdetails->siteshortname = format_string($SITE->shortname);
5900 $fromstring = $fromdetails->name;
5901 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
5902 $fromstring = get_string('emailvia', 'core', $fromdetails);
5904 $mail->FromName = $fromstring;
5905 if (empty($replyto)) {
5906 $tempreplyto[] = array($from->email, fullname($from));
5908 } else {
5909 $mail->From = $noreplyaddress;
5910 $fromdetails = new stdClass();
5911 $fromdetails->name = fullname($from);
5912 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5913 $fromdetails->siteshortname = format_string($SITE->shortname);
5914 $fromstring = $fromdetails->name;
5915 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
5916 $fromstring = get_string('emailvia', 'core', $fromdetails);
5918 $mail->FromName = $fromstring;
5919 if (empty($replyto)) {
5920 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
5924 if (!empty($replyto)) {
5925 $tempreplyto[] = array($replyto, $replytoname);
5928 $temprecipients[] = array($user->email, fullname($user));
5930 // Set word wrap.
5931 $mail->WordWrap = $wordwrapwidth;
5933 if (!empty($from->customheaders)) {
5934 // Add custom headers.
5935 if (is_array($from->customheaders)) {
5936 foreach ($from->customheaders as $customheader) {
5937 $mail->addCustomHeader($customheader);
5939 } else {
5940 $mail->addCustomHeader($from->customheaders);
5944 // If the X-PHP-Originating-Script email header is on then also add an additional
5945 // header with details of where exactly in moodle the email was triggered from,
5946 // either a call to message_send() or to email_to_user().
5947 if (ini_get('mail.add_x_header')) {
5949 $stack = debug_backtrace(false);
5950 $origin = $stack[0];
5952 foreach ($stack as $depth => $call) {
5953 if ($call['function'] == 'message_send') {
5954 $origin = $call;
5958 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
5959 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
5960 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
5963 if (!empty($from->priority)) {
5964 $mail->Priority = $from->priority;
5967 $renderer = $PAGE->get_renderer('core');
5968 $context = array(
5969 'sitefullname' => $SITE->fullname,
5970 'siteshortname' => $SITE->shortname,
5971 'sitewwwroot' => $CFG->wwwroot,
5972 'subject' => $subject,
5973 'to' => $user->email,
5974 'toname' => fullname($user),
5975 'from' => $mail->From,
5976 'fromname' => $mail->FromName,
5978 if (!empty($tempreplyto[0])) {
5979 $context['replyto'] = $tempreplyto[0][0];
5980 $context['replytoname'] = $tempreplyto[0][1];
5982 if ($user->id > 0) {
5983 $context['touserid'] = $user->id;
5984 $context['tousername'] = $user->username;
5987 if (!empty($user->mailformat) && $user->mailformat == 1) {
5988 // Only process html templates if the user preferences allow html email.
5990 if ($messagehtml) {
5991 // If html has been given then pass it through the template.
5992 $context['body'] = $messagehtml;
5993 $messagehtml = $renderer->render_from_template('core/email_html', $context);
5995 } else {
5996 // If no html has been given, BUT there is an html wrapping template then
5997 // auto convert the text to html and then wrap it.
5998 $autohtml = trim(text_to_html($messagetext));
5999 $context['body'] = $autohtml;
6000 $temphtml = $renderer->render_from_template('core/email_html', $context);
6001 if ($autohtml != $temphtml) {
6002 $messagehtml = $temphtml;
6007 $context['body'] = $messagetext;
6008 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
6009 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
6010 $messagetext = $renderer->render_from_template('core/email_text', $context);
6012 // Autogenerate a MessageID if it's missing.
6013 if (empty($mail->MessageID)) {
6014 $mail->MessageID = generate_email_messageid();
6017 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6018 // Don't ever send HTML to users who don't want it.
6019 $mail->isHTML(true);
6020 $mail->Encoding = 'quoted-printable';
6021 $mail->Body = $messagehtml;
6022 $mail->AltBody = "\n$messagetext\n";
6023 } else {
6024 $mail->IsHTML(false);
6025 $mail->Body = "\n$messagetext\n";
6028 if ($attachment && $attachname) {
6029 if (preg_match( "~\\.\\.~" , $attachment )) {
6030 // Security check for ".." in dir path.
6031 $supportuser = core_user::get_support_user();
6032 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6033 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6034 } else {
6035 require_once($CFG->libdir.'/filelib.php');
6036 $mimetype = mimeinfo('type', $attachname);
6038 $attachmentpath = $attachment;
6040 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6041 $attachpath = str_replace('\\', '/', $attachmentpath);
6042 // Make sure both variables are normalised before comparing.
6043 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
6045 // If the attachment is a full path to a file in the tempdir, use it as is,
6046 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6047 if (strpos($attachpath, $temppath) !== 0) {
6048 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
6051 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
6055 // Check if the email should be sent in an other charset then the default UTF-8.
6056 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6058 // Use the defined site mail charset or eventually the one preferred by the recipient.
6059 $charset = $CFG->sitemailcharset;
6060 if (!empty($CFG->allowusermailcharset)) {
6061 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6062 $charset = $useremailcharset;
6066 // Convert all the necessary strings if the charset is supported.
6067 $charsets = get_list_of_charsets();
6068 unset($charsets['UTF-8']);
6069 if (in_array($charset, $charsets)) {
6070 $mail->CharSet = $charset;
6071 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6072 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6073 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6074 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6076 foreach ($temprecipients as $key => $values) {
6077 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6079 foreach ($tempreplyto as $key => $values) {
6080 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6085 foreach ($temprecipients as $values) {
6086 $mail->addAddress($values[0], $values[1]);
6088 foreach ($tempreplyto as $values) {
6089 $mail->addReplyTo($values[0], $values[1]);
6092 if ($mail->send()) {
6093 set_send_count($user);
6094 if (!empty($mail->SMTPDebug)) {
6095 echo '</pre>';
6097 return true;
6098 } else {
6099 // Trigger event for failing to send email.
6100 $event = \core\event\email_failed::create(array(
6101 'context' => context_system::instance(),
6102 'userid' => $from->id,
6103 'relateduserid' => $user->id,
6104 'other' => array(
6105 'subject' => $subject,
6106 'message' => $messagetext,
6107 'errorinfo' => $mail->ErrorInfo
6110 $event->trigger();
6111 if (CLI_SCRIPT) {
6112 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6114 if (!empty($mail->SMTPDebug)) {
6115 echo '</pre>';
6117 return false;
6122 * Check to see if a user's real email address should be used for the "From" field.
6124 * @param object $from The user object for the user we are sending the email from.
6125 * @param object $user The user object that we are sending the email to.
6126 * @param array $unused No longer used.
6127 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6129 function can_send_from_real_email_address($from, $user, $unused = null) {
6130 global $CFG;
6131 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6132 return false;
6134 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6135 // Email is in the list of allowed domains for sending email,
6136 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6137 // in a course with the sender.
6138 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6139 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6140 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6141 && enrol_get_shared_courses($user, $from, false, true)))) {
6142 return true;
6144 return false;
6148 * Generate a signoff for emails based on support settings
6150 * @return string
6152 function generate_email_signoff() {
6153 global $CFG;
6155 $signoff = "\n";
6156 if (!empty($CFG->supportname)) {
6157 $signoff .= $CFG->supportname."\n";
6159 if (!empty($CFG->supportemail)) {
6160 $signoff .= $CFG->supportemail."\n";
6162 if (!empty($CFG->supportpage)) {
6163 $signoff .= $CFG->supportpage."\n";
6165 return $signoff;
6169 * Sets specified user's password and send the new password to the user via email.
6171 * @param stdClass $user A {@link $USER} object
6172 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6173 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6175 function setnew_password_and_mail($user, $fasthash = false) {
6176 global $CFG, $DB;
6178 // We try to send the mail in language the user understands,
6179 // unfortunately the filter_string() does not support alternative langs yet
6180 // so multilang will not work properly for site->fullname.
6181 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6183 $site = get_site();
6185 $supportuser = core_user::get_support_user();
6187 $newpassword = generate_password();
6189 update_internal_user_password($user, $newpassword, $fasthash);
6191 $a = new stdClass();
6192 $a->firstname = fullname($user, true);
6193 $a->sitename = format_string($site->fullname);
6194 $a->username = $user->username;
6195 $a->newpassword = $newpassword;
6196 $a->link = $CFG->wwwroot .'/login/';
6197 $a->signoff = generate_email_signoff();
6199 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6201 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6203 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6204 return email_to_user($user, $supportuser, $subject, $message);
6209 * Resets specified user's password and send the new password to the user via email.
6211 * @param stdClass $user A {@link $USER} object
6212 * @return bool Returns true if mail was sent OK and false if there was an error.
6214 function reset_password_and_mail($user) {
6215 global $CFG;
6217 $site = get_site();
6218 $supportuser = core_user::get_support_user();
6220 $userauth = get_auth_plugin($user->auth);
6221 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6222 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6223 return false;
6226 $newpassword = generate_password();
6228 if (!$userauth->user_update_password($user, $newpassword)) {
6229 print_error("cannotsetpassword");
6232 $a = new stdClass();
6233 $a->firstname = $user->firstname;
6234 $a->lastname = $user->lastname;
6235 $a->sitename = format_string($site->fullname);
6236 $a->username = $user->username;
6237 $a->newpassword = $newpassword;
6238 $a->link = $CFG->wwwroot .'/login/change_password.php';
6239 $a->signoff = generate_email_signoff();
6241 $message = get_string('newpasswordtext', '', $a);
6243 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6245 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6247 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6248 return email_to_user($user, $supportuser, $subject, $message);
6252 * Send email to specified user with confirmation text and activation link.
6254 * @param stdClass $user A {@link $USER} object
6255 * @param string $confirmationurl user confirmation URL
6256 * @return bool Returns true if mail was sent OK and false if there was an error.
6258 function send_confirmation_email($user, $confirmationurl = null) {
6259 global $CFG;
6261 $site = get_site();
6262 $supportuser = core_user::get_support_user();
6264 $data = new stdClass();
6265 $data->firstname = fullname($user);
6266 $data->sitename = format_string($site->fullname);
6267 $data->admin = generate_email_signoff();
6269 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6271 if (empty($confirmationurl)) {
6272 $confirmationurl = '/login/confirm.php';
6275 $confirmationurl = new moodle_url($confirmationurl);
6276 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6277 $confirmationurl->remove_params('data');
6278 $confirmationpath = $confirmationurl->out(false);
6280 // We need to custom encode the username to include trailing dots in the link.
6281 // Because of this custom encoding we can't use moodle_url directly.
6282 // Determine if a query string is present in the confirmation url.
6283 $hasquerystring = strpos($confirmationpath, '?') !== false;
6284 // Perform normal url encoding of the username first.
6285 $username = urlencode($user->username);
6286 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6287 $username = str_replace('.', '%2E', $username);
6289 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6291 $message = get_string('emailconfirmation', '', $data);
6292 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6294 $user->mailformat = 1; // Always send HTML version as well.
6296 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6297 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6301 * Sends a password change confirmation email.
6303 * @param stdClass $user A {@link $USER} object
6304 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6305 * @return bool Returns true if mail was sent OK and false if there was an error.
6307 function send_password_change_confirmation_email($user, $resetrecord) {
6308 global $CFG;
6310 $site = get_site();
6311 $supportuser = core_user::get_support_user();
6312 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6314 $data = new stdClass();
6315 $data->firstname = $user->firstname;
6316 $data->lastname = $user->lastname;
6317 $data->username = $user->username;
6318 $data->sitename = format_string($site->fullname);
6319 $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6320 $data->admin = generate_email_signoff();
6321 $data->resetminutes = $pwresetmins;
6323 $message = get_string('emailresetconfirmation', '', $data);
6324 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6326 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6327 return email_to_user($user, $supportuser, $subject, $message);
6332 * Sends an email containinginformation on how to change your password.
6334 * @param stdClass $user A {@link $USER} object
6335 * @return bool Returns true if mail was sent OK and false if there was an error.
6337 function send_password_change_info($user) {
6338 global $CFG;
6340 $site = get_site();
6341 $supportuser = core_user::get_support_user();
6342 $systemcontext = context_system::instance();
6344 $data = new stdClass();
6345 $data->firstname = $user->firstname;
6346 $data->lastname = $user->lastname;
6347 $data->username = $user->username;
6348 $data->sitename = format_string($site->fullname);
6349 $data->admin = generate_email_signoff();
6351 $userauth = get_auth_plugin($user->auth);
6353 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6354 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6355 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6356 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6357 return email_to_user($user, $supportuser, $subject, $message);
6360 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6361 // We have some external url for password changing.
6362 $data->link .= $userauth->change_password_url();
6364 } else {
6365 // No way to change password, sorry.
6366 $data->link = '';
6369 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6370 $message = get_string('emailpasswordchangeinfo', '', $data);
6371 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6372 } else {
6373 $message = get_string('emailpasswordchangeinfofail', '', $data);
6374 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6377 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6378 return email_to_user($user, $supportuser, $subject, $message);
6383 * Check that an email is allowed. It returns an error message if there was a problem.
6385 * @param string $email Content of email
6386 * @return string|false
6388 function email_is_not_allowed($email) {
6389 global $CFG;
6391 if (!empty($CFG->allowemailaddresses)) {
6392 $allowed = explode(' ', $CFG->allowemailaddresses);
6393 foreach ($allowed as $allowedpattern) {
6394 $allowedpattern = trim($allowedpattern);
6395 if (!$allowedpattern) {
6396 continue;
6398 if (strpos($allowedpattern, '.') === 0) {
6399 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6400 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6401 return false;
6404 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6405 return false;
6408 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6410 } else if (!empty($CFG->denyemailaddresses)) {
6411 $denied = explode(' ', $CFG->denyemailaddresses);
6412 foreach ($denied as $deniedpattern) {
6413 $deniedpattern = trim($deniedpattern);
6414 if (!$deniedpattern) {
6415 continue;
6417 if (strpos($deniedpattern, '.') === 0) {
6418 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6419 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6420 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6423 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6424 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6429 return false;
6432 // FILE HANDLING.
6435 * Returns local file storage instance
6437 * @return file_storage
6439 function get_file_storage($reset = false) {
6440 global $CFG;
6442 static $fs = null;
6444 if ($reset) {
6445 $fs = null;
6446 return;
6449 if ($fs) {
6450 return $fs;
6453 require_once("$CFG->libdir/filelib.php");
6455 $fs = new file_storage();
6457 return $fs;
6461 * Returns local file storage instance
6463 * @return file_browser
6465 function get_file_browser() {
6466 global $CFG;
6468 static $fb = null;
6470 if ($fb) {
6471 return $fb;
6474 require_once("$CFG->libdir/filelib.php");
6476 $fb = new file_browser();
6478 return $fb;
6482 * Returns file packer
6484 * @param string $mimetype default application/zip
6485 * @return file_packer
6487 function get_file_packer($mimetype='application/zip') {
6488 global $CFG;
6490 static $fp = array();
6492 if (isset($fp[$mimetype])) {
6493 return $fp[$mimetype];
6496 switch ($mimetype) {
6497 case 'application/zip':
6498 case 'application/vnd.moodle.profiling':
6499 $classname = 'zip_packer';
6500 break;
6502 case 'application/x-gzip' :
6503 $classname = 'tgz_packer';
6504 break;
6506 case 'application/vnd.moodle.backup':
6507 $classname = 'mbz_packer';
6508 break;
6510 default:
6511 return false;
6514 require_once("$CFG->libdir/filestorage/$classname.php");
6515 $fp[$mimetype] = new $classname();
6517 return $fp[$mimetype];
6521 * Returns current name of file on disk if it exists.
6523 * @param string $newfile File to be verified
6524 * @return string Current name of file on disk if true
6526 function valid_uploaded_file($newfile) {
6527 if (empty($newfile)) {
6528 return '';
6530 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6531 return $newfile['tmp_name'];
6532 } else {
6533 return '';
6538 * Returns the maximum size for uploading files.
6540 * There are seven possible upload limits:
6541 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6542 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6543 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6544 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6545 * 5. by the Moodle admin in $CFG->maxbytes
6546 * 6. by the teacher in the current course $course->maxbytes
6547 * 7. by the teacher for the current module, eg $assignment->maxbytes
6549 * These last two are passed to this function as arguments (in bytes).
6550 * Anything defined as 0 is ignored.
6551 * The smallest of all the non-zero numbers is returned.
6553 * @todo Finish documenting this function
6555 * @param int $sitebytes Set maximum size
6556 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6557 * @param int $modulebytes Current module ->maxbytes (in bytes)
6558 * @param bool $unused This parameter has been deprecated and is not used any more.
6559 * @return int The maximum size for uploading files.
6561 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6563 if (! $filesize = ini_get('upload_max_filesize')) {
6564 $filesize = '5M';
6566 $minimumsize = get_real_size($filesize);
6568 if ($postsize = ini_get('post_max_size')) {
6569 $postsize = get_real_size($postsize);
6570 if ($postsize < $minimumsize) {
6571 $minimumsize = $postsize;
6575 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6576 $minimumsize = $sitebytes;
6579 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6580 $minimumsize = $coursebytes;
6583 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6584 $minimumsize = $modulebytes;
6587 return $minimumsize;
6591 * Returns the maximum size for uploading files for the current user
6593 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6595 * @param context $context The context in which to check user capabilities
6596 * @param int $sitebytes Set maximum size
6597 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6598 * @param int $modulebytes Current module ->maxbytes (in bytes)
6599 * @param stdClass $user The user
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_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6604 $unused = false) {
6605 global $USER;
6607 if (empty($user)) {
6608 $user = $USER;
6611 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6612 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6615 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6619 * Returns an array of possible sizes in local language
6621 * Related to {@link get_max_upload_file_size()} - this function returns an
6622 * array of possible sizes in an array, translated to the
6623 * local language.
6625 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6627 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6628 * with the value set to 0. This option will be the first in the list.
6630 * @uses SORT_NUMERIC
6631 * @param int $sitebytes Set maximum size
6632 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6633 * @param int $modulebytes Current module ->maxbytes (in bytes)
6634 * @param int|array $custombytes custom upload size/s which will be added to list,
6635 * Only value/s smaller then maxsize will be added to list.
6636 * @return array
6638 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6639 global $CFG;
6641 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6642 return array();
6645 if ($sitebytes == 0) {
6646 // Will get the minimum of upload_max_filesize or post_max_size.
6647 $sitebytes = get_max_upload_file_size();
6650 $filesize = array();
6651 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6652 5242880, 10485760, 20971520, 52428800, 104857600,
6653 262144000, 524288000, 786432000, 1073741824,
6654 2147483648, 4294967296, 8589934592);
6656 // If custombytes is given and is valid then add it to the list.
6657 if (is_number($custombytes) and $custombytes > 0) {
6658 $custombytes = (int)$custombytes;
6659 if (!in_array($custombytes, $sizelist)) {
6660 $sizelist[] = $custombytes;
6662 } else if (is_array($custombytes)) {
6663 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6666 // Allow maxbytes to be selected if it falls outside the above boundaries.
6667 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6668 // Note: get_real_size() is used in order to prevent problems with invalid values.
6669 $sizelist[] = get_real_size($CFG->maxbytes);
6672 foreach ($sizelist as $sizebytes) {
6673 if ($sizebytes < $maxsize && $sizebytes > 0) {
6674 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6678 $limitlevel = '';
6679 $displaysize = '';
6680 if ($modulebytes &&
6681 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6682 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6683 $limitlevel = get_string('activity', 'core');
6684 $displaysize = display_size($modulebytes);
6685 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6687 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6688 $limitlevel = get_string('course', 'core');
6689 $displaysize = display_size($coursebytes);
6690 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6692 } else if ($sitebytes) {
6693 $limitlevel = get_string('site', 'core');
6694 $displaysize = display_size($sitebytes);
6695 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6698 krsort($filesize, SORT_NUMERIC);
6699 if ($limitlevel) {
6700 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6701 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6704 return $filesize;
6708 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6710 * If excludefiles is defined, then that file/directory is ignored
6711 * If getdirs is true, then (sub)directories are included in the output
6712 * If getfiles is true, then files are included in the output
6713 * (at least one of these must be true!)
6715 * @todo Finish documenting this function. Add examples of $excludefile usage.
6717 * @param string $rootdir A given root directory to start from
6718 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6719 * @param bool $descend If true then subdirectories are recursed as well
6720 * @param bool $getdirs If true then (sub)directories are included in the output
6721 * @param bool $getfiles If true then files are included in the output
6722 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6724 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6726 $dirs = array();
6728 if (!$getdirs and !$getfiles) { // Nothing to show.
6729 return $dirs;
6732 if (!is_dir($rootdir)) { // Must be a directory.
6733 return $dirs;
6736 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6737 return $dirs;
6740 if (!is_array($excludefiles)) {
6741 $excludefiles = array($excludefiles);
6744 while (false !== ($file = readdir($dir))) {
6745 $firstchar = substr($file, 0, 1);
6746 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6747 continue;
6749 $fullfile = $rootdir .'/'. $file;
6750 if (filetype($fullfile) == 'dir') {
6751 if ($getdirs) {
6752 $dirs[] = $file;
6754 if ($descend) {
6755 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6756 foreach ($subdirs as $subdir) {
6757 $dirs[] = $file .'/'. $subdir;
6760 } else if ($getfiles) {
6761 $dirs[] = $file;
6764 closedir($dir);
6766 asort($dirs);
6768 return $dirs;
6773 * Adds up all the files in a directory and works out the size.
6775 * @param string $rootdir The directory to start from
6776 * @param string $excludefile A file to exclude when summing directory size
6777 * @return int The summed size of all files and subfiles within the root directory
6779 function get_directory_size($rootdir, $excludefile='') {
6780 global $CFG;
6782 // Do it this way if we can, it's much faster.
6783 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6784 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6785 $output = null;
6786 $return = null;
6787 exec($command, $output, $return);
6788 if (is_array($output)) {
6789 // We told it to return k.
6790 return get_real_size(intval($output[0]).'k');
6794 if (!is_dir($rootdir)) {
6795 // Must be a directory.
6796 return 0;
6799 if (!$dir = @opendir($rootdir)) {
6800 // Can't open it for some reason.
6801 return 0;
6804 $size = 0;
6806 while (false !== ($file = readdir($dir))) {
6807 $firstchar = substr($file, 0, 1);
6808 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6809 continue;
6811 $fullfile = $rootdir .'/'. $file;
6812 if (filetype($fullfile) == 'dir') {
6813 $size += get_directory_size($fullfile, $excludefile);
6814 } else {
6815 $size += filesize($fullfile);
6818 closedir($dir);
6820 return $size;
6824 * Converts bytes into display form
6826 * @static string $gb Localized string for size in gigabytes
6827 * @static string $mb Localized string for size in megabytes
6828 * @static string $kb Localized string for size in kilobytes
6829 * @static string $b Localized string for size in bytes
6830 * @param int $size The size to convert to human readable form
6831 * @return string
6833 function display_size($size) {
6835 static $gb, $mb, $kb, $b;
6837 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6838 return get_string('unlimited');
6841 if (empty($gb)) {
6842 $gb = get_string('sizegb');
6843 $mb = get_string('sizemb');
6844 $kb = get_string('sizekb');
6845 $b = get_string('sizeb');
6848 if ($size >= 1073741824) {
6849 $size = round($size / 1073741824 * 10) / 10 . $gb;
6850 } else if ($size >= 1048576) {
6851 $size = round($size / 1048576 * 10) / 10 . $mb;
6852 } else if ($size >= 1024) {
6853 $size = round($size / 1024 * 10) / 10 . $kb;
6854 } else {
6855 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6857 return $size;
6861 * Cleans a given filename by removing suspicious or troublesome characters
6863 * @see clean_param()
6864 * @param string $string file name
6865 * @return string cleaned file name
6867 function clean_filename($string) {
6868 return clean_param($string, PARAM_FILE);
6871 // STRING TRANSLATION.
6874 * Returns the code for the current language
6876 * @category string
6877 * @return string
6879 function current_language() {
6880 global $CFG, $USER, $SESSION, $COURSE;
6882 if (!empty($SESSION->forcelang)) {
6883 // Allows overriding course-forced language (useful for admins to check
6884 // issues in courses whose language they don't understand).
6885 // Also used by some code to temporarily get language-related information in a
6886 // specific language (see force_current_language()).
6887 $return = $SESSION->forcelang;
6889 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6890 // Course language can override all other settings for this page.
6891 $return = $COURSE->lang;
6893 } else if (!empty($SESSION->lang)) {
6894 // Session language can override other settings.
6895 $return = $SESSION->lang;
6897 } else if (!empty($USER->lang)) {
6898 $return = $USER->lang;
6900 } else if (isset($CFG->lang)) {
6901 $return = $CFG->lang;
6903 } else {
6904 $return = 'en';
6907 // Just in case this slipped in from somewhere by accident.
6908 $return = str_replace('_utf8', '', $return);
6910 return $return;
6914 * Returns parent language of current active language if defined
6916 * @category string
6917 * @param string $lang null means current language
6918 * @return string
6920 function get_parent_language($lang=null) {
6922 // Let's hack around the current language.
6923 if (!empty($lang)) {
6924 $oldforcelang = force_current_language($lang);
6927 $parentlang = get_string('parentlanguage', 'langconfig');
6928 if ($parentlang === 'en') {
6929 $parentlang = '';
6932 // Let's hack around the current language.
6933 if (!empty($lang)) {
6934 force_current_language($oldforcelang);
6937 return $parentlang;
6941 * Force the current language to get strings and dates localised in the given language.
6943 * After calling this function, all strings will be provided in the given language
6944 * until this function is called again, or equivalent code is run.
6946 * @param string $language
6947 * @return string previous $SESSION->forcelang value
6949 function force_current_language($language) {
6950 global $SESSION;
6951 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6952 if ($language !== $sessionforcelang) {
6953 // Seting forcelang to null or an empty string disables it's effect.
6954 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6955 $SESSION->forcelang = $language;
6956 moodle_setlocale();
6959 return $sessionforcelang;
6963 * Returns current string_manager instance.
6965 * The param $forcereload is needed for CLI installer only where the string_manager instance
6966 * must be replaced during the install.php script life time.
6968 * @category string
6969 * @param bool $forcereload shall the singleton be released and new instance created instead?
6970 * @return core_string_manager
6972 function get_string_manager($forcereload=false) {
6973 global $CFG;
6975 static $singleton = null;
6977 if ($forcereload) {
6978 $singleton = null;
6980 if ($singleton === null) {
6981 if (empty($CFG->early_install_lang)) {
6983 if (empty($CFG->langlist)) {
6984 $translist = array();
6985 } else {
6986 $translist = explode(',', $CFG->langlist);
6989 if (!empty($CFG->config_php_settings['customstringmanager'])) {
6990 $classname = $CFG->config_php_settings['customstringmanager'];
6992 if (class_exists($classname)) {
6993 $implements = class_implements($classname);
6995 if (isset($implements['core_string_manager'])) {
6996 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist);
6997 return $singleton;
6999 } else {
7000 debugging('Unable to instantiate custom string manager: class '.$classname.
7001 ' does not implement the core_string_manager interface.');
7004 } else {
7005 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7009 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
7011 } else {
7012 $singleton = new core_string_manager_install();
7016 return $singleton;
7020 * Returns a localized string.
7022 * Returns the translated string specified by $identifier as
7023 * for $module. Uses the same format files as STphp.
7024 * $a is an object, string or number that can be used
7025 * within translation strings
7027 * eg 'hello {$a->firstname} {$a->lastname}'
7028 * or 'hello {$a}'
7030 * If you would like to directly echo the localized string use
7031 * the function {@link print_string()}
7033 * Example usage of this function involves finding the string you would
7034 * like a local equivalent of and using its identifier and module information
7035 * to retrieve it.<br/>
7036 * If you open moodle/lang/en/moodle.php and look near line 278
7037 * you will find a string to prompt a user for their word for 'course'
7038 * <code>
7039 * $string['course'] = 'Course';
7040 * </code>
7041 * So if you want to display the string 'Course'
7042 * in any language that supports it on your site
7043 * you just need to use the identifier 'course'
7044 * <code>
7045 * $mystring = '<strong>'. get_string('course') .'</strong>';
7046 * or
7047 * </code>
7048 * If the string you want is in another file you'd take a slightly
7049 * different approach. Looking in moodle/lang/en/calendar.php you find
7050 * around line 75:
7051 * <code>
7052 * $string['typecourse'] = 'Course event';
7053 * </code>
7054 * If you want to display the string "Course event" in any language
7055 * supported you would use the identifier 'typecourse' and the module 'calendar'
7056 * (because it is in the file calendar.php):
7057 * <code>
7058 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7059 * </code>
7061 * As a last resort, should the identifier fail to map to a string
7062 * the returned string will be [[ $identifier ]]
7064 * In Moodle 2.3 there is a new argument to this function $lazyload.
7065 * Setting $lazyload to true causes get_string to return a lang_string object
7066 * rather than the string itself. The fetching of the string is then put off until
7067 * the string object is first used. The object can be used by calling it's out
7068 * method or by casting the object to a string, either directly e.g.
7069 * (string)$stringobject
7070 * or indirectly by using the string within another string or echoing it out e.g.
7071 * echo $stringobject
7072 * return "<p>{$stringobject}</p>";
7073 * It is worth noting that using $lazyload and attempting to use the string as an
7074 * array key will cause a fatal error as objects cannot be used as array keys.
7075 * But you should never do that anyway!
7076 * For more information {@link lang_string}
7078 * @category string
7079 * @param string $identifier The key identifier for the localized string
7080 * @param string $component The module where the key identifier is stored,
7081 * usually expressed as the filename in the language pack without the
7082 * .php on the end but can also be written as mod/forum or grade/export/xls.
7083 * If none is specified then moodle.php is used.
7084 * @param string|object|array $a An object, string or number that can be used
7085 * within translation strings
7086 * @param bool $lazyload If set to true a string object is returned instead of
7087 * the string itself. The string then isn't calculated until it is first used.
7088 * @return string The localized string.
7089 * @throws coding_exception
7091 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7092 global $CFG;
7094 // If the lazy load argument has been supplied return a lang_string object
7095 // instead.
7096 // We need to make sure it is true (and a bool) as you will see below there
7097 // used to be a forth argument at one point.
7098 if ($lazyload === true) {
7099 return new lang_string($identifier, $component, $a);
7102 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7103 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7106 // There is now a forth argument again, this time it is a boolean however so
7107 // we can still check for the old extralocations parameter.
7108 if (!is_bool($lazyload) && !empty($lazyload)) {
7109 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7112 if (strpos($component, '/') !== false) {
7113 debugging('The module name you passed to get_string is the deprecated format ' .
7114 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7115 $componentpath = explode('/', $component);
7117 switch ($componentpath[0]) {
7118 case 'mod':
7119 $component = $componentpath[1];
7120 break;
7121 case 'blocks':
7122 case 'block':
7123 $component = 'block_'.$componentpath[1];
7124 break;
7125 case 'enrol':
7126 $component = 'enrol_'.$componentpath[1];
7127 break;
7128 case 'format':
7129 $component = 'format_'.$componentpath[1];
7130 break;
7131 case 'grade':
7132 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7133 break;
7137 $result = get_string_manager()->get_string($identifier, $component, $a);
7139 // Debugging feature lets you display string identifier and component.
7140 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7141 $result .= ' {' . $identifier . '/' . $component . '}';
7143 return $result;
7147 * Converts an array of strings to their localized value.
7149 * @param array $array An array of strings
7150 * @param string $component The language module that these strings can be found in.
7151 * @return stdClass translated strings.
7153 function get_strings($array, $component = '') {
7154 $string = new stdClass;
7155 foreach ($array as $item) {
7156 $string->$item = get_string($item, $component);
7158 return $string;
7162 * Prints out a translated string.
7164 * Prints out a translated string using the return value from the {@link get_string()} function.
7166 * Example usage of this function when the string is in the moodle.php file:<br/>
7167 * <code>
7168 * echo '<strong>';
7169 * print_string('course');
7170 * echo '</strong>';
7171 * </code>
7173 * Example usage of this function when the string is not in the moodle.php file:<br/>
7174 * <code>
7175 * echo '<h1>';
7176 * print_string('typecourse', 'calendar');
7177 * echo '</h1>';
7178 * </code>
7180 * @category string
7181 * @param string $identifier The key identifier for the localized string
7182 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7183 * @param string|object|array $a An object, string or number that can be used within translation strings
7185 function print_string($identifier, $component = '', $a = null) {
7186 echo get_string($identifier, $component, $a);
7190 * Returns a list of charset codes
7192 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7193 * (checking that such charset is supported by the texlib library!)
7195 * @return array And associative array with contents in the form of charset => charset
7197 function get_list_of_charsets() {
7199 $charsets = array(
7200 'EUC-JP' => 'EUC-JP',
7201 'ISO-2022-JP'=> 'ISO-2022-JP',
7202 'ISO-8859-1' => 'ISO-8859-1',
7203 'SHIFT-JIS' => 'SHIFT-JIS',
7204 'GB2312' => 'GB2312',
7205 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7206 'UTF-8' => 'UTF-8');
7208 asort($charsets);
7210 return $charsets;
7214 * Returns a list of valid and compatible themes
7216 * @return array
7218 function get_list_of_themes() {
7219 global $CFG;
7221 $themes = array();
7223 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7224 $themelist = explode(',', $CFG->themelist);
7225 } else {
7226 $themelist = array_keys(core_component::get_plugin_list("theme"));
7229 foreach ($themelist as $key => $themename) {
7230 $theme = theme_config::load($themename);
7231 $themes[$themename] = $theme;
7234 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7236 return $themes;
7240 * Factory function for emoticon_manager
7242 * @return emoticon_manager singleton
7244 function get_emoticon_manager() {
7245 static $singleton = null;
7247 if (is_null($singleton)) {
7248 $singleton = new emoticon_manager();
7251 return $singleton;
7255 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7257 * Whenever this manager mentiones 'emoticon object', the following data
7258 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7259 * altidentifier and altcomponent
7261 * @see admin_setting_emoticons
7263 * @copyright 2010 David Mudrak
7264 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7266 class emoticon_manager {
7269 * Returns the currently enabled emoticons
7271 * @return array of emoticon objects
7273 public function get_emoticons() {
7274 global $CFG;
7276 if (empty($CFG->emoticons)) {
7277 return array();
7280 $emoticons = $this->decode_stored_config($CFG->emoticons);
7282 if (!is_array($emoticons)) {
7283 // Something is wrong with the format of stored setting.
7284 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7285 return array();
7288 return $emoticons;
7292 * Converts emoticon object into renderable pix_emoticon object
7294 * @param stdClass $emoticon emoticon object
7295 * @param array $attributes explicit HTML attributes to set
7296 * @return pix_emoticon
7298 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7299 $stringmanager = get_string_manager();
7300 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7301 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7302 } else {
7303 $alt = s($emoticon->text);
7305 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7309 * Encodes the array of emoticon objects into a string storable in config table
7311 * @see self::decode_stored_config()
7312 * @param array $emoticons array of emtocion objects
7313 * @return string
7315 public function encode_stored_config(array $emoticons) {
7316 return json_encode($emoticons);
7320 * Decodes the string into an array of emoticon objects
7322 * @see self::encode_stored_config()
7323 * @param string $encoded
7324 * @return string|null
7326 public function decode_stored_config($encoded) {
7327 $decoded = json_decode($encoded);
7328 if (!is_array($decoded)) {
7329 return null;
7331 return $decoded;
7335 * Returns default set of emoticons supported by Moodle
7337 * @return array of sdtClasses
7339 public function default_emoticons() {
7340 return array(
7341 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7342 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7343 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7344 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7345 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7346 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7347 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7348 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7349 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7350 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7351 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7352 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7353 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7354 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7355 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7356 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7357 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7358 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7359 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7360 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7361 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7362 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7363 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7364 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7365 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7366 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7367 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7368 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7369 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7370 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7375 * Helper method preparing the stdClass with the emoticon properties
7377 * @param string|array $text or array of strings
7378 * @param string $imagename to be used by {@link pix_emoticon}
7379 * @param string $altidentifier alternative string identifier, null for no alt
7380 * @param string $altcomponent where the alternative string is defined
7381 * @param string $imagecomponent to be used by {@link pix_emoticon}
7382 * @return stdClass
7384 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7385 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7386 return (object)array(
7387 'text' => $text,
7388 'imagename' => $imagename,
7389 'imagecomponent' => $imagecomponent,
7390 'altidentifier' => $altidentifier,
7391 'altcomponent' => $altcomponent,
7396 // ENCRYPTION.
7399 * rc4encrypt
7401 * @param string $data Data to encrypt.
7402 * @return string The now encrypted data.
7404 function rc4encrypt($data) {
7405 return endecrypt(get_site_identifier(), $data, '');
7409 * rc4decrypt
7411 * @param string $data Data to decrypt.
7412 * @return string The now decrypted data.
7414 function rc4decrypt($data) {
7415 return endecrypt(get_site_identifier(), $data, 'de');
7419 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7421 * @todo Finish documenting this function
7423 * @param string $pwd The password to use when encrypting or decrypting
7424 * @param string $data The data to be decrypted/encrypted
7425 * @param string $case Either 'de' for decrypt or '' for encrypt
7426 * @return string
7428 function endecrypt ($pwd, $data, $case) {
7430 if ($case == 'de') {
7431 $data = urldecode($data);
7434 $key[] = '';
7435 $box[] = '';
7436 $pwdlength = strlen($pwd);
7438 for ($i = 0; $i <= 255; $i++) {
7439 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7440 $box[$i] = $i;
7443 $x = 0;
7445 for ($i = 0; $i <= 255; $i++) {
7446 $x = ($x + $box[$i] + $key[$i]) % 256;
7447 $tempswap = $box[$i];
7448 $box[$i] = $box[$x];
7449 $box[$x] = $tempswap;
7452 $cipher = '';
7454 $a = 0;
7455 $j = 0;
7457 for ($i = 0; $i < strlen($data); $i++) {
7458 $a = ($a + 1) % 256;
7459 $j = ($j + $box[$a]) % 256;
7460 $temp = $box[$a];
7461 $box[$a] = $box[$j];
7462 $box[$j] = $temp;
7463 $k = $box[(($box[$a] + $box[$j]) % 256)];
7464 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7465 $cipher .= chr($cipherby);
7468 if ($case == 'de') {
7469 $cipher = urldecode(urlencode($cipher));
7470 } else {
7471 $cipher = urlencode($cipher);
7474 return $cipher;
7477 // ENVIRONMENT CHECKING.
7480 * This method validates a plug name. It is much faster than calling clean_param.
7482 * @param string $name a string that might be a plugin name.
7483 * @return bool if this string is a valid plugin name.
7485 function is_valid_plugin_name($name) {
7486 // This does not work for 'mod', bad luck, use any other type.
7487 return core_component::is_valid_plugin_name('tool', $name);
7491 * Get a list of all the plugins of a given type that define a certain API function
7492 * in a certain file. The plugin component names and function names are returned.
7494 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7495 * @param string $function the part of the name of the function after the
7496 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7497 * names like report_courselist_hook.
7498 * @param string $file the name of file within the plugin that defines the
7499 * function. Defaults to lib.php.
7500 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7501 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7503 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7504 global $CFG;
7506 // We don't include here as all plugin types files would be included.
7507 $plugins = get_plugins_with_function($function, $file, false);
7509 if (empty($plugins[$plugintype])) {
7510 return array();
7513 $allplugins = core_component::get_plugin_list($plugintype);
7515 // Reformat the array and include the files.
7516 $pluginfunctions = array();
7517 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7519 // Check that it has not been removed and the file is still available.
7520 if (!empty($allplugins[$pluginname])) {
7522 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7523 if (file_exists($filepath)) {
7524 include_once($filepath);
7525 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7530 return $pluginfunctions;
7534 * Get a list of all the plugins that define a certain API function in a certain file.
7536 * @param string $function the part of the name of the function after the
7537 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7538 * names like report_courselist_hook.
7539 * @param string $file the name of file within the plugin that defines the
7540 * function. Defaults to lib.php.
7541 * @param bool $include Whether to include the files that contain the functions or not.
7542 * @return array with [plugintype][plugin] = functionname
7544 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7545 global $CFG;
7547 if (during_initial_install() || isset($CFG->upgraderunning)) {
7548 // API functions _must not_ be called during an installation or upgrade.
7549 return [];
7552 $cache = \cache::make('core', 'plugin_functions');
7554 // Including both although I doubt that we will find two functions definitions with the same name.
7555 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7556 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7557 $pluginfunctions = $cache->get($key);
7559 // Use the plugin manager to check that plugins are currently installed.
7560 $pluginmanager = \core_plugin_manager::instance();
7562 if ($pluginfunctions !== false) {
7564 // Checking that the files are still available.
7565 foreach ($pluginfunctions as $plugintype => $plugins) {
7567 $allplugins = \core_component::get_plugin_list($plugintype);
7568 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7569 foreach ($plugins as $plugin => $function) {
7570 if (!isset($installedplugins[$plugin])) {
7571 // Plugin code is still present on disk but it is not installed.
7572 unset($pluginfunctions[$plugintype][$plugin]);
7573 continue;
7576 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7577 if (empty($allplugins[$plugin])) {
7578 unset($pluginfunctions[$plugintype][$plugin]);
7579 continue;
7582 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7583 if ($include && $fileexists) {
7584 // Include the files if it was requested.
7585 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7586 } else if (!$fileexists) {
7587 // If the file is not available any more it should not be returned.
7588 unset($pluginfunctions[$plugintype][$plugin]);
7592 return $pluginfunctions;
7595 $pluginfunctions = array();
7597 // To fill the cached. Also, everything should continue working with cache disabled.
7598 $plugintypes = \core_component::get_plugin_types();
7599 foreach ($plugintypes as $plugintype => $unused) {
7601 // We need to include files here.
7602 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7603 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7604 foreach ($pluginswithfile as $plugin => $notused) {
7606 if (!isset($installedplugins[$plugin])) {
7607 continue;
7610 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7612 $pluginfunction = false;
7613 if (function_exists($fullfunction)) {
7614 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7615 $pluginfunction = $fullfunction;
7617 } else if ($plugintype === 'mod') {
7618 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7619 $shortfunction = $plugin . '_' . $function;
7620 if (function_exists($shortfunction)) {
7621 $pluginfunction = $shortfunction;
7625 if ($pluginfunction) {
7626 if (empty($pluginfunctions[$plugintype])) {
7627 $pluginfunctions[$plugintype] = array();
7629 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7634 $cache->set($key, $pluginfunctions);
7636 return $pluginfunctions;
7641 * Lists plugin-like directories within specified directory
7643 * This function was originally used for standard Moodle plugins, please use
7644 * new core_component::get_plugin_list() now.
7646 * This function is used for general directory listing and backwards compatility.
7648 * @param string $directory relative directory from root
7649 * @param string $exclude dir name to exclude from the list (defaults to none)
7650 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7651 * @return array Sorted array of directory names found under the requested parameters
7653 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7654 global $CFG;
7656 $plugins = array();
7658 if (empty($basedir)) {
7659 $basedir = $CFG->dirroot .'/'. $directory;
7661 } else {
7662 $basedir = $basedir .'/'. $directory;
7665 if ($CFG->debugdeveloper and empty($exclude)) {
7666 // Make sure devs do not use this to list normal plugins,
7667 // this is intended for general directories that are not plugins!
7669 $subtypes = core_component::get_plugin_types();
7670 if (in_array($basedir, $subtypes)) {
7671 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7673 unset($subtypes);
7676 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7677 if (!$dirhandle = opendir($basedir)) {
7678 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7679 return array();
7681 while (false !== ($dir = readdir($dirhandle))) {
7682 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7683 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7684 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7685 continue;
7687 if (filetype($basedir .'/'. $dir) != 'dir') {
7688 continue;
7690 $plugins[] = $dir;
7692 closedir($dirhandle);
7694 if ($plugins) {
7695 asort($plugins);
7697 return $plugins;
7701 * Invoke plugin's callback functions
7703 * @param string $type plugin type e.g. 'mod'
7704 * @param string $name plugin name
7705 * @param string $feature feature name
7706 * @param string $action feature's action
7707 * @param array $params parameters of callback function, should be an array
7708 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7709 * @return mixed
7711 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7713 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7714 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7718 * Invoke component's callback functions
7720 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7721 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7722 * @param array $params parameters of callback function
7723 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7724 * @return mixed
7726 function component_callback($component, $function, array $params = array(), $default = null) {
7728 $functionname = component_callback_exists($component, $function);
7730 if ($functionname) {
7731 // Function exists, so just return function result.
7732 $ret = call_user_func_array($functionname, $params);
7733 if (is_null($ret)) {
7734 return $default;
7735 } else {
7736 return $ret;
7739 return $default;
7743 * Determine if a component callback exists and return the function name to call. Note that this
7744 * function will include the required library files so that the functioname returned can be
7745 * called directly.
7747 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7748 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7749 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7750 * @throws coding_exception if invalid component specfied
7752 function component_callback_exists($component, $function) {
7753 global $CFG; // This is needed for the inclusions.
7755 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7756 if (empty($cleancomponent)) {
7757 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7759 $component = $cleancomponent;
7761 list($type, $name) = core_component::normalize_component($component);
7762 $component = $type . '_' . $name;
7764 $oldfunction = $name.'_'.$function;
7765 $function = $component.'_'.$function;
7767 $dir = core_component::get_component_directory($component);
7768 if (empty($dir)) {
7769 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7772 // Load library and look for function.
7773 if (file_exists($dir.'/lib.php')) {
7774 require_once($dir.'/lib.php');
7777 if (!function_exists($function) and function_exists($oldfunction)) {
7778 if ($type !== 'mod' and $type !== 'core') {
7779 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7781 $function = $oldfunction;
7784 if (function_exists($function)) {
7785 return $function;
7787 return false;
7791 * Call the specified callback method on the provided class.
7793 * If the callback returns null, then the default value is returned instead.
7794 * If the class does not exist, then the default value is returned.
7796 * @param string $classname The name of the class to call upon.
7797 * @param string $methodname The name of the staticically defined method on the class.
7798 * @param array $params The arguments to pass into the method.
7799 * @param mixed $default The default value.
7800 * @return mixed The return value.
7802 function component_class_callback($classname, $methodname, array $params, $default = null) {
7803 if (!class_exists($classname)) {
7804 return $default;
7807 if (!method_exists($classname, $methodname)) {
7808 return $default;
7811 $fullfunction = $classname . '::' . $methodname;
7812 $result = call_user_func_array($fullfunction, $params);
7814 if (null === $result) {
7815 return $default;
7816 } else {
7817 return $result;
7822 * Checks whether a plugin supports a specified feature.
7824 * @param string $type Plugin type e.g. 'mod'
7825 * @param string $name Plugin name e.g. 'forum'
7826 * @param string $feature Feature code (FEATURE_xx constant)
7827 * @param mixed $default default value if feature support unknown
7828 * @return mixed Feature result (false if not supported, null if feature is unknown,
7829 * otherwise usually true but may have other feature-specific value such as array)
7830 * @throws coding_exception
7832 function plugin_supports($type, $name, $feature, $default = null) {
7833 global $CFG;
7835 if ($type === 'mod' and $name === 'NEWMODULE') {
7836 // Somebody forgot to rename the module template.
7837 return false;
7840 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7841 if (empty($component)) {
7842 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7845 $function = null;
7847 if ($type === 'mod') {
7848 // We need this special case because we support subplugins in modules,
7849 // otherwise it would end up in infinite loop.
7850 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7851 include_once("$CFG->dirroot/mod/$name/lib.php");
7852 $function = $component.'_supports';
7853 if (!function_exists($function)) {
7854 // Legacy non-frankenstyle function name.
7855 $function = $name.'_supports';
7859 } else {
7860 if (!$path = core_component::get_plugin_directory($type, $name)) {
7861 // Non existent plugin type.
7862 return false;
7864 if (file_exists("$path/lib.php")) {
7865 include_once("$path/lib.php");
7866 $function = $component.'_supports';
7870 if ($function and function_exists($function)) {
7871 $supports = $function($feature);
7872 if (is_null($supports)) {
7873 // Plugin does not know - use default.
7874 return $default;
7875 } else {
7876 return $supports;
7880 // Plugin does not care, so use default.
7881 return $default;
7885 * Returns true if the current version of PHP is greater that the specified one.
7887 * @todo Check PHP version being required here is it too low?
7889 * @param string $version The version of php being tested.
7890 * @return bool
7892 function check_php_version($version='5.2.4') {
7893 return (version_compare(phpversion(), $version) >= 0);
7897 * Determine if moodle installation requires update.
7899 * Checks version numbers of main code and all plugins to see
7900 * if there are any mismatches.
7902 * @return bool
7904 function moodle_needs_upgrading() {
7905 global $CFG;
7907 if (empty($CFG->version)) {
7908 return true;
7911 // There is no need to purge plugininfo caches here because
7912 // these caches are not used during upgrade and they are purged after
7913 // every upgrade.
7915 if (empty($CFG->allversionshash)) {
7916 return true;
7919 $hash = core_component::get_all_versions_hash();
7921 return ($hash !== $CFG->allversionshash);
7925 * Returns the major version of this site
7927 * Moodle version numbers consist of three numbers separated by a dot, for
7928 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7929 * called major version. This function extracts the major version from either
7930 * $CFG->release (default) or eventually from the $release variable defined in
7931 * the main version.php.
7933 * @param bool $fromdisk should the version if source code files be used
7934 * @return string|false the major version like '2.3', false if could not be determined
7936 function moodle_major_version($fromdisk = false) {
7937 global $CFG;
7939 if ($fromdisk) {
7940 $release = null;
7941 require($CFG->dirroot.'/version.php');
7942 if (empty($release)) {
7943 return false;
7946 } else {
7947 if (empty($CFG->release)) {
7948 return false;
7950 $release = $CFG->release;
7953 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7954 return $matches[0];
7955 } else {
7956 return false;
7960 // MISCELLANEOUS.
7963 * Sets the system locale
7965 * @category string
7966 * @param string $locale Can be used to force a locale
7968 function moodle_setlocale($locale='') {
7969 global $CFG;
7971 static $currentlocale = ''; // Last locale caching.
7973 $oldlocale = $currentlocale;
7975 // Fetch the correct locale based on ostype.
7976 if ($CFG->ostype == 'WINDOWS') {
7977 $stringtofetch = 'localewin';
7978 } else {
7979 $stringtofetch = 'locale';
7982 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7983 if (!empty($locale)) {
7984 $currentlocale = $locale;
7985 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7986 $currentlocale = $CFG->locale;
7987 } else {
7988 $currentlocale = get_string($stringtofetch, 'langconfig');
7991 // Do nothing if locale already set up.
7992 if ($oldlocale == $currentlocale) {
7993 return;
7996 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7997 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7998 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8000 // Get current values.
8001 $monetary= setlocale (LC_MONETARY, 0);
8002 $numeric = setlocale (LC_NUMERIC, 0);
8003 $ctype = setlocale (LC_CTYPE, 0);
8004 if ($CFG->ostype != 'WINDOWS') {
8005 $messages= setlocale (LC_MESSAGES, 0);
8007 // Set locale to all.
8008 $result = setlocale (LC_ALL, $currentlocale);
8009 // If setting of locale fails try the other utf8 or utf-8 variant,
8010 // some operating systems support both (Debian), others just one (OSX).
8011 if ($result === false) {
8012 if (stripos($currentlocale, '.UTF-8') !== false) {
8013 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8014 setlocale (LC_ALL, $newlocale);
8015 } else if (stripos($currentlocale, '.UTF8') !== false) {
8016 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8017 setlocale (LC_ALL, $newlocale);
8020 // Set old values.
8021 setlocale (LC_MONETARY, $monetary);
8022 setlocale (LC_NUMERIC, $numeric);
8023 if ($CFG->ostype != 'WINDOWS') {
8024 setlocale (LC_MESSAGES, $messages);
8026 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8027 // To workaround a well-known PHP problem with Turkish letter Ii.
8028 setlocale (LC_CTYPE, $ctype);
8033 * Count words in a string.
8035 * Words are defined as things between whitespace.
8037 * @category string
8038 * @param string $string The text to be searched for words.
8039 * @return int The count of words in the specified string
8041 function count_words($string) {
8042 $string = strip_tags($string);
8043 // Decode HTML entities.
8044 $string = html_entity_decode($string);
8045 // Replace underscores (which are classed as word characters) with spaces.
8046 $string = preg_replace('/_/u', ' ', $string);
8047 // Remove any characters that shouldn't be treated as word boundaries.
8048 $string = preg_replace('/[\'"’-]/u', '', $string);
8049 // Remove dots and commas from within numbers only.
8050 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
8052 return count(preg_split('/\w\b/u', $string)) - 1;
8056 * Count letters in a string.
8058 * Letters are defined as chars not in tags and different from whitespace.
8060 * @category string
8061 * @param string $string The text to be searched for letters.
8062 * @return int The count of letters in the specified text.
8064 function count_letters($string) {
8065 $string = strip_tags($string); // Tags are out now.
8066 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8068 return core_text::strlen($string);
8072 * Generate and return a random string of the specified length.
8074 * @param int $length The length of the string to be created.
8075 * @return string
8077 function random_string($length=15) {
8078 $randombytes = random_bytes_emulate($length);
8079 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8080 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8081 $pool .= '0123456789';
8082 $poollen = strlen($pool);
8083 $string = '';
8084 for ($i = 0; $i < $length; $i++) {
8085 $rand = ord($randombytes[$i]);
8086 $string .= substr($pool, ($rand%($poollen)), 1);
8088 return $string;
8092 * Generate a complex random string (useful for md5 salts)
8094 * This function is based on the above {@link random_string()} however it uses a
8095 * larger pool of characters and generates a string between 24 and 32 characters
8097 * @param int $length Optional if set generates a string to exactly this length
8098 * @return string
8100 function complex_random_string($length=null) {
8101 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8102 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8103 $poollen = strlen($pool);
8104 if ($length===null) {
8105 $length = floor(rand(24, 32));
8107 $randombytes = random_bytes_emulate($length);
8108 $string = '';
8109 for ($i = 0; $i < $length; $i++) {
8110 $rand = ord($randombytes[$i]);
8111 $string .= $pool[($rand%$poollen)];
8113 return $string;
8117 * Try to generates cryptographically secure pseudo-random bytes.
8119 * Note this is achieved by fallbacking between:
8120 * - PHP 7 random_bytes().
8121 * - OpenSSL openssl_random_pseudo_bytes().
8122 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8124 * @param int $length requested length in bytes
8125 * @return string binary data
8127 function random_bytes_emulate($length) {
8128 global $CFG;
8129 if ($length <= 0) {
8130 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8131 return '';
8133 if (function_exists('random_bytes')) {
8134 // Use PHP 7 goodness.
8135 $hash = @random_bytes($length);
8136 if ($hash !== false) {
8137 return $hash;
8140 if (function_exists('openssl_random_pseudo_bytes')) {
8141 // If you have the openssl extension enabled.
8142 $hash = openssl_random_pseudo_bytes($length);
8143 if ($hash !== false) {
8144 return $hash;
8148 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8149 $staticdata = serialize($CFG) . serialize($_SERVER);
8150 $hash = '';
8151 do {
8152 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8153 } while (strlen($hash) < $length);
8155 return substr($hash, 0, $length);
8159 * Given some text (which may contain HTML) and an ideal length,
8160 * this function truncates the text neatly on a word boundary if possible
8162 * @category string
8163 * @param string $text text to be shortened
8164 * @param int $ideal ideal string length
8165 * @param boolean $exact if false, $text will not be cut mid-word
8166 * @param string $ending The string to append if the passed string is truncated
8167 * @return string $truncate shortened string
8169 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8170 // If the plain text is shorter than the maximum length, return the whole text.
8171 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8172 return $text;
8175 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8176 // and only tag in its 'line'.
8177 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8179 $totallength = core_text::strlen($ending);
8180 $truncate = '';
8182 // This array stores information about open and close tags and their position
8183 // in the truncated string. Each item in the array is an object with fields
8184 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8185 // (byte position in truncated text).
8186 $tagdetails = array();
8188 foreach ($lines as $linematchings) {
8189 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8190 if (!empty($linematchings[1])) {
8191 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8192 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8193 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8194 // Record closing tag.
8195 $tagdetails[] = (object) array(
8196 'open' => false,
8197 'tag' => core_text::strtolower($tagmatchings[1]),
8198 'pos' => core_text::strlen($truncate),
8201 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8202 // Record opening tag.
8203 $tagdetails[] = (object) array(
8204 'open' => true,
8205 'tag' => core_text::strtolower($tagmatchings[1]),
8206 'pos' => core_text::strlen($truncate),
8208 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8209 $tagdetails[] = (object) array(
8210 'open' => true,
8211 'tag' => core_text::strtolower('if'),
8212 'pos' => core_text::strlen($truncate),
8214 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8215 $tagdetails[] = (object) array(
8216 'open' => false,
8217 'tag' => core_text::strtolower('if'),
8218 'pos' => core_text::strlen($truncate),
8222 // Add html-tag to $truncate'd text.
8223 $truncate .= $linematchings[1];
8226 // Calculate the length of the plain text part of the line; handle entities as one character.
8227 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8228 if ($totallength + $contentlength > $ideal) {
8229 // The number of characters which are left.
8230 $left = $ideal - $totallength;
8231 $entitieslength = 0;
8232 // Search for html entities.
8233 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)) {
8234 // Calculate the real length of all entities in the legal range.
8235 foreach ($entities[0] as $entity) {
8236 if ($entity[1]+1-$entitieslength <= $left) {
8237 $left--;
8238 $entitieslength += core_text::strlen($entity[0]);
8239 } else {
8240 // No more characters left.
8241 break;
8245 $breakpos = $left + $entitieslength;
8247 // If the words shouldn't be cut in the middle...
8248 if (!$exact) {
8249 // Search the last occurence of a space.
8250 for (; $breakpos > 0; $breakpos--) {
8251 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8252 if ($char === '.' or $char === ' ') {
8253 $breakpos += 1;
8254 break;
8255 } else if (strlen($char) > 2) {
8256 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8257 $breakpos += 1;
8258 break;
8263 if ($breakpos == 0) {
8264 // This deals with the test_shorten_text_no_spaces case.
8265 $breakpos = $left + $entitieslength;
8266 } else if ($breakpos > $left + $entitieslength) {
8267 // This deals with the previous for loop breaking on the first char.
8268 $breakpos = $left + $entitieslength;
8271 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8272 // Maximum length is reached, so get off the loop.
8273 break;
8274 } else {
8275 $truncate .= $linematchings[2];
8276 $totallength += $contentlength;
8279 // If the maximum length is reached, get off the loop.
8280 if ($totallength >= $ideal) {
8281 break;
8285 // Add the defined ending to the text.
8286 $truncate .= $ending;
8288 // Now calculate the list of open html tags based on the truncate position.
8289 $opentags = array();
8290 foreach ($tagdetails as $taginfo) {
8291 if ($taginfo->open) {
8292 // Add tag to the beginning of $opentags list.
8293 array_unshift($opentags, $taginfo->tag);
8294 } else {
8295 // Can have multiple exact same open tags, close the last one.
8296 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8297 if ($pos !== false) {
8298 unset($opentags[$pos]);
8303 // Close all unclosed html-tags.
8304 foreach ($opentags as $tag) {
8305 if ($tag === 'if') {
8306 $truncate .= '<!--<![endif]-->';
8307 } else {
8308 $truncate .= '</' . $tag . '>';
8312 return $truncate;
8316 * Shortens a given filename by removing characters positioned after the ideal string length.
8317 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8318 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8320 * @param string $filename file name
8321 * @param int $length ideal string length
8322 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8323 * @return string $shortened shortened file name
8325 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8326 $shortened = $filename;
8327 // Extract a part of the filename if it's char size exceeds the ideal string length.
8328 if (core_text::strlen($filename) > $length) {
8329 // Exclude extension if present in filename.
8330 $mimetypes = get_mimetypes_array();
8331 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8332 if ($extension && !empty($mimetypes[$extension])) {
8333 $basename = pathinfo($filename, PATHINFO_FILENAME);
8334 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8335 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8336 $shortened .= '.' . $extension;
8337 } else {
8338 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8339 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8342 return $shortened;
8346 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8348 * @param array $path The paths to reduce the length.
8349 * @param int $length Ideal string length
8350 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8351 * @return array $result Shortened paths in array.
8353 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8354 $result = null;
8356 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8357 $carry[] = shorten_filename($singlepath, $length, $includehash);
8358 return $carry;
8359 }, []);
8361 return $result;
8365 * Given dates in seconds, how many weeks is the date from startdate
8366 * The first week is 1, the second 2 etc ...
8368 * @param int $startdate Timestamp for the start date
8369 * @param int $thedate Timestamp for the end date
8370 * @return string
8372 function getweek ($startdate, $thedate) {
8373 if ($thedate < $startdate) {
8374 return 0;
8377 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8381 * Returns a randomly generated password of length $maxlen. inspired by
8383 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8384 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8386 * @param int $maxlen The maximum size of the password being generated.
8387 * @return string
8389 function generate_password($maxlen=10) {
8390 global $CFG;
8392 if (empty($CFG->passwordpolicy)) {
8393 $fillers = PASSWORD_DIGITS;
8394 $wordlist = file($CFG->wordlist);
8395 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8396 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8397 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8398 $password = $word1 . $filler1 . $word2;
8399 } else {
8400 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8401 $digits = $CFG->minpassworddigits;
8402 $lower = $CFG->minpasswordlower;
8403 $upper = $CFG->minpasswordupper;
8404 $nonalphanum = $CFG->minpasswordnonalphanum;
8405 $total = $lower + $upper + $digits + $nonalphanum;
8406 // Var minlength should be the greater one of the two ( $minlen and $total ).
8407 $minlen = $minlen < $total ? $total : $minlen;
8408 // Var maxlen can never be smaller than minlen.
8409 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8410 $additional = $maxlen - $total;
8412 // Make sure we have enough characters to fulfill
8413 // complexity requirements.
8414 $passworddigits = PASSWORD_DIGITS;
8415 while ($digits > strlen($passworddigits)) {
8416 $passworddigits .= PASSWORD_DIGITS;
8418 $passwordlower = PASSWORD_LOWER;
8419 while ($lower > strlen($passwordlower)) {
8420 $passwordlower .= PASSWORD_LOWER;
8422 $passwordupper = PASSWORD_UPPER;
8423 while ($upper > strlen($passwordupper)) {
8424 $passwordupper .= PASSWORD_UPPER;
8426 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8427 while ($nonalphanum > strlen($passwordnonalphanum)) {
8428 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8431 // Now mix and shuffle it all.
8432 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8433 substr(str_shuffle ($passwordupper), 0, $upper) .
8434 substr(str_shuffle ($passworddigits), 0, $digits) .
8435 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8436 substr(str_shuffle ($passwordlower .
8437 $passwordupper .
8438 $passworddigits .
8439 $passwordnonalphanum), 0 , $additional));
8442 return substr ($password, 0, $maxlen);
8446 * Given a float, prints it nicely.
8447 * Localized floats must not be used in calculations!
8449 * The stripzeros feature is intended for making numbers look nicer in small
8450 * areas where it is not necessary to indicate the degree of accuracy by showing
8451 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8452 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8454 * @param float $float The float to print
8455 * @param int $decimalpoints The number of decimal places to print.
8456 * @param bool $localized use localized decimal separator
8457 * @param bool $stripzeros If true, removes final zeros after decimal point
8458 * @return string locale float
8460 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8461 if (is_null($float)) {
8462 return '';
8464 if ($localized) {
8465 $separator = get_string('decsep', 'langconfig');
8466 } else {
8467 $separator = '.';
8469 $result = number_format($float, $decimalpoints, $separator, '');
8470 if ($stripzeros) {
8471 // Remove zeros and final dot if not needed.
8472 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8474 return $result;
8478 * Converts locale specific floating point/comma number back to standard PHP float value
8479 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8481 * @param string $localefloat locale aware float representation
8482 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8483 * @return mixed float|bool - false or the parsed float.
8485 function unformat_float($localefloat, $strict = false) {
8486 $localefloat = trim($localefloat);
8488 if ($localefloat == '') {
8489 return null;
8492 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8493 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8495 if ($strict && !is_numeric($localefloat)) {
8496 return false;
8499 return (float)$localefloat;
8503 * Given a simple array, this shuffles it up just like shuffle()
8504 * Unlike PHP's shuffle() this function works on any machine.
8506 * @param array $array The array to be rearranged
8507 * @return array
8509 function swapshuffle($array) {
8511 $last = count($array) - 1;
8512 for ($i = 0; $i <= $last; $i++) {
8513 $from = rand(0, $last);
8514 $curr = $array[$i];
8515 $array[$i] = $array[$from];
8516 $array[$from] = $curr;
8518 return $array;
8522 * Like {@link swapshuffle()}, but works on associative arrays
8524 * @param array $array The associative array to be rearranged
8525 * @return array
8527 function swapshuffle_assoc($array) {
8529 $newarray = array();
8530 $newkeys = swapshuffle(array_keys($array));
8532 foreach ($newkeys as $newkey) {
8533 $newarray[$newkey] = $array[$newkey];
8535 return $newarray;
8539 * Given an arbitrary array, and a number of draws,
8540 * this function returns an array with that amount
8541 * of items. The indexes are retained.
8543 * @todo Finish documenting this function
8545 * @param array $array
8546 * @param int $draws
8547 * @return array
8549 function draw_rand_array($array, $draws) {
8551 $return = array();
8553 $last = count($array);
8555 if ($draws > $last) {
8556 $draws = $last;
8559 while ($draws > 0) {
8560 $last--;
8562 $keys = array_keys($array);
8563 $rand = rand(0, $last);
8565 $return[$keys[$rand]] = $array[$keys[$rand]];
8566 unset($array[$keys[$rand]]);
8568 $draws--;
8571 return $return;
8575 * Calculate the difference between two microtimes
8577 * @param string $a The first Microtime
8578 * @param string $b The second Microtime
8579 * @return string
8581 function microtime_diff($a, $b) {
8582 list($adec, $asec) = explode(' ', $a);
8583 list($bdec, $bsec) = explode(' ', $b);
8584 return $bsec - $asec + $bdec - $adec;
8588 * Given a list (eg a,b,c,d,e) this function returns
8589 * an array of 1->a, 2->b, 3->c etc
8591 * @param string $list The string to explode into array bits
8592 * @param string $separator The separator used within the list string
8593 * @return array The now assembled array
8595 function make_menu_from_list($list, $separator=',') {
8597 $array = array_reverse(explode($separator, $list), true);
8598 foreach ($array as $key => $item) {
8599 $outarray[$key+1] = trim($item);
8601 return $outarray;
8605 * Creates an array that represents all the current grades that
8606 * can be chosen using the given grading type.
8608 * Negative numbers
8609 * are scales, zero is no grade, and positive numbers are maximum
8610 * grades.
8612 * @todo Finish documenting this function or better deprecated this completely!
8614 * @param int $gradingtype
8615 * @return array
8617 function make_grades_menu($gradingtype) {
8618 global $DB;
8620 $grades = array();
8621 if ($gradingtype < 0) {
8622 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8623 return make_menu_from_list($scale->scale);
8625 } else if ($gradingtype > 0) {
8626 for ($i=$gradingtype; $i>=0; $i--) {
8627 $grades[$i] = $i .' / '. $gradingtype;
8629 return $grades;
8631 return $grades;
8635 * make_unique_id_code
8637 * @todo Finish documenting this function
8639 * @uses $_SERVER
8640 * @param string $extra Extra string to append to the end of the code
8641 * @return string
8643 function make_unique_id_code($extra = '') {
8645 $hostname = 'unknownhost';
8646 if (!empty($_SERVER['HTTP_HOST'])) {
8647 $hostname = $_SERVER['HTTP_HOST'];
8648 } else if (!empty($_ENV['HTTP_HOST'])) {
8649 $hostname = $_ENV['HTTP_HOST'];
8650 } else if (!empty($_SERVER['SERVER_NAME'])) {
8651 $hostname = $_SERVER['SERVER_NAME'];
8652 } else if (!empty($_ENV['SERVER_NAME'])) {
8653 $hostname = $_ENV['SERVER_NAME'];
8656 $date = gmdate("ymdHis");
8658 $random = random_string(6);
8660 if ($extra) {
8661 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8662 } else {
8663 return $hostname .'+'. $date .'+'. $random;
8669 * Function to check the passed address is within the passed subnet
8671 * The parameter is a comma separated string of subnet definitions.
8672 * Subnet strings can be in one of three formats:
8673 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8674 * 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)
8675 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8676 * Code for type 1 modified from user posted comments by mediator at
8677 * {@link http://au.php.net/manual/en/function.ip2long.php}
8679 * @param string $addr The address you are checking
8680 * @param string $subnetstr The string of subnet addresses
8681 * @return bool
8683 function address_in_subnet($addr, $subnetstr) {
8685 if ($addr == '0.0.0.0') {
8686 return false;
8688 $subnets = explode(',', $subnetstr);
8689 $found = false;
8690 $addr = trim($addr);
8691 $addr = cleanremoteaddr($addr, false); // Normalise.
8692 if ($addr === null) {
8693 return false;
8695 $addrparts = explode(':', $addr);
8697 $ipv6 = strpos($addr, ':');
8699 foreach ($subnets as $subnet) {
8700 $subnet = trim($subnet);
8701 if ($subnet === '') {
8702 continue;
8705 if (strpos($subnet, '/') !== false) {
8706 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8707 list($ip, $mask) = explode('/', $subnet);
8708 $mask = trim($mask);
8709 if (!is_number($mask)) {
8710 continue; // Incorect mask number, eh?
8712 $ip = cleanremoteaddr($ip, false); // Normalise.
8713 if ($ip === null) {
8714 continue;
8716 if (strpos($ip, ':') !== false) {
8717 // IPv6.
8718 if (!$ipv6) {
8719 continue;
8721 if ($mask > 128 or $mask < 0) {
8722 continue; // Nonsense.
8724 if ($mask == 0) {
8725 return true; // Any address.
8727 if ($mask == 128) {
8728 if ($ip === $addr) {
8729 return true;
8731 continue;
8733 $ipparts = explode(':', $ip);
8734 $modulo = $mask % 16;
8735 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8736 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8737 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8738 if ($modulo == 0) {
8739 return true;
8741 $pos = ($mask-$modulo)/16;
8742 $ipnet = hexdec($ipparts[$pos]);
8743 $addrnet = hexdec($addrparts[$pos]);
8744 $mask = 0xffff << (16 - $modulo);
8745 if (($addrnet & $mask) == ($ipnet & $mask)) {
8746 return true;
8750 } else {
8751 // IPv4.
8752 if ($ipv6) {
8753 continue;
8755 if ($mask > 32 or $mask < 0) {
8756 continue; // Nonsense.
8758 if ($mask == 0) {
8759 return true;
8761 if ($mask == 32) {
8762 if ($ip === $addr) {
8763 return true;
8765 continue;
8767 $mask = 0xffffffff << (32 - $mask);
8768 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8769 return true;
8773 } else if (strpos($subnet, '-') !== false) {
8774 // 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.
8775 $parts = explode('-', $subnet);
8776 if (count($parts) != 2) {
8777 continue;
8780 if (strpos($subnet, ':') !== false) {
8781 // IPv6.
8782 if (!$ipv6) {
8783 continue;
8785 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8786 if ($ipstart === null) {
8787 continue;
8789 $ipparts = explode(':', $ipstart);
8790 $start = hexdec(array_pop($ipparts));
8791 $ipparts[] = trim($parts[1]);
8792 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8793 if ($ipend === null) {
8794 continue;
8796 $ipparts[7] = '';
8797 $ipnet = implode(':', $ipparts);
8798 if (strpos($addr, $ipnet) !== 0) {
8799 continue;
8801 $ipparts = explode(':', $ipend);
8802 $end = hexdec($ipparts[7]);
8804 $addrend = hexdec($addrparts[7]);
8806 if (($addrend >= $start) and ($addrend <= $end)) {
8807 return true;
8810 } else {
8811 // IPv4.
8812 if ($ipv6) {
8813 continue;
8815 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8816 if ($ipstart === null) {
8817 continue;
8819 $ipparts = explode('.', $ipstart);
8820 $ipparts[3] = trim($parts[1]);
8821 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8822 if ($ipend === null) {
8823 continue;
8826 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8827 return true;
8831 } else {
8832 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8833 if (strpos($subnet, ':') !== false) {
8834 // IPv6.
8835 if (!$ipv6) {
8836 continue;
8838 $parts = explode(':', $subnet);
8839 $count = count($parts);
8840 if ($parts[$count-1] === '') {
8841 unset($parts[$count-1]); // Trim trailing :'s.
8842 $count--;
8843 $subnet = implode('.', $parts);
8845 $isip = cleanremoteaddr($subnet, false); // Normalise.
8846 if ($isip !== null) {
8847 if ($isip === $addr) {
8848 return true;
8850 continue;
8851 } else if ($count > 8) {
8852 continue;
8854 $zeros = array_fill(0, 8-$count, '0');
8855 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8856 if (address_in_subnet($addr, $subnet)) {
8857 return true;
8860 } else {
8861 // IPv4.
8862 if ($ipv6) {
8863 continue;
8865 $parts = explode('.', $subnet);
8866 $count = count($parts);
8867 if ($parts[$count-1] === '') {
8868 unset($parts[$count-1]); // Trim trailing .
8869 $count--;
8870 $subnet = implode('.', $parts);
8872 if ($count == 4) {
8873 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8874 if ($subnet === $addr) {
8875 return true;
8877 continue;
8878 } else if ($count > 4) {
8879 continue;
8881 $zeros = array_fill(0, 4-$count, '0');
8882 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8883 if (address_in_subnet($addr, $subnet)) {
8884 return true;
8890 return false;
8894 * For outputting debugging info
8896 * @param string $string The string to write
8897 * @param string $eol The end of line char(s) to use
8898 * @param string $sleep Period to make the application sleep
8899 * This ensures any messages have time to display before redirect
8901 function mtrace($string, $eol="\n", $sleep=0) {
8902 global $CFG;
8904 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
8905 $fn = $CFG->mtrace_wrapper;
8906 $fn($string, $eol);
8907 return;
8908 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
8909 fwrite(STDOUT, $string.$eol);
8910 } else {
8911 echo $string . $eol;
8914 flush();
8916 // Delay to keep message on user's screen in case of subsequent redirect.
8917 if ($sleep) {
8918 sleep($sleep);
8923 * Replace 1 or more slashes or backslashes to 1 slash
8925 * @param string $path The path to strip
8926 * @return string the path with double slashes removed
8928 function cleardoubleslashes ($path) {
8929 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8933 * Is the current ip in a given list?
8935 * @param string $list
8936 * @return bool
8938 function remoteip_in_list($list) {
8939 $inlist = false;
8940 $clientip = getremoteaddr(null);
8942 if (!$clientip) {
8943 // Ensure access on cli.
8944 return true;
8947 $list = explode("\n", $list);
8948 foreach ($list as $line) {
8949 $tokens = explode('#', $line);
8950 $subnet = trim($tokens[0]);
8951 if (address_in_subnet($clientip, $subnet)) {
8952 $inlist = true;
8953 break;
8956 return $inlist;
8960 * Returns most reliable client address
8962 * @param string $default If an address can't be determined, then return this
8963 * @return string The remote IP address
8965 function getremoteaddr($default='0.0.0.0') {
8966 global $CFG;
8968 if (empty($CFG->getremoteaddrconf)) {
8969 // This will happen, for example, before just after the upgrade, as the
8970 // user is redirected to the admin screen.
8971 $variablestoskip = 0;
8972 } else {
8973 $variablestoskip = $CFG->getremoteaddrconf;
8975 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8976 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8977 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8978 return $address ? $address : $default;
8981 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8982 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8983 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8984 $address = $forwardedaddresses[0];
8986 if (substr_count($address, ":") > 1) {
8987 // Remove port and brackets from IPv6.
8988 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8989 $address = $matches[1];
8991 } else {
8992 // Remove port from IPv4.
8993 if (substr_count($address, ":") == 1) {
8994 $parts = explode(":", $address);
8995 $address = $parts[0];
8999 $address = cleanremoteaddr($address);
9000 return $address ? $address : $default;
9003 if (!empty($_SERVER['REMOTE_ADDR'])) {
9004 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9005 return $address ? $address : $default;
9006 } else {
9007 return $default;
9012 * Cleans an ip address. Internal addresses are now allowed.
9013 * (Originally local addresses were not allowed.)
9015 * @param string $addr IPv4 or IPv6 address
9016 * @param bool $compress use IPv6 address compression
9017 * @return string normalised ip address string, null if error
9019 function cleanremoteaddr($addr, $compress=false) {
9020 $addr = trim($addr);
9022 if (strpos($addr, ':') !== false) {
9023 // Can be only IPv6.
9024 $parts = explode(':', $addr);
9025 $count = count($parts);
9027 if (strpos($parts[$count-1], '.') !== false) {
9028 // Legacy ipv4 notation.
9029 $last = array_pop($parts);
9030 $ipv4 = cleanremoteaddr($last, true);
9031 if ($ipv4 === null) {
9032 return null;
9034 $bits = explode('.', $ipv4);
9035 $parts[] = dechex($bits[0]).dechex($bits[1]);
9036 $parts[] = dechex($bits[2]).dechex($bits[3]);
9037 $count = count($parts);
9038 $addr = implode(':', $parts);
9041 if ($count < 3 or $count > 8) {
9042 return null; // Severly malformed.
9045 if ($count != 8) {
9046 if (strpos($addr, '::') === false) {
9047 return null; // Malformed.
9049 // Uncompress.
9050 $insertat = array_search('', $parts, true);
9051 $missing = array_fill(0, 1 + 8 - $count, '0');
9052 array_splice($parts, $insertat, 1, $missing);
9053 foreach ($parts as $key => $part) {
9054 if ($part === '') {
9055 $parts[$key] = '0';
9060 $adr = implode(':', $parts);
9061 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9062 return null; // Incorrect format - sorry.
9065 // Normalise 0s and case.
9066 $parts = array_map('hexdec', $parts);
9067 $parts = array_map('dechex', $parts);
9069 $result = implode(':', $parts);
9071 if (!$compress) {
9072 return $result;
9075 if ($result === '0:0:0:0:0:0:0:0') {
9076 return '::'; // All addresses.
9079 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9080 if ($compressed !== $result) {
9081 return $compressed;
9084 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9085 if ($compressed !== $result) {
9086 return $compressed;
9089 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9090 if ($compressed !== $result) {
9091 return $compressed;
9094 return $result;
9097 // First get all things that look like IPv4 addresses.
9098 $parts = array();
9099 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9100 return null;
9102 unset($parts[0]);
9104 foreach ($parts as $key => $match) {
9105 if ($match > 255) {
9106 return null;
9108 $parts[$key] = (int)$match; // Normalise 0s.
9111 return implode('.', $parts);
9116 * Is IP address a public address?
9118 * @param string $ip The ip to check
9119 * @return bool true if the ip is public
9121 function ip_is_public($ip) {
9122 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9126 * This function will make a complete copy of anything it's given,
9127 * regardless of whether it's an object or not.
9129 * @param mixed $thing Something you want cloned
9130 * @return mixed What ever it is you passed it
9132 function fullclone($thing) {
9133 return unserialize(serialize($thing));
9137 * Used to make sure that $min <= $value <= $max
9139 * Make sure that value is between min, and max
9141 * @param int $min The minimum value
9142 * @param int $value The value to check
9143 * @param int $max The maximum value
9144 * @return int
9146 function bounded_number($min, $value, $max) {
9147 if ($value < $min) {
9148 return $min;
9150 if ($value > $max) {
9151 return $max;
9153 return $value;
9157 * Check if there is a nested array within the passed array
9159 * @param array $array
9160 * @return bool true if there is a nested array false otherwise
9162 function array_is_nested($array) {
9163 foreach ($array as $value) {
9164 if (is_array($value)) {
9165 return true;
9168 return false;
9172 * get_performance_info() pairs up with init_performance_info()
9173 * loaded in setup.php. Returns an array with 'html' and 'txt'
9174 * values ready for use, and each of the individual stats provided
9175 * separately as well.
9177 * @return array
9179 function get_performance_info() {
9180 global $CFG, $PERF, $DB, $PAGE;
9182 $info = array();
9183 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9185 $info['html'] = '';
9186 if (!empty($CFG->themedesignermode)) {
9187 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9188 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9190 $info['html'] .= '<ul class="list-unstyled m-l-1 row">'; // Holds userfriendly HTML representation.
9192 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9194 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9195 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9197 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9198 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9200 if (function_exists('memory_get_usage')) {
9201 $info['memory_total'] = memory_get_usage();
9202 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9203 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9204 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9205 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9208 if (function_exists('memory_get_peak_usage')) {
9209 $info['memory_peak'] = memory_get_peak_usage();
9210 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9211 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9214 $info['html'] .= '</ul><ul class="list-unstyled m-l-1 row">';
9215 $inc = get_included_files();
9216 $info['includecount'] = count($inc);
9217 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9218 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9220 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9221 // We can not track more performance before installation or before PAGE init, sorry.
9222 return $info;
9225 $filtermanager = filter_manager::instance();
9226 if (method_exists($filtermanager, 'get_performance_summary')) {
9227 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9228 $info = array_merge($filterinfo, $info);
9229 foreach ($filterinfo as $key => $value) {
9230 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9231 $info['txt'] .= "$key: $value ";
9235 $stringmanager = get_string_manager();
9236 if (method_exists($stringmanager, 'get_performance_summary')) {
9237 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9238 $info = array_merge($filterinfo, $info);
9239 foreach ($filterinfo as $key => $value) {
9240 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9241 $info['txt'] .= "$key: $value ";
9245 if (!empty($PERF->logwrites)) {
9246 $info['logwrites'] = $PERF->logwrites;
9247 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9248 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9251 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9252 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9253 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9255 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9256 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9257 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9259 if (function_exists('posix_times')) {
9260 $ptimes = posix_times();
9261 if (is_array($ptimes)) {
9262 foreach ($ptimes as $key => $val) {
9263 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9265 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9266 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9267 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9271 // Grab the load average for the last minute.
9272 // /proc will only work under some linux configurations
9273 // while uptime is there under MacOSX/Darwin and other unices.
9274 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9275 list($serverload) = explode(' ', $loadavg[0]);
9276 unset($loadavg);
9277 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9278 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9279 $serverload = $matches[1];
9280 } else {
9281 trigger_error('Could not parse uptime output!');
9284 if (!empty($serverload)) {
9285 $info['serverload'] = $serverload;
9286 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9287 $info['txt'] .= "serverload: {$info['serverload']} ";
9290 // Display size of session if session started.
9291 if ($si = \core\session\manager::get_performance_info()) {
9292 $info['sessionsize'] = $si['size'];
9293 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9294 $info['txt'] .= $si['txt'];
9297 $info['html'] .= '</ul>';
9298 if ($stats = cache_helper::get_stats()) {
9299 $html = '<ul class="cachesused list-unstyled m-l-1 row">';
9300 $html .= '<li class="cache-stats-heading font-weight-bold">Caches used (hits/misses/sets)</li>';
9301 $html .= '</ul><ul class="cachesused list-unstyled m-l-1">';
9302 $text = 'Caches used (hits/misses/sets): ';
9303 $hits = 0;
9304 $misses = 0;
9305 $sets = 0;
9306 foreach ($stats as $definition => $details) {
9307 switch ($details['mode']) {
9308 case cache_store::MODE_APPLICATION:
9309 $modeclass = 'application';
9310 $mode = ' <span title="application cache">[a]</span>';
9311 break;
9312 case cache_store::MODE_SESSION:
9313 $modeclass = 'session';
9314 $mode = ' <span title="session cache">[s]</span>';
9315 break;
9316 case cache_store::MODE_REQUEST:
9317 $modeclass = 'request';
9318 $mode = ' <span title="request cache">[r]</span>';
9319 break;
9321 $html .= '<ul class="cache-definition-stats list-unstyled m-l-1 m-b-1 cache-mode-'.$modeclass.' card d-inline-block">';
9322 $html .= '<li class="cache-definition-stats-heading p-t-1 card-header bg-dark bg-inverse font-weight-bold">' .
9323 $definition . $mode.'</li>';
9324 $text .= "$definition {";
9325 foreach ($details['stores'] as $store => $data) {
9326 $hits += $data['hits'];
9327 $misses += $data['misses'];
9328 $sets += $data['sets'];
9329 if ($data['hits'] == 0 and $data['misses'] > 0) {
9330 $cachestoreclass = 'nohits text-danger';
9331 } else if ($data['hits'] < $data['misses']) {
9332 $cachestoreclass = 'lowhits text-warning';
9333 } else {
9334 $cachestoreclass = 'hihits text-success';
9336 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9337 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">" .
9338 "$store: $data[hits] / $data[misses] / $data[sets]</li>";
9339 // This makes boxes of same sizes.
9340 if (count($details['stores']) == 1) {
9341 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">&nbsp;</li>";
9344 $html .= '</ul>';
9345 $text .= '} ';
9347 $html .= '</ul> ';
9348 $html .= "<div class='cache-total-stats row'>Total: $hits / $misses / $sets</div>";
9349 $info['cachesused'] = "$hits / $misses / $sets";
9350 $info['html'] .= $html;
9351 $info['txt'] .= $text.'. ';
9352 } else {
9353 $info['cachesused'] = '0 / 0 / 0';
9354 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9355 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9358 $info['html'] = '<div class="performanceinfo siteinfo container-fluid">'.$info['html'].'</div>';
9359 return $info;
9363 * Delete directory or only its content
9365 * @param string $dir directory path
9366 * @param bool $contentonly
9367 * @return bool success, true also if dir does not exist
9369 function remove_dir($dir, $contentonly=false) {
9370 if (!file_exists($dir)) {
9371 // Nothing to do.
9372 return true;
9374 if (!$handle = opendir($dir)) {
9375 return false;
9377 $result = true;
9378 while (false!==($item = readdir($handle))) {
9379 if ($item != '.' && $item != '..') {
9380 if (is_dir($dir.'/'.$item)) {
9381 $result = remove_dir($dir.'/'.$item) && $result;
9382 } else {
9383 $result = unlink($dir.'/'.$item) && $result;
9387 closedir($handle);
9388 if ($contentonly) {
9389 clearstatcache(); // Make sure file stat cache is properly invalidated.
9390 return $result;
9392 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9393 clearstatcache(); // Make sure file stat cache is properly invalidated.
9394 return $result;
9398 * Detect if an object or a class contains a given property
9399 * will take an actual object or the name of a class
9401 * @param mix $obj Name of class or real object to test
9402 * @param string $property name of property to find
9403 * @return bool true if property exists
9405 function object_property_exists( $obj, $property ) {
9406 if (is_string( $obj )) {
9407 $properties = get_class_vars( $obj );
9408 } else {
9409 $properties = get_object_vars( $obj );
9411 return array_key_exists( $property, $properties );
9415 * Converts an object into an associative array
9417 * This function converts an object into an associative array by iterating
9418 * over its public properties. Because this function uses the foreach
9419 * construct, Iterators are respected. It works recursively on arrays of objects.
9420 * Arrays and simple values are returned as is.
9422 * If class has magic properties, it can implement IteratorAggregate
9423 * and return all available properties in getIterator()
9425 * @param mixed $var
9426 * @return array
9428 function convert_to_array($var) {
9429 $result = array();
9431 // Loop over elements/properties.
9432 foreach ($var as $key => $value) {
9433 // Recursively convert objects.
9434 if (is_object($value) || is_array($value)) {
9435 $result[$key] = convert_to_array($value);
9436 } else {
9437 // Simple values are untouched.
9438 $result[$key] = $value;
9441 return $result;
9445 * Detect a custom script replacement in the data directory that will
9446 * replace an existing moodle script
9448 * @return string|bool full path name if a custom script exists, false if no custom script exists
9450 function custom_script_path() {
9451 global $CFG, $SCRIPT;
9453 if ($SCRIPT === null) {
9454 // Probably some weird external script.
9455 return false;
9458 $scriptpath = $CFG->customscripts . $SCRIPT;
9460 // Check the custom script exists.
9461 if (file_exists($scriptpath) and is_file($scriptpath)) {
9462 return $scriptpath;
9463 } else {
9464 return false;
9469 * Returns whether or not the user object is a remote MNET user. This function
9470 * is in moodlelib because it does not rely on loading any of the MNET code.
9472 * @param object $user A valid user object
9473 * @return bool True if the user is from a remote Moodle.
9475 function is_mnet_remote_user($user) {
9476 global $CFG;
9478 if (!isset($CFG->mnet_localhost_id)) {
9479 include_once($CFG->dirroot . '/mnet/lib.php');
9480 $env = new mnet_environment();
9481 $env->init();
9482 unset($env);
9485 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9489 * This function will search for browser prefereed languages, setting Moodle
9490 * to use the best one available if $SESSION->lang is undefined
9492 function setup_lang_from_browser() {
9493 global $CFG, $SESSION, $USER;
9495 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9496 // Lang is defined in session or user profile, nothing to do.
9497 return;
9500 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9501 return;
9504 // Extract and clean langs from headers.
9505 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9506 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9507 $rawlangs = explode(',', $rawlangs); // Convert to array.
9508 $langs = array();
9510 $order = 1.0;
9511 foreach ($rawlangs as $lang) {
9512 if (strpos($lang, ';') === false) {
9513 $langs[(string)$order] = $lang;
9514 $order = $order-0.01;
9515 } else {
9516 $parts = explode(';', $lang);
9517 $pos = strpos($parts[1], '=');
9518 $langs[substr($parts[1], $pos+1)] = $parts[0];
9521 krsort($langs, SORT_NUMERIC);
9523 // Look for such langs under standard locations.
9524 foreach ($langs as $lang) {
9525 // Clean it properly for include.
9526 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9527 if (get_string_manager()->translation_exists($lang, false)) {
9528 // Lang exists, set it in session.
9529 $SESSION->lang = $lang;
9530 // We have finished. Go out.
9531 break;
9534 return;
9538 * Check if $url matches anything in proxybypass list
9540 * Any errors just result in the proxy being used (least bad)
9542 * @param string $url url to check
9543 * @return boolean true if we should bypass the proxy
9545 function is_proxybypass( $url ) {
9546 global $CFG;
9548 // Sanity check.
9549 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9550 return false;
9553 // Get the host part out of the url.
9554 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9555 return false;
9558 // Get the possible bypass hosts into an array.
9559 $matches = explode( ',', $CFG->proxybypass );
9561 // Check for a match.
9562 // (IPs need to match the left hand side and hosts the right of the url,
9563 // but we can recklessly check both as there can't be a false +ve).
9564 foreach ($matches as $match) {
9565 $match = trim($match);
9567 // Try for IP match (Left side).
9568 $lhs = substr($host, 0, strlen($match));
9569 if (strcasecmp($match, $lhs)==0) {
9570 return true;
9573 // Try for host match (Right side).
9574 $rhs = substr($host, -strlen($match));
9575 if (strcasecmp($match, $rhs)==0) {
9576 return true;
9580 // Nothing matched.
9581 return false;
9585 * Check if the passed navigation is of the new style
9587 * @param mixed $navigation
9588 * @return bool true for yes false for no
9590 function is_newnav($navigation) {
9591 if (is_array($navigation) && !empty($navigation['newnav'])) {
9592 return true;
9593 } else {
9594 return false;
9599 * Checks whether the given variable name is defined as a variable within the given object.
9601 * This will NOT work with stdClass objects, which have no class variables.
9603 * @param string $var The variable name
9604 * @param object $object The object to check
9605 * @return boolean
9607 function in_object_vars($var, $object) {
9608 $classvars = get_class_vars(get_class($object));
9609 $classvars = array_keys($classvars);
9610 return in_array($var, $classvars);
9614 * Returns an array without repeated objects.
9615 * This function is similar to array_unique, but for arrays that have objects as values
9617 * @param array $array
9618 * @param bool $keepkeyassoc
9619 * @return array
9621 function object_array_unique($array, $keepkeyassoc = true) {
9622 $duplicatekeys = array();
9623 $tmp = array();
9625 foreach ($array as $key => $val) {
9626 // Convert objects to arrays, in_array() does not support objects.
9627 if (is_object($val)) {
9628 $val = (array)$val;
9631 if (!in_array($val, $tmp)) {
9632 $tmp[] = $val;
9633 } else {
9634 $duplicatekeys[] = $key;
9638 foreach ($duplicatekeys as $key) {
9639 unset($array[$key]);
9642 return $keepkeyassoc ? $array : array_values($array);
9646 * Is a userid the primary administrator?
9648 * @param int $userid int id of user to check
9649 * @return boolean
9651 function is_primary_admin($userid) {
9652 $primaryadmin = get_admin();
9654 if ($userid == $primaryadmin->id) {
9655 return true;
9656 } else {
9657 return false;
9662 * Returns the site identifier
9664 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9666 function get_site_identifier() {
9667 global $CFG;
9668 // Check to see if it is missing. If so, initialise it.
9669 if (empty($CFG->siteidentifier)) {
9670 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9672 // Return it.
9673 return $CFG->siteidentifier;
9677 * Check whether the given password has no more than the specified
9678 * number of consecutive identical characters.
9680 * @param string $password password to be checked against the password policy
9681 * @param integer $maxchars maximum number of consecutive identical characters
9682 * @return bool
9684 function check_consecutive_identical_characters($password, $maxchars) {
9686 if ($maxchars < 1) {
9687 return true; // Zero 0 is to disable this check.
9689 if (strlen($password) <= $maxchars) {
9690 return true; // Too short to fail this test.
9693 $previouschar = '';
9694 $consecutivecount = 1;
9695 foreach (str_split($password) as $char) {
9696 if ($char != $previouschar) {
9697 $consecutivecount = 1;
9698 } else {
9699 $consecutivecount++;
9700 if ($consecutivecount > $maxchars) {
9701 return false; // Check failed already.
9705 $previouschar = $char;
9708 return true;
9712 * Helper function to do partial function binding.
9713 * so we can use it for preg_replace_callback, for example
9714 * this works with php functions, user functions, static methods and class methods
9715 * it returns you a callback that you can pass on like so:
9717 * $callback = partial('somefunction', $arg1, $arg2);
9718 * or
9719 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9720 * or even
9721 * $obj = new someclass();
9722 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9724 * and then the arguments that are passed through at calltime are appended to the argument list.
9726 * @param mixed $function a php callback
9727 * @param mixed $arg1,... $argv arguments to partially bind with
9728 * @return array Array callback
9730 function partial() {
9731 if (!class_exists('partial')) {
9733 * Used to manage function binding.
9734 * @copyright 2009 Penny Leach
9735 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9737 class partial{
9738 /** @var array */
9739 public $values = array();
9740 /** @var string The function to call as a callback. */
9741 public $func;
9743 * Constructor
9744 * @param string $func
9745 * @param array $args
9747 public function __construct($func, $args) {
9748 $this->values = $args;
9749 $this->func = $func;
9752 * Calls the callback function.
9753 * @return mixed
9755 public function method() {
9756 $args = func_get_args();
9757 return call_user_func_array($this->func, array_merge($this->values, $args));
9761 $args = func_get_args();
9762 $func = array_shift($args);
9763 $p = new partial($func, $args);
9764 return array($p, 'method');
9768 * helper function to load up and initialise the mnet environment
9769 * this must be called before you use mnet functions.
9771 * @return mnet_environment the equivalent of old $MNET global
9773 function get_mnet_environment() {
9774 global $CFG;
9775 require_once($CFG->dirroot . '/mnet/lib.php');
9776 static $instance = null;
9777 if (empty($instance)) {
9778 $instance = new mnet_environment();
9779 $instance->init();
9781 return $instance;
9785 * during xmlrpc server code execution, any code wishing to access
9786 * information about the remote peer must use this to get it.
9788 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9790 function get_mnet_remote_client() {
9791 if (!defined('MNET_SERVER')) {
9792 debugging(get_string('notinxmlrpcserver', 'mnet'));
9793 return false;
9795 global $MNET_REMOTE_CLIENT;
9796 if (isset($MNET_REMOTE_CLIENT)) {
9797 return $MNET_REMOTE_CLIENT;
9799 return false;
9803 * during the xmlrpc server code execution, this will be called
9804 * to setup the object returned by {@link get_mnet_remote_client}
9806 * @param mnet_remote_client $client the client to set up
9807 * @throws moodle_exception
9809 function set_mnet_remote_client($client) {
9810 if (!defined('MNET_SERVER')) {
9811 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9813 global $MNET_REMOTE_CLIENT;
9814 $MNET_REMOTE_CLIENT = $client;
9818 * return the jump url for a given remote user
9819 * this is used for rewriting forum post links in emails, etc
9821 * @param stdclass $user the user to get the idp url for
9823 function mnet_get_idp_jump_url($user) {
9824 global $CFG;
9826 static $mnetjumps = array();
9827 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9828 $idp = mnet_get_peer_host($user->mnethostid);
9829 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9830 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9832 return $mnetjumps[$user->mnethostid];
9836 * Gets the homepage to use for the current user
9838 * @return int One of HOMEPAGE_*
9840 function get_home_page() {
9841 global $CFG;
9843 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9844 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9845 return HOMEPAGE_MY;
9846 } else {
9847 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9850 return HOMEPAGE_SITE;
9854 * Gets the name of a course to be displayed when showing a list of courses.
9855 * By default this is just $course->fullname but user can configure it. The
9856 * result of this function should be passed through print_string.
9857 * @param stdClass|course_in_list $course Moodle course object
9858 * @return string Display name of course (either fullname or short + fullname)
9860 function get_course_display_name_for_list($course) {
9861 global $CFG;
9862 if (!empty($CFG->courselistshortnames)) {
9863 if (!($course instanceof stdClass)) {
9864 $course = (object)convert_to_array($course);
9866 return get_string('courseextendednamedisplay', '', $course);
9867 } else {
9868 return $course->fullname;
9873 * Safe analogue of unserialize() that can only parse arrays
9875 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
9876 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
9877 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
9879 * @param string $expression
9880 * @return array|bool either parsed array or false if parsing was impossible.
9882 function unserialize_array($expression) {
9883 $subs = [];
9884 // Find nested arrays, parse them and store in $subs , substitute with special string.
9885 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
9886 $key = '--SUB' . count($subs) . '--';
9887 $subs[$key] = unserialize_array($matches[2]);
9888 if ($subs[$key] === false) {
9889 return false;
9891 $expression = str_replace($matches[2], $key . ';', $expression);
9894 // Check the expression is an array.
9895 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
9896 return false;
9898 // Get the size and elements of an array (key;value;key;value;....).
9899 $parts = explode(';', $matches1[2]);
9900 $size = intval($matches1[1]);
9901 if (count($parts) < $size * 2 + 1) {
9902 return false;
9904 // Analyze each part and make sure it is an integer or string or a substitute.
9905 $value = [];
9906 for ($i = 0; $i < $size * 2; $i++) {
9907 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
9908 $parts[$i] = (int)$matches2[1];
9909 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
9910 $parts[$i] = $matches3[2];
9911 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
9912 $parts[$i] = $subs[$parts[$i]];
9913 } else {
9914 return false;
9917 // Combine keys and values.
9918 for ($i = 0; $i < $size * 2; $i += 2) {
9919 $value[$parts[$i]] = $parts[$i+1];
9921 return $value;
9925 * The lang_string class
9927 * This special class is used to create an object representation of a string request.
9928 * It is special because processing doesn't occur until the object is first used.
9929 * The class was created especially to aid performance in areas where strings were
9930 * required to be generated but were not necessarily used.
9931 * As an example the admin tree when generated uses over 1500 strings, of which
9932 * normally only 1/3 are ever actually printed at any time.
9933 * The performance advantage is achieved by not actually processing strings that
9934 * arn't being used, as such reducing the processing required for the page.
9936 * How to use the lang_string class?
9937 * There are two methods of using the lang_string class, first through the
9938 * forth argument of the get_string function, and secondly directly.
9939 * The following are examples of both.
9940 * 1. Through get_string calls e.g.
9941 * $string = get_string($identifier, $component, $a, true);
9942 * $string = get_string('yes', 'moodle', null, true);
9943 * 2. Direct instantiation
9944 * $string = new lang_string($identifier, $component, $a, $lang);
9945 * $string = new lang_string('yes');
9947 * How do I use a lang_string object?
9948 * The lang_string object makes use of a magic __toString method so that you
9949 * are able to use the object exactly as you would use a string in most cases.
9950 * This means you are able to collect it into a variable and then directly
9951 * echo it, or concatenate it into another string, or similar.
9952 * The other thing you can do is manually get the string by calling the
9953 * lang_strings out method e.g.
9954 * $string = new lang_string('yes');
9955 * $string->out();
9956 * Also worth noting is that the out method can take one argument, $lang which
9957 * allows the developer to change the language on the fly.
9959 * When should I use a lang_string object?
9960 * The lang_string object is designed to be used in any situation where a
9961 * string may not be needed, but needs to be generated.
9962 * The admin tree is a good example of where lang_string objects should be
9963 * used.
9964 * A more practical example would be any class that requries strings that may
9965 * not be printed (after all classes get renderer by renderers and who knows
9966 * what they will do ;))
9968 * When should I not use a lang_string object?
9969 * Don't use lang_strings when you are going to use a string immediately.
9970 * There is no need as it will be processed immediately and there will be no
9971 * advantage, and in fact perhaps a negative hit as a class has to be
9972 * instantiated for a lang_string object, however get_string won't require
9973 * that.
9975 * Limitations:
9976 * 1. You cannot use a lang_string object as an array offset. Doing so will
9977 * result in PHP throwing an error. (You can use it as an object property!)
9979 * @package core
9980 * @category string
9981 * @copyright 2011 Sam Hemelryk
9982 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9984 class lang_string {
9986 /** @var string The strings identifier */
9987 protected $identifier;
9988 /** @var string The strings component. Default '' */
9989 protected $component = '';
9990 /** @var array|stdClass Any arguments required for the string. Default null */
9991 protected $a = null;
9992 /** @var string The language to use when processing the string. Default null */
9993 protected $lang = null;
9995 /** @var string The processed string (once processed) */
9996 protected $string = null;
9999 * A special boolean. If set to true then the object has been woken up and
10000 * cannot be regenerated. If this is set then $this->string MUST be used.
10001 * @var bool
10003 protected $forcedstring = false;
10006 * Constructs a lang_string object
10008 * This function should do as little processing as possible to ensure the best
10009 * performance for strings that won't be used.
10011 * @param string $identifier The strings identifier
10012 * @param string $component The strings component
10013 * @param stdClass|array $a Any arguments the string requires
10014 * @param string $lang The language to use when processing the string.
10015 * @throws coding_exception
10017 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10018 if (empty($component)) {
10019 $component = 'moodle';
10022 $this->identifier = $identifier;
10023 $this->component = $component;
10024 $this->lang = $lang;
10026 // We MUST duplicate $a to ensure that it if it changes by reference those
10027 // changes are not carried across.
10028 // To do this we always ensure $a or its properties/values are strings
10029 // and that any properties/values that arn't convertable are forgotten.
10030 if (!empty($a)) {
10031 if (is_scalar($a)) {
10032 $this->a = $a;
10033 } else if ($a instanceof lang_string) {
10034 $this->a = $a->out();
10035 } else if (is_object($a) or is_array($a)) {
10036 $a = (array)$a;
10037 $this->a = array();
10038 foreach ($a as $key => $value) {
10039 // Make sure conversion errors don't get displayed (results in '').
10040 if (is_array($value)) {
10041 $this->a[$key] = '';
10042 } else if (is_object($value)) {
10043 if (method_exists($value, '__toString')) {
10044 $this->a[$key] = $value->__toString();
10045 } else {
10046 $this->a[$key] = '';
10048 } else {
10049 $this->a[$key] = (string)$value;
10055 if (debugging(false, DEBUG_DEVELOPER)) {
10056 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10057 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10059 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10060 throw new coding_exception('Invalid string compontent. Please check your string definition');
10062 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10063 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10069 * Processes the string.
10071 * This function actually processes the string, stores it in the string property
10072 * and then returns it.
10073 * You will notice that this function is VERY similar to the get_string method.
10074 * That is because it is pretty much doing the same thing.
10075 * However as this function is an upgrade it isn't as tolerant to backwards
10076 * compatibility.
10078 * @return string
10079 * @throws coding_exception
10081 protected function get_string() {
10082 global $CFG;
10084 // Check if we need to process the string.
10085 if ($this->string === null) {
10086 // Check the quality of the identifier.
10087 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10088 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);
10091 // Process the string.
10092 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10093 // Debugging feature lets you display string identifier and component.
10094 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10095 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10098 // Return the string.
10099 return $this->string;
10103 * Returns the string
10105 * @param string $lang The langauge to use when processing the string
10106 * @return string
10108 public function out($lang = null) {
10109 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10110 if ($this->forcedstring) {
10111 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10112 return $this->get_string();
10114 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10115 return $translatedstring->out();
10117 return $this->get_string();
10121 * Magic __toString method for printing a string
10123 * @return string
10125 public function __toString() {
10126 return $this->get_string();
10130 * Magic __set_state method used for var_export
10132 * @return string
10134 public function __set_state() {
10135 return $this->get_string();
10139 * Prepares the lang_string for sleep and stores only the forcedstring and
10140 * string properties... the string cannot be regenerated so we need to ensure
10141 * it is generated for this.
10143 * @return string
10145 public function __sleep() {
10146 $this->get_string();
10147 $this->forcedstring = true;
10148 return array('forcedstring', 'string', 'lang');
10152 * Returns the identifier.
10154 * @return string
10156 public function get_identifier() {
10157 return $this->identifier;
10161 * Returns the component.
10163 * @return string
10165 public function get_component() {
10166 return $this->component;