MDL-61585 analytics: Include missing indicators
[moodle.git] / lib / moodlelib.php
blobb1b61970ceb516424f4b965cba0360a73d9b104c
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 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1631 * {@link phpunit_util::reset_dataroot()}
1633 * @return void
1635 function purge_all_caches() {
1636 global $CFG, $DB;
1638 reset_text_filters_cache();
1639 js_reset_all_caches();
1640 theme_reset_all_caches();
1641 get_string_manager()->reset_caches();
1642 core_text::reset_caches();
1643 if (class_exists('core_plugin_manager')) {
1644 core_plugin_manager::reset_caches();
1647 // Bump up cacherev field for all courses.
1648 try {
1649 increment_revision_number('course', 'cacherev', '');
1650 } catch (moodle_exception $e) {
1651 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1654 $DB->reset_caches();
1655 cache_helper::purge_all();
1657 // Purge all other caches: rss, simplepie, etc.
1658 clearstatcache();
1659 remove_dir($CFG->cachedir.'', true);
1661 // Make sure cache dir is writable, throws exception if not.
1662 make_cache_directory('');
1664 // This is the only place where we purge local caches, we are only adding files there.
1665 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1666 remove_dir($CFG->localcachedir, true);
1667 set_config('localcachedirpurged', time());
1668 make_localcache_directory('', true);
1669 \core\task\manager::clear_static_caches();
1673 * Get volatile flags
1675 * @param string $type
1676 * @param int $changedsince default null
1677 * @return array records array
1679 function get_cache_flags($type, $changedsince = null) {
1680 global $DB;
1682 $params = array('type' => $type, 'expiry' => time());
1683 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1684 if ($changedsince !== null) {
1685 $params['changedsince'] = $changedsince;
1686 $sqlwhere .= " AND timemodified > :changedsince";
1688 $cf = array();
1689 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1690 foreach ($flags as $flag) {
1691 $cf[$flag->name] = $flag->value;
1694 return $cf;
1698 * Get volatile flags
1700 * @param string $type
1701 * @param string $name
1702 * @param int $changedsince default null
1703 * @return string|false The cache flag value or false
1705 function get_cache_flag($type, $name, $changedsince=null) {
1706 global $DB;
1708 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1710 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1711 if ($changedsince !== null) {
1712 $params['changedsince'] = $changedsince;
1713 $sqlwhere .= " AND timemodified > :changedsince";
1716 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1720 * Set a volatile flag
1722 * @param string $type the "type" namespace for the key
1723 * @param string $name the key to set
1724 * @param string $value the value to set (without magic quotes) - null will remove the flag
1725 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1726 * @return bool Always returns true
1728 function set_cache_flag($type, $name, $value, $expiry = null) {
1729 global $DB;
1731 $timemodified = time();
1732 if ($expiry === null || $expiry < $timemodified) {
1733 $expiry = $timemodified + 24 * 60 * 60;
1734 } else {
1735 $expiry = (int)$expiry;
1738 if ($value === null) {
1739 unset_cache_flag($type, $name);
1740 return true;
1743 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1744 // This is a potential problem in DEBUG_DEVELOPER.
1745 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1746 return true; // No need to update.
1748 $f->value = $value;
1749 $f->expiry = $expiry;
1750 $f->timemodified = $timemodified;
1751 $DB->update_record('cache_flags', $f);
1752 } else {
1753 $f = new stdClass();
1754 $f->flagtype = $type;
1755 $f->name = $name;
1756 $f->value = $value;
1757 $f->expiry = $expiry;
1758 $f->timemodified = $timemodified;
1759 $DB->insert_record('cache_flags', $f);
1761 return true;
1765 * Removes a single volatile flag
1767 * @param string $type the "type" namespace for the key
1768 * @param string $name the key to set
1769 * @return bool
1771 function unset_cache_flag($type, $name) {
1772 global $DB;
1773 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1774 return true;
1778 * Garbage-collect volatile flags
1780 * @return bool Always returns true
1782 function gc_cache_flags() {
1783 global $DB;
1784 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1785 return true;
1788 // USER PREFERENCE API.
1791 * Refresh user preference cache. This is used most often for $USER
1792 * object that is stored in session, but it also helps with performance in cron script.
1794 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1796 * @package core
1797 * @category preference
1798 * @access public
1799 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1800 * @param int $cachelifetime Cache life time on the current page (in seconds)
1801 * @throws coding_exception
1802 * @return null
1804 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1805 global $DB;
1806 // Static cache, we need to check on each page load, not only every 2 minutes.
1807 static $loadedusers = array();
1809 if (!isset($user->id)) {
1810 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1813 if (empty($user->id) or isguestuser($user->id)) {
1814 // No permanent storage for not-logged-in users and guest.
1815 if (!isset($user->preference)) {
1816 $user->preference = array();
1818 return;
1821 $timenow = time();
1823 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1824 // Already loaded at least once on this page. Are we up to date?
1825 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1826 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1827 return;
1829 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1830 // No change since the lastcheck on this page.
1831 $user->preference['_lastloaded'] = $timenow;
1832 return;
1836 // OK, so we have to reload all preferences.
1837 $loadedusers[$user->id] = true;
1838 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1839 $user->preference['_lastloaded'] = $timenow;
1843 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1845 * NOTE: internal function, do not call from other code.
1847 * @package core
1848 * @access private
1849 * @param integer $userid the user whose prefs were changed.
1851 function mark_user_preferences_changed($userid) {
1852 global $CFG;
1854 if (empty($userid) or isguestuser($userid)) {
1855 // No cache flags for guest and not-logged-in users.
1856 return;
1859 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1863 * Sets a preference for the specified user.
1865 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1867 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1869 * @package core
1870 * @category preference
1871 * @access public
1872 * @param string $name The key to set as preference for the specified user
1873 * @param string $value The value to set for the $name key in the specified user's
1874 * record, null means delete current value.
1875 * @param stdClass|int|null $user A moodle user object or id, null means current user
1876 * @throws coding_exception
1877 * @return bool Always true or exception
1879 function set_user_preference($name, $value, $user = null) {
1880 global $USER, $DB;
1882 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1883 throw new coding_exception('Invalid preference name in set_user_preference() call');
1886 if (is_null($value)) {
1887 // Null means delete current.
1888 return unset_user_preference($name, $user);
1889 } else if (is_object($value)) {
1890 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1891 } else if (is_array($value)) {
1892 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1894 // Value column maximum length is 1333 characters.
1895 $value = (string)$value;
1896 if (core_text::strlen($value) > 1333) {
1897 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1900 if (is_null($user)) {
1901 $user = $USER;
1902 } else if (isset($user->id)) {
1903 // It is a valid object.
1904 } else if (is_numeric($user)) {
1905 $user = (object)array('id' => (int)$user);
1906 } else {
1907 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1910 check_user_preferences_loaded($user);
1912 if (empty($user->id) or isguestuser($user->id)) {
1913 // No permanent storage for not-logged-in users and guest.
1914 $user->preference[$name] = $value;
1915 return true;
1918 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1919 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1920 // Preference already set to this value.
1921 return true;
1923 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1925 } else {
1926 $preference = new stdClass();
1927 $preference->userid = $user->id;
1928 $preference->name = $name;
1929 $preference->value = $value;
1930 $DB->insert_record('user_preferences', $preference);
1933 // Update value in cache.
1934 $user->preference[$name] = $value;
1935 // Update the $USER in case where we've not a direct reference to $USER.
1936 if ($user !== $USER && $user->id == $USER->id) {
1937 $USER->preference[$name] = $value;
1940 // Set reload flag for other sessions.
1941 mark_user_preferences_changed($user->id);
1943 return true;
1947 * Sets a whole array of preferences for the current user
1949 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1951 * @package core
1952 * @category preference
1953 * @access public
1954 * @param array $prefarray An array of key/value pairs to be set
1955 * @param stdClass|int|null $user A moodle user object or id, null means current user
1956 * @return bool Always true or exception
1958 function set_user_preferences(array $prefarray, $user = null) {
1959 foreach ($prefarray as $name => $value) {
1960 set_user_preference($name, $value, $user);
1962 return true;
1966 * Unsets a preference completely by deleting it from the database
1968 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1970 * @package core
1971 * @category preference
1972 * @access public
1973 * @param string $name The key to unset as preference for the specified user
1974 * @param stdClass|int|null $user A moodle user object or id, null means current user
1975 * @throws coding_exception
1976 * @return bool Always true or exception
1978 function unset_user_preference($name, $user = null) {
1979 global $USER, $DB;
1981 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1982 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1985 if (is_null($user)) {
1986 $user = $USER;
1987 } else if (isset($user->id)) {
1988 // It is a valid object.
1989 } else if (is_numeric($user)) {
1990 $user = (object)array('id' => (int)$user);
1991 } else {
1992 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1995 check_user_preferences_loaded($user);
1997 if (empty($user->id) or isguestuser($user->id)) {
1998 // No permanent storage for not-logged-in user and guest.
1999 unset($user->preference[$name]);
2000 return true;
2003 // Delete from DB.
2004 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2006 // Delete the preference from cache.
2007 unset($user->preference[$name]);
2008 // Update the $USER in case where we've not a direct reference to $USER.
2009 if ($user !== $USER && $user->id == $USER->id) {
2010 unset($USER->preference[$name]);
2013 // Set reload flag for other sessions.
2014 mark_user_preferences_changed($user->id);
2016 return true;
2020 * Used to fetch user preference(s)
2022 * If no arguments are supplied this function will return
2023 * all of the current user preferences as an array.
2025 * If a name is specified then this function
2026 * attempts to return that particular preference value. If
2027 * none is found, then the optional value $default is returned,
2028 * otherwise null.
2030 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2032 * @package core
2033 * @category preference
2034 * @access public
2035 * @param string $name Name of the key to use in finding a preference value
2036 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2037 * @param stdClass|int|null $user A moodle user object or id, null means current user
2038 * @throws coding_exception
2039 * @return string|mixed|null A string containing the value of a single preference. An
2040 * array with all of the preferences or null
2042 function get_user_preferences($name = null, $default = null, $user = null) {
2043 global $USER;
2045 if (is_null($name)) {
2046 // All prefs.
2047 } else if (is_numeric($name) or $name === '_lastloaded') {
2048 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2051 if (is_null($user)) {
2052 $user = $USER;
2053 } else if (isset($user->id)) {
2054 // Is a valid object.
2055 } else if (is_numeric($user)) {
2056 if ($USER->id == $user) {
2057 $user = $USER;
2058 } else {
2059 $user = (object)array('id' => (int)$user);
2061 } else {
2062 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2065 check_user_preferences_loaded($user);
2067 if (empty($name)) {
2068 // All values.
2069 return $user->preference;
2070 } else if (isset($user->preference[$name])) {
2071 // The single string value.
2072 return $user->preference[$name];
2073 } else {
2074 // Default value (null if not specified).
2075 return $default;
2079 // FUNCTIONS FOR HANDLING TIME.
2082 * Given Gregorian date parts in user time produce a GMT timestamp.
2084 * @package core
2085 * @category time
2086 * @param int $year The year part to create timestamp of
2087 * @param int $month The month part to create timestamp of
2088 * @param int $day The day part to create timestamp of
2089 * @param int $hour The hour part to create timestamp of
2090 * @param int $minute The minute part to create timestamp of
2091 * @param int $second The second part to create timestamp of
2092 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2093 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2094 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2095 * applied only if timezone is 99 or string.
2096 * @return int GMT timestamp
2098 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2099 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2100 $date->setDate((int)$year, (int)$month, (int)$day);
2101 $date->setTime((int)$hour, (int)$minute, (int)$second);
2103 $time = $date->getTimestamp();
2105 if ($time === false) {
2106 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2107 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2110 // Moodle BC DST stuff.
2111 if (!$applydst) {
2112 $time += dst_offset_on($time, $timezone);
2115 return $time;
2120 * Format a date/time (seconds) as weeks, days, hours etc as needed
2122 * Given an amount of time in seconds, returns string
2123 * formatted nicely as years, days, hours etc as needed
2125 * @package core
2126 * @category time
2127 * @uses MINSECS
2128 * @uses HOURSECS
2129 * @uses DAYSECS
2130 * @uses YEARSECS
2131 * @param int $totalsecs Time in seconds
2132 * @param stdClass $str Should be a time object
2133 * @return string A nicely formatted date/time string
2135 function format_time($totalsecs, $str = null) {
2137 $totalsecs = abs($totalsecs);
2139 if (!$str) {
2140 // Create the str structure the slow way.
2141 $str = new stdClass();
2142 $str->day = get_string('day');
2143 $str->days = get_string('days');
2144 $str->hour = get_string('hour');
2145 $str->hours = get_string('hours');
2146 $str->min = get_string('min');
2147 $str->mins = get_string('mins');
2148 $str->sec = get_string('sec');
2149 $str->secs = get_string('secs');
2150 $str->year = get_string('year');
2151 $str->years = get_string('years');
2154 $years = floor($totalsecs/YEARSECS);
2155 $remainder = $totalsecs - ($years*YEARSECS);
2156 $days = floor($remainder/DAYSECS);
2157 $remainder = $totalsecs - ($days*DAYSECS);
2158 $hours = floor($remainder/HOURSECS);
2159 $remainder = $remainder - ($hours*HOURSECS);
2160 $mins = floor($remainder/MINSECS);
2161 $secs = $remainder - ($mins*MINSECS);
2163 $ss = ($secs == 1) ? $str->sec : $str->secs;
2164 $sm = ($mins == 1) ? $str->min : $str->mins;
2165 $sh = ($hours == 1) ? $str->hour : $str->hours;
2166 $sd = ($days == 1) ? $str->day : $str->days;
2167 $sy = ($years == 1) ? $str->year : $str->years;
2169 $oyears = '';
2170 $odays = '';
2171 $ohours = '';
2172 $omins = '';
2173 $osecs = '';
2175 if ($years) {
2176 $oyears = $years .' '. $sy;
2178 if ($days) {
2179 $odays = $days .' '. $sd;
2181 if ($hours) {
2182 $ohours = $hours .' '. $sh;
2184 if ($mins) {
2185 $omins = $mins .' '. $sm;
2187 if ($secs) {
2188 $osecs = $secs .' '. $ss;
2191 if ($years) {
2192 return trim($oyears .' '. $odays);
2194 if ($days) {
2195 return trim($odays .' '. $ohours);
2197 if ($hours) {
2198 return trim($ohours .' '. $omins);
2200 if ($mins) {
2201 return trim($omins .' '. $osecs);
2203 if ($secs) {
2204 return $osecs;
2206 return get_string('now');
2210 * Returns a formatted string that represents a date in user time.
2212 * @package core
2213 * @category time
2214 * @param int $date the timestamp in UTC, as obtained from the database.
2215 * @param string $format strftime format. You should probably get this using
2216 * get_string('strftime...', 'langconfig');
2217 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2218 * not 99 then daylight saving will not be added.
2219 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2220 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2221 * If false then the leading zero is maintained.
2222 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2223 * @return string the formatted date/time.
2225 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2226 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2227 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2231 * Returns a formatted date ensuring it is UTF-8.
2233 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2234 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2236 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2237 * @param string $format strftime format.
2238 * @param int|float|string $tz the user timezone
2239 * @return string the formatted date/time.
2240 * @since Moodle 2.3.3
2242 function date_format_string($date, $format, $tz = 99) {
2243 global $CFG;
2245 $localewincharset = null;
2246 // Get the calendar type user is using.
2247 if ($CFG->ostype == 'WINDOWS') {
2248 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2249 $localewincharset = $calendartype->locale_win_charset();
2252 if ($localewincharset) {
2253 $format = core_text::convert($format, 'utf-8', $localewincharset);
2256 date_default_timezone_set(core_date::get_user_timezone($tz));
2257 $datestring = strftime($format, $date);
2258 core_date::set_default_server_timezone();
2260 if ($localewincharset) {
2261 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2264 return $datestring;
2268 * Given a $time timestamp in GMT (seconds since epoch),
2269 * returns an array that represents the Gregorian date in user time
2271 * @package core
2272 * @category time
2273 * @param int $time Timestamp in GMT
2274 * @param float|int|string $timezone user timezone
2275 * @return array An array that represents the date in user time
2277 function usergetdate($time, $timezone=99) {
2278 date_default_timezone_set(core_date::get_user_timezone($timezone));
2279 $result = getdate($time);
2280 core_date::set_default_server_timezone();
2282 return $result;
2286 * Given a GMT timestamp (seconds since epoch), offsets it by
2287 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2289 * NOTE: this function does not include DST properly,
2290 * you should use the PHP date stuff instead!
2292 * @package core
2293 * @category time
2294 * @param int $date Timestamp in GMT
2295 * @param float|int|string $timezone user timezone
2296 * @return int
2298 function usertime($date, $timezone=99) {
2299 $userdate = new DateTime('@' . $date);
2300 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2301 $dst = dst_offset_on($date, $timezone);
2303 return $date - $userdate->getOffset() + $dst;
2307 * Given a time, return the GMT timestamp of the most recent midnight
2308 * for the current user.
2310 * @package core
2311 * @category time
2312 * @param int $date Timestamp in GMT
2313 * @param float|int|string $timezone user timezone
2314 * @return int Returns a GMT timestamp
2316 function usergetmidnight($date, $timezone=99) {
2318 $userdate = usergetdate($date, $timezone);
2320 // Time of midnight of this user's day, in GMT.
2321 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2326 * Returns a string that prints the user's timezone
2328 * @package core
2329 * @category time
2330 * @param float|int|string $timezone user timezone
2331 * @return string
2333 function usertimezone($timezone=99) {
2334 $tz = core_date::get_user_timezone($timezone);
2335 return core_date::get_localised_timezone($tz);
2339 * Returns a float or a string which denotes the user's timezone
2340 * 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)
2341 * means that for this timezone there are also DST rules to be taken into account
2342 * Checks various settings and picks the most dominant of those which have a value
2344 * @package core
2345 * @category time
2346 * @param float|int|string $tz timezone to calculate GMT time offset before
2347 * calculating user timezone, 99 is default user timezone
2348 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2349 * @return float|string
2351 function get_user_timezone($tz = 99) {
2352 global $USER, $CFG;
2354 $timezones = array(
2355 $tz,
2356 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2357 isset($USER->timezone) ? $USER->timezone : 99,
2358 isset($CFG->timezone) ? $CFG->timezone : 99,
2361 $tz = 99;
2363 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2364 foreach ($timezones as $nextvalue) {
2365 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2366 $tz = $nextvalue;
2369 return is_numeric($tz) ? (float) $tz : $tz;
2373 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2374 * - Note: Daylight saving only works for string timezones and not for float.
2376 * @package core
2377 * @category time
2378 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2379 * @param int|float|string $strtimezone user timezone
2380 * @return int
2382 function dst_offset_on($time, $strtimezone = null) {
2383 $tz = core_date::get_user_timezone($strtimezone);
2384 $date = new DateTime('@' . $time);
2385 $date->setTimezone(new DateTimeZone($tz));
2386 if ($date->format('I') == '1') {
2387 if ($tz === 'Australia/Lord_Howe') {
2388 return 1800;
2390 return 3600;
2392 return 0;
2396 * Calculates when the day appears in specific month
2398 * @package core
2399 * @category time
2400 * @param int $startday starting day of the month
2401 * @param int $weekday The day when week starts (normally taken from user preferences)
2402 * @param int $month The month whose day is sought
2403 * @param int $year The year of the month whose day is sought
2404 * @return int
2406 function find_day_in_month($startday, $weekday, $month, $year) {
2407 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2409 $daysinmonth = days_in_month($month, $year);
2410 $daysinweek = count($calendartype->get_weekdays());
2412 if ($weekday == -1) {
2413 // Don't care about weekday, so return:
2414 // abs($startday) if $startday != -1
2415 // $daysinmonth otherwise.
2416 return ($startday == -1) ? $daysinmonth : abs($startday);
2419 // From now on we 're looking for a specific weekday.
2420 // Give "end of month" its actual value, since we know it.
2421 if ($startday == -1) {
2422 $startday = -1 * $daysinmonth;
2425 // Starting from day $startday, the sign is the direction.
2426 if ($startday < 1) {
2427 $startday = abs($startday);
2428 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2430 // This is the last such weekday of the month.
2431 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2432 if ($lastinmonth > $daysinmonth) {
2433 $lastinmonth -= $daysinweek;
2436 // Find the first such weekday <= $startday.
2437 while ($lastinmonth > $startday) {
2438 $lastinmonth -= $daysinweek;
2441 return $lastinmonth;
2442 } else {
2443 $indexweekday = dayofweek($startday, $month, $year);
2445 $diff = $weekday - $indexweekday;
2446 if ($diff < 0) {
2447 $diff += $daysinweek;
2450 // This is the first such weekday of the month equal to or after $startday.
2451 $firstfromindex = $startday + $diff;
2453 return $firstfromindex;
2458 * Calculate the number of days in a given month
2460 * @package core
2461 * @category time
2462 * @param int $month The month whose day count is sought
2463 * @param int $year The year of the month whose day count is sought
2464 * @return int
2466 function days_in_month($month, $year) {
2467 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2468 return $calendartype->get_num_days_in_month($year, $month);
2472 * Calculate the position in the week of a specific calendar day
2474 * @package core
2475 * @category time
2476 * @param int $day The day of the date whose position in the week is sought
2477 * @param int $month The month of the date whose position in the week is sought
2478 * @param int $year The year of the date whose position in the week is sought
2479 * @return int
2481 function dayofweek($day, $month, $year) {
2482 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2483 return $calendartype->get_weekday($year, $month, $day);
2486 // USER AUTHENTICATION AND LOGIN.
2489 * Returns full login url.
2491 * Any form submissions for authentication to this URL must include username,
2492 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2494 * @return string login url
2496 function get_login_url() {
2497 global $CFG;
2499 return "$CFG->wwwroot/login/index.php";
2503 * This function checks that the current user is logged in and has the
2504 * required privileges
2506 * This function checks that the current user is logged in, and optionally
2507 * whether they are allowed to be in a particular course and view a particular
2508 * course module.
2509 * If they are not logged in, then it redirects them to the site login unless
2510 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2511 * case they are automatically logged in as guests.
2512 * If $courseid is given and the user is not enrolled in that course then the
2513 * user is redirected to the course enrolment page.
2514 * If $cm is given and the course module is hidden and the user is not a teacher
2515 * in the course then the user is redirected to the course home page.
2517 * When $cm parameter specified, this function sets page layout to 'module'.
2518 * You need to change it manually later if some other layout needed.
2520 * @package core_access
2521 * @category access
2523 * @param mixed $courseorid id of the course or course object
2524 * @param bool $autologinguest default true
2525 * @param object $cm course module object
2526 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2527 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2528 * in order to keep redirects working properly. MDL-14495
2529 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2530 * @return mixed Void, exit, and die depending on path
2531 * @throws coding_exception
2532 * @throws require_login_exception
2533 * @throws moodle_exception
2535 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2536 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2538 // Must not redirect when byteserving already started.
2539 if (!empty($_SERVER['HTTP_RANGE'])) {
2540 $preventredirect = true;
2543 if (AJAX_SCRIPT) {
2544 // We cannot redirect for AJAX scripts either.
2545 $preventredirect = true;
2548 // Setup global $COURSE, themes, language and locale.
2549 if (!empty($courseorid)) {
2550 if (is_object($courseorid)) {
2551 $course = $courseorid;
2552 } else if ($courseorid == SITEID) {
2553 $course = clone($SITE);
2554 } else {
2555 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2557 if ($cm) {
2558 if ($cm->course != $course->id) {
2559 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2561 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2562 if (!($cm instanceof cm_info)) {
2563 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2564 // db queries so this is not really a performance concern, however it is obviously
2565 // better if you use get_fast_modinfo to get the cm before calling this.
2566 $modinfo = get_fast_modinfo($course);
2567 $cm = $modinfo->get_cm($cm->id);
2570 } else {
2571 // Do not touch global $COURSE via $PAGE->set_course(),
2572 // the reasons is we need to be able to call require_login() at any time!!
2573 $course = $SITE;
2574 if ($cm) {
2575 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2579 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2580 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2581 // risk leading the user back to the AJAX request URL.
2582 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2583 $setwantsurltome = false;
2586 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2587 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2588 if ($preventredirect) {
2589 throw new require_login_session_timeout_exception();
2590 } else {
2591 if ($setwantsurltome) {
2592 $SESSION->wantsurl = qualified_me();
2594 redirect(get_login_url());
2598 // If the user is not even logged in yet then make sure they are.
2599 if (!isloggedin()) {
2600 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2601 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2602 // Misconfigured site guest, just redirect to login page.
2603 redirect(get_login_url());
2604 exit; // Never reached.
2606 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2607 complete_user_login($guest);
2608 $USER->autologinguest = true;
2609 $SESSION->lang = $lang;
2610 } else {
2611 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2612 if ($preventredirect) {
2613 throw new require_login_exception('You are not logged in');
2616 if ($setwantsurltome) {
2617 $SESSION->wantsurl = qualified_me();
2620 $referer = get_local_referer(false);
2621 if (!empty($referer)) {
2622 $SESSION->fromurl = $referer;
2625 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2626 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2627 foreach($authsequence as $authname) {
2628 $authplugin = get_auth_plugin($authname);
2629 $authplugin->pre_loginpage_hook();
2630 if (isloggedin()) {
2631 break;
2635 // If we're still not logged in then go to the login page
2636 if (!isloggedin()) {
2637 redirect(get_login_url());
2638 exit; // Never reached.
2643 // Loginas as redirection if needed.
2644 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2645 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2646 if ($USER->loginascontext->instanceid != $course->id) {
2647 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2652 // Check whether the user should be changing password (but only if it is REALLY them).
2653 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2654 $userauth = get_auth_plugin($USER->auth);
2655 if ($userauth->can_change_password() and !$preventredirect) {
2656 if ($setwantsurltome) {
2657 $SESSION->wantsurl = qualified_me();
2659 if ($changeurl = $userauth->change_password_url()) {
2660 // Use plugin custom url.
2661 redirect($changeurl);
2662 } else {
2663 // Use moodle internal method.
2664 redirect($CFG->wwwroot .'/login/change_password.php');
2666 } else if ($userauth->can_change_password()) {
2667 throw new moodle_exception('forcepasswordchangenotice');
2668 } else {
2669 throw new moodle_exception('nopasswordchangeforced', 'auth');
2673 // Check that the user account is properly set up. If we can't redirect to
2674 // edit their profile and this is not a WS request, perform just the lax check.
2675 // It will allow them to use filepicker on the profile edit page.
2677 if ($preventredirect && !WS_SERVER) {
2678 $usernotfullysetup = user_not_fully_set_up($USER, false);
2679 } else {
2680 $usernotfullysetup = user_not_fully_set_up($USER, true);
2683 if ($usernotfullysetup) {
2684 if ($preventredirect) {
2685 throw new moodle_exception('usernotfullysetup');
2687 if ($setwantsurltome) {
2688 $SESSION->wantsurl = qualified_me();
2690 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2693 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2694 sesskey();
2696 if (\core\session\manager::is_loggedinas()) {
2697 // During a "logged in as" session we should force all content to be cleaned because the
2698 // logged in user will be viewing potentially malicious user generated content.
2699 // See MDL-63786 for more details.
2700 $CFG->forceclean = true;
2703 // Do not bother admins with any formalities, except for activities pending deletion.
2704 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2705 // Set the global $COURSE.
2706 if ($cm) {
2707 $PAGE->set_cm($cm, $course);
2708 $PAGE->set_pagelayout('incourse');
2709 } else if (!empty($courseorid)) {
2710 $PAGE->set_course($course);
2712 // Set accesstime or the user will appear offline which messes up messaging.
2713 user_accesstime_log($course->id);
2714 return;
2717 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2718 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2719 if (!defined('NO_SITEPOLICY_CHECK')) {
2720 define('NO_SITEPOLICY_CHECK', false);
2723 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2724 // Do not test if the script explicitly asked for skipping the site policies check.
2725 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2726 $manager = new \core_privacy\local\sitepolicy\manager();
2727 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2728 if ($preventredirect) {
2729 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2731 if ($setwantsurltome) {
2732 $SESSION->wantsurl = qualified_me();
2734 redirect($policyurl);
2738 // Fetch the system context, the course context, and prefetch its child contexts.
2739 $sysctx = context_system::instance();
2740 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2741 if ($cm) {
2742 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2743 } else {
2744 $cmcontext = null;
2747 // If the site is currently under maintenance, then print a message.
2748 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2749 if ($preventredirect) {
2750 throw new require_login_exception('Maintenance in progress');
2752 $PAGE->set_context(null);
2753 print_maintenance_message();
2756 // Make sure the course itself is not hidden.
2757 if ($course->id == SITEID) {
2758 // Frontpage can not be hidden.
2759 } else {
2760 if (is_role_switched($course->id)) {
2761 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2762 } else {
2763 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2764 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2765 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2766 if ($preventredirect) {
2767 throw new require_login_exception('Course is hidden');
2769 $PAGE->set_context(null);
2770 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2771 // the navigation will mess up when trying to find it.
2772 navigation_node::override_active_url(new moodle_url('/'));
2773 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2778 // Is the user enrolled?
2779 if ($course->id == SITEID) {
2780 // Everybody is enrolled on the frontpage.
2781 } else {
2782 if (\core\session\manager::is_loggedinas()) {
2783 // Make sure the REAL person can access this course first.
2784 $realuser = \core\session\manager::get_realuser();
2785 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2786 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2787 if ($preventredirect) {
2788 throw new require_login_exception('Invalid course login-as access');
2790 $PAGE->set_context(null);
2791 echo $OUTPUT->header();
2792 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2796 $access = false;
2798 if (is_role_switched($course->id)) {
2799 // Ok, user had to be inside this course before the switch.
2800 $access = true;
2802 } else if (is_viewing($coursecontext, $USER)) {
2803 // Ok, no need to mess with enrol.
2804 $access = true;
2806 } else {
2807 if (isset($USER->enrol['enrolled'][$course->id])) {
2808 if ($USER->enrol['enrolled'][$course->id] > time()) {
2809 $access = true;
2810 if (isset($USER->enrol['tempguest'][$course->id])) {
2811 unset($USER->enrol['tempguest'][$course->id]);
2812 remove_temp_course_roles($coursecontext);
2814 } else {
2815 // Expired.
2816 unset($USER->enrol['enrolled'][$course->id]);
2819 if (isset($USER->enrol['tempguest'][$course->id])) {
2820 if ($USER->enrol['tempguest'][$course->id] == 0) {
2821 $access = true;
2822 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2823 $access = true;
2824 } else {
2825 // Expired.
2826 unset($USER->enrol['tempguest'][$course->id]);
2827 remove_temp_course_roles($coursecontext);
2831 if (!$access) {
2832 // Cache not ok.
2833 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2834 if ($until !== false) {
2835 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2836 if ($until == 0) {
2837 $until = ENROL_MAX_TIMESTAMP;
2839 $USER->enrol['enrolled'][$course->id] = $until;
2840 $access = true;
2842 } else {
2843 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2844 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2845 $enrols = enrol_get_plugins(true);
2846 // First ask all enabled enrol instances in course if they want to auto enrol user.
2847 foreach ($instances as $instance) {
2848 if (!isset($enrols[$instance->enrol])) {
2849 continue;
2851 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2852 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2853 if ($until !== false) {
2854 if ($until == 0) {
2855 $until = ENROL_MAX_TIMESTAMP;
2857 $USER->enrol['enrolled'][$course->id] = $until;
2858 $access = true;
2859 break;
2862 // If not enrolled yet try to gain temporary guest access.
2863 if (!$access) {
2864 foreach ($instances as $instance) {
2865 if (!isset($enrols[$instance->enrol])) {
2866 continue;
2868 // Get a duration for the guest access, a timestamp in the future or false.
2869 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2870 if ($until !== false and $until > time()) {
2871 $USER->enrol['tempguest'][$course->id] = $until;
2872 $access = true;
2873 break;
2881 if (!$access) {
2882 if ($preventredirect) {
2883 throw new require_login_exception('Not enrolled');
2885 if ($setwantsurltome) {
2886 $SESSION->wantsurl = qualified_me();
2888 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2892 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
2893 if ($cm && $cm->deletioninprogress) {
2894 if ($preventredirect) {
2895 throw new moodle_exception('activityisscheduledfordeletion');
2897 require_once($CFG->dirroot . '/course/lib.php');
2898 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
2901 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2902 if ($cm && !$cm->uservisible) {
2903 if ($preventredirect) {
2904 throw new require_login_exception('Activity is hidden');
2906 // Get the error message that activity is not available and why (if explanation can be shown to the user).
2907 $PAGE->set_course($course);
2908 $renderer = $PAGE->get_renderer('course');
2909 $message = $renderer->course_section_cm_unavailable_error_message($cm);
2910 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
2913 // Set the global $COURSE.
2914 if ($cm) {
2915 $PAGE->set_cm($cm, $course);
2916 $PAGE->set_pagelayout('incourse');
2917 } else if (!empty($courseorid)) {
2918 $PAGE->set_course($course);
2921 // Finally access granted, update lastaccess times.
2922 user_accesstime_log($course->id);
2927 * This function just makes sure a user is logged out.
2929 * @package core_access
2930 * @category access
2932 function require_logout() {
2933 global $USER, $DB;
2935 if (!isloggedin()) {
2936 // This should not happen often, no need for hooks or events here.
2937 \core\session\manager::terminate_current();
2938 return;
2941 // Execute hooks before action.
2942 $authplugins = array();
2943 $authsequence = get_enabled_auth_plugins();
2944 foreach ($authsequence as $authname) {
2945 $authplugins[$authname] = get_auth_plugin($authname);
2946 $authplugins[$authname]->prelogout_hook();
2949 // Store info that gets removed during logout.
2950 $sid = session_id();
2951 $event = \core\event\user_loggedout::create(
2952 array(
2953 'userid' => $USER->id,
2954 'objectid' => $USER->id,
2955 'other' => array('sessionid' => $sid),
2958 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2959 $event->add_record_snapshot('sessions', $session);
2962 // Clone of $USER object to be used by auth plugins.
2963 $user = fullclone($USER);
2965 // Delete session record and drop $_SESSION content.
2966 \core\session\manager::terminate_current();
2968 // Trigger event AFTER action.
2969 $event->trigger();
2971 // Hook to execute auth plugins redirection after event trigger.
2972 foreach ($authplugins as $authplugin) {
2973 $authplugin->postlogout_hook($user);
2978 * Weaker version of require_login()
2980 * This is a weaker version of {@link require_login()} which only requires login
2981 * when called from within a course rather than the site page, unless
2982 * the forcelogin option is turned on.
2983 * @see require_login()
2985 * @package core_access
2986 * @category access
2988 * @param mixed $courseorid The course object or id in question
2989 * @param bool $autologinguest Allow autologin guests if that is wanted
2990 * @param object $cm Course activity module if known
2991 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2992 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2993 * in order to keep redirects working properly. MDL-14495
2994 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2995 * @return void
2996 * @throws coding_exception
2998 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2999 global $CFG, $PAGE, $SITE;
3000 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3001 or (!is_object($courseorid) and $courseorid == SITEID));
3002 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3003 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3004 // db queries so this is not really a performance concern, however it is obviously
3005 // better if you use get_fast_modinfo to get the cm before calling this.
3006 if (is_object($courseorid)) {
3007 $course = $courseorid;
3008 } else {
3009 $course = clone($SITE);
3011 $modinfo = get_fast_modinfo($course);
3012 $cm = $modinfo->get_cm($cm->id);
3014 if (!empty($CFG->forcelogin)) {
3015 // Login required for both SITE and courses.
3016 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3018 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3019 // Always login for hidden activities.
3020 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3022 } else if (isloggedin() && !isguestuser()) {
3023 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3024 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3026 } else if ($issite) {
3027 // Login for SITE not required.
3028 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3029 if (!empty($courseorid)) {
3030 if (is_object($courseorid)) {
3031 $course = $courseorid;
3032 } else {
3033 $course = clone $SITE;
3035 if ($cm) {
3036 if ($cm->course != $course->id) {
3037 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3039 $PAGE->set_cm($cm, $course);
3040 $PAGE->set_pagelayout('incourse');
3041 } else {
3042 $PAGE->set_course($course);
3044 } else {
3045 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3046 $PAGE->set_course($PAGE->course);
3048 // Do not update access time for webservice or ajax requests.
3049 if (!WS_SERVER && !AJAX_SCRIPT) {
3050 user_accesstime_log(SITEID);
3052 return;
3054 } else {
3055 // Course login always required.
3056 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3061 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3063 * @param string $keyvalue the key value
3064 * @param string $script unique script identifier
3065 * @param int $instance instance id
3066 * @return stdClass the key entry in the user_private_key table
3067 * @since Moodle 3.2
3068 * @throws moodle_exception
3070 function validate_user_key($keyvalue, $script, $instance) {
3071 global $DB;
3073 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3074 print_error('invalidkey');
3077 if (!empty($key->validuntil) and $key->validuntil < time()) {
3078 print_error('expiredkey');
3081 if ($key->iprestriction) {
3082 $remoteaddr = getremoteaddr(null);
3083 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3084 print_error('ipmismatch');
3087 return $key;
3091 * Require key login. Function terminates with error if key not found or incorrect.
3093 * @uses NO_MOODLE_COOKIES
3094 * @uses PARAM_ALPHANUM
3095 * @param string $script unique script identifier
3096 * @param int $instance optional instance id
3097 * @return int Instance ID
3099 function require_user_key_login($script, $instance=null) {
3100 global $DB;
3102 if (!NO_MOODLE_COOKIES) {
3103 print_error('sessioncookiesdisable');
3106 // Extra safety.
3107 \core\session\manager::write_close();
3109 $keyvalue = required_param('key', PARAM_ALPHANUM);
3111 $key = validate_user_key($keyvalue, $script, $instance);
3113 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3114 print_error('invaliduserid');
3117 // Emulate normal session.
3118 enrol_check_plugins($user);
3119 \core\session\manager::set_user($user);
3121 // Note we are not using normal login.
3122 if (!defined('USER_KEY_LOGIN')) {
3123 define('USER_KEY_LOGIN', true);
3126 // Return instance id - it might be empty.
3127 return $key->instance;
3131 * Creates a new private user access key.
3133 * @param string $script unique target identifier
3134 * @param int $userid
3135 * @param int $instance optional instance id
3136 * @param string $iprestriction optional ip restricted access
3137 * @param int $validuntil key valid only until given data
3138 * @return string access key value
3140 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3141 global $DB;
3143 $key = new stdClass();
3144 $key->script = $script;
3145 $key->userid = $userid;
3146 $key->instance = $instance;
3147 $key->iprestriction = $iprestriction;
3148 $key->validuntil = $validuntil;
3149 $key->timecreated = time();
3151 // Something long and unique.
3152 $key->value = md5($userid.'_'.time().random_string(40));
3153 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3154 // Must be unique.
3155 $key->value = md5($userid.'_'.time().random_string(40));
3157 $DB->insert_record('user_private_key', $key);
3158 return $key->value;
3162 * Delete the user's new private user access keys for a particular script.
3164 * @param string $script unique target identifier
3165 * @param int $userid
3166 * @return void
3168 function delete_user_key($script, $userid) {
3169 global $DB;
3170 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3174 * Gets a private user access key (and creates one if one doesn't exist).
3176 * @param string $script unique target identifier
3177 * @param int $userid
3178 * @param int $instance optional instance id
3179 * @param string $iprestriction optional ip restricted access
3180 * @param int $validuntil key valid only until given date
3181 * @return string access key value
3183 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3184 global $DB;
3186 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3187 'instance' => $instance, 'iprestriction' => $iprestriction,
3188 'validuntil' => $validuntil))) {
3189 return $key->value;
3190 } else {
3191 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3197 * Modify the user table by setting the currently logged in user's last login to now.
3199 * @return bool Always returns true
3201 function update_user_login_times() {
3202 global $USER, $DB;
3204 if (isguestuser()) {
3205 // Do not update guest access times/ips for performance.
3206 return true;
3209 $now = time();
3211 $user = new stdClass();
3212 $user->id = $USER->id;
3214 // Make sure all users that logged in have some firstaccess.
3215 if ($USER->firstaccess == 0) {
3216 $USER->firstaccess = $user->firstaccess = $now;
3219 // Store the previous current as lastlogin.
3220 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3222 $USER->currentlogin = $user->currentlogin = $now;
3224 // Function user_accesstime_log() may not update immediately, better do it here.
3225 $USER->lastaccess = $user->lastaccess = $now;
3226 $USER->lastip = $user->lastip = getremoteaddr();
3228 // Note: do not call user_update_user() here because this is part of the login process,
3229 // the login event means that these fields were updated.
3230 $DB->update_record('user', $user);
3231 return true;
3235 * Determines if a user has completed setting up their account.
3237 * The lax mode (with $strict = false) has been introduced for special cases
3238 * only where we want to skip certain checks intentionally. This is valid in
3239 * certain mnet or ajax scenarios when the user cannot / should not be
3240 * redirected to edit their profile. In most cases, you should perform the
3241 * strict check.
3243 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3244 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3245 * @return bool
3247 function user_not_fully_set_up($user, $strict = true) {
3248 global $CFG;
3249 require_once($CFG->dirroot.'/user/profile/lib.php');
3251 if (isguestuser($user)) {
3252 return false;
3255 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3256 return true;
3259 if ($strict) {
3260 if (empty($user->id)) {
3261 // Strict mode can be used with existing accounts only.
3262 return true;
3264 if (!profile_has_required_custom_fields_set($user->id)) {
3265 return true;
3269 return false;
3273 * Check whether the user has exceeded the bounce threshold
3275 * @param stdClass $user A {@link $USER} object
3276 * @return bool true => User has exceeded bounce threshold
3278 function over_bounce_threshold($user) {
3279 global $CFG, $DB;
3281 if (empty($CFG->handlebounces)) {
3282 return false;
3285 if (empty($user->id)) {
3286 // No real (DB) user, nothing to do here.
3287 return false;
3290 // Set sensible defaults.
3291 if (empty($CFG->minbounces)) {
3292 $CFG->minbounces = 10;
3294 if (empty($CFG->bounceratio)) {
3295 $CFG->bounceratio = .20;
3297 $bouncecount = 0;
3298 $sendcount = 0;
3299 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3300 $bouncecount = $bounce->value;
3302 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3303 $sendcount = $send->value;
3305 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3309 * Used to increment or reset email sent count
3311 * @param stdClass $user object containing an id
3312 * @param bool $reset will reset the count to 0
3313 * @return void
3315 function set_send_count($user, $reset=false) {
3316 global $DB;
3318 if (empty($user->id)) {
3319 // No real (DB) user, nothing to do here.
3320 return;
3323 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3324 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3325 $DB->update_record('user_preferences', $pref);
3326 } else if (!empty($reset)) {
3327 // If it's not there and we're resetting, don't bother. Make a new one.
3328 $pref = new stdClass();
3329 $pref->name = 'email_send_count';
3330 $pref->value = 1;
3331 $pref->userid = $user->id;
3332 $DB->insert_record('user_preferences', $pref, false);
3337 * Increment or reset user's email bounce count
3339 * @param stdClass $user object containing an id
3340 * @param bool $reset will reset the count to 0
3342 function set_bounce_count($user, $reset=false) {
3343 global $DB;
3345 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3346 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3347 $DB->update_record('user_preferences', $pref);
3348 } else if (!empty($reset)) {
3349 // If it's not there and we're resetting, don't bother. Make a new one.
3350 $pref = new stdClass();
3351 $pref->name = 'email_bounce_count';
3352 $pref->value = 1;
3353 $pref->userid = $user->id;
3354 $DB->insert_record('user_preferences', $pref, false);
3359 * Determines if the logged in user is currently moving an activity
3361 * @param int $courseid The id of the course being tested
3362 * @return bool
3364 function ismoving($courseid) {
3365 global $USER;
3367 if (!empty($USER->activitycopy)) {
3368 return ($USER->activitycopycourse == $courseid);
3370 return false;
3374 * Returns a persons full name
3376 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3377 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3378 * specify one.
3380 * @param stdClass $user A {@link $USER} object to get full name of.
3381 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3382 * @return string
3384 function fullname($user, $override=false) {
3385 global $CFG, $SESSION;
3387 if (!isset($user->firstname) and !isset($user->lastname)) {
3388 return '';
3391 // Get all of the name fields.
3392 $allnames = get_all_user_name_fields();
3393 if ($CFG->debugdeveloper) {
3394 foreach ($allnames as $allname) {
3395 if (!property_exists($user, $allname)) {
3396 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3397 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3398 // Message has been sent, no point in sending the message multiple times.
3399 break;
3404 if (!$override) {
3405 if (!empty($CFG->forcefirstname)) {
3406 $user->firstname = $CFG->forcefirstname;
3408 if (!empty($CFG->forcelastname)) {
3409 $user->lastname = $CFG->forcelastname;
3413 if (!empty($SESSION->fullnamedisplay)) {
3414 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3417 $template = null;
3418 // If the fullnamedisplay setting is available, set the template to that.
3419 if (isset($CFG->fullnamedisplay)) {
3420 $template = $CFG->fullnamedisplay;
3422 // If the template is empty, or set to language, return the language string.
3423 if ((empty($template) || $template == 'language') && !$override) {
3424 return get_string('fullnamedisplay', null, $user);
3427 // Check to see if we are displaying according to the alternative full name format.
3428 if ($override) {
3429 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3430 // Default to show just the user names according to the fullnamedisplay string.
3431 return get_string('fullnamedisplay', null, $user);
3432 } else {
3433 // If the override is true, then change the template to use the complete name.
3434 $template = $CFG->alternativefullnameformat;
3438 $requirednames = array();
3439 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3440 foreach ($allnames as $allname) {
3441 if (strpos($template, $allname) !== false) {
3442 $requirednames[] = $allname;
3446 $displayname = $template;
3447 // Switch in the actual data into the template.
3448 foreach ($requirednames as $altname) {
3449 if (isset($user->$altname)) {
3450 // Using empty() on the below if statement causes breakages.
3451 if ((string)$user->$altname == '') {
3452 $displayname = str_replace($altname, 'EMPTY', $displayname);
3453 } else {
3454 $displayname = str_replace($altname, $user->$altname, $displayname);
3456 } else {
3457 $displayname = str_replace($altname, 'EMPTY', $displayname);
3460 // Tidy up any misc. characters (Not perfect, but gets most characters).
3461 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3462 // katakana and parenthesis.
3463 $patterns = array();
3464 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3465 // filled in by a user.
3466 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3467 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3468 // This regular expression is to remove any double spaces in the display name.
3469 $patterns[] = '/\s{2,}/u';
3470 foreach ($patterns as $pattern) {
3471 $displayname = preg_replace($pattern, ' ', $displayname);
3474 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3475 $displayname = trim($displayname);
3476 if (empty($displayname)) {
3477 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3478 // people in general feel is a good setting to fall back on.
3479 $displayname = $user->firstname;
3481 return $displayname;
3485 * A centralised location for the all name fields. Returns an array / sql string snippet.
3487 * @param bool $returnsql True for an sql select field snippet.
3488 * @param string $tableprefix table query prefix to use in front of each field.
3489 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3490 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3491 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3492 * @return array|string All name fields.
3494 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3495 // This array is provided in this order because when called by fullname() (above) if firstname is before
3496 // firstnamephonetic str_replace() will change the wrong placeholder.
3497 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3498 'lastnamephonetic' => 'lastnamephonetic',
3499 'middlename' => 'middlename',
3500 'alternatename' => 'alternatename',
3501 'firstname' => 'firstname',
3502 'lastname' => 'lastname');
3504 // Let's add a prefix to the array of user name fields if provided.
3505 if ($prefix) {
3506 foreach ($alternatenames as $key => $altname) {
3507 $alternatenames[$key] = $prefix . $altname;
3511 // If we want the end result to have firstname and lastname at the front / top of the result.
3512 if ($order) {
3513 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3514 for ($i = 0; $i < 2; $i++) {
3515 // Get the last element.
3516 $lastelement = end($alternatenames);
3517 // Remove it from the array.
3518 unset($alternatenames[$lastelement]);
3519 // Put the element back on the top of the array.
3520 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3524 // Create an sql field snippet if requested.
3525 if ($returnsql) {
3526 if ($tableprefix) {
3527 if ($fieldprefix) {
3528 foreach ($alternatenames as $key => $altname) {
3529 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3531 } else {
3532 foreach ($alternatenames as $key => $altname) {
3533 $alternatenames[$key] = $tableprefix . '.' . $altname;
3537 $alternatenames = implode(',', $alternatenames);
3539 return $alternatenames;
3543 * Reduces lines of duplicated code for getting user name fields.
3545 * See also {@link user_picture::unalias()}
3547 * @param object $addtoobject Object to add user name fields to.
3548 * @param object $secondobject Object that contains user name field information.
3549 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3550 * @param array $additionalfields Additional fields to be matched with data in the second object.
3551 * The key can be set to the user table field name.
3552 * @return object User name fields.
3554 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3555 $fields = get_all_user_name_fields(false, null, $prefix);
3556 if ($additionalfields) {
3557 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3558 // the key is a number and then sets the key to the array value.
3559 foreach ($additionalfields as $key => $value) {
3560 if (is_numeric($key)) {
3561 $additionalfields[$value] = $prefix . $value;
3562 unset($additionalfields[$key]);
3563 } else {
3564 $additionalfields[$key] = $prefix . $value;
3567 $fields = array_merge($fields, $additionalfields);
3569 foreach ($fields as $key => $field) {
3570 // Important that we have all of the user name fields present in the object that we are sending back.
3571 $addtoobject->$key = '';
3572 if (isset($secondobject->$field)) {
3573 $addtoobject->$key = $secondobject->$field;
3576 return $addtoobject;
3580 * Returns an array of values in order of occurance in a provided string.
3581 * The key in the result is the character postion in the string.
3583 * @param array $values Values to be found in the string format
3584 * @param string $stringformat The string which may contain values being searched for.
3585 * @return array An array of values in order according to placement in the string format.
3587 function order_in_string($values, $stringformat) {
3588 $valuearray = array();
3589 foreach ($values as $value) {
3590 $pattern = "/$value\b/";
3591 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3592 if (preg_match($pattern, $stringformat)) {
3593 $replacement = "thing";
3594 // Replace the value with something more unique to ensure we get the right position when using strpos().
3595 $newformat = preg_replace($pattern, $replacement, $stringformat);
3596 $position = strpos($newformat, $replacement);
3597 $valuearray[$position] = $value;
3600 ksort($valuearray);
3601 return $valuearray;
3605 * Checks if current user is shown any extra fields when listing users.
3607 * @param object $context Context
3608 * @param array $already Array of fields that we're going to show anyway
3609 * so don't bother listing them
3610 * @return array Array of field names from user table, not including anything
3611 * listed in $already
3613 function get_extra_user_fields($context, $already = array()) {
3614 global $CFG;
3616 // Only users with permission get the extra fields.
3617 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3618 return array();
3621 // Split showuseridentity on comma (filter needed in case the showuseridentity is empty).
3622 $extra = array_filter(explode(',', $CFG->showuseridentity));
3624 foreach ($extra as $key => $field) {
3625 if (in_array($field, $already)) {
3626 unset($extra[$key]);
3630 // If the identity fields are also among hidden fields, make sure the user can see them.
3631 $hiddenfields = array_filter(explode(',', $CFG->hiddenuserfields));
3632 $hiddenidentifiers = array_intersect($extra, $hiddenfields);
3634 if ($hiddenidentifiers) {
3635 if ($context->get_course_context(false)) {
3636 // We are somewhere inside a course.
3637 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3639 } else {
3640 // We are not inside a course.
3641 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
3644 if (!$canviewhiddenuserfields) {
3645 // Remove hidden identifiers from the list.
3646 $extra = array_diff($extra, $hiddenidentifiers);
3650 // Re-index the entries.
3651 $extra = array_values($extra);
3653 return $extra;
3657 * If the current user is to be shown extra user fields when listing or
3658 * selecting users, returns a string suitable for including in an SQL select
3659 * clause to retrieve those fields.
3661 * @param context $context Context
3662 * @param string $alias Alias of user table, e.g. 'u' (default none)
3663 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3664 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3665 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3667 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3668 $fields = get_extra_user_fields($context, $already);
3669 $result = '';
3670 // Add punctuation for alias.
3671 if ($alias !== '') {
3672 $alias .= '.';
3674 foreach ($fields as $field) {
3675 $result .= ', ' . $alias . $field;
3676 if ($prefix) {
3677 $result .= ' AS ' . $prefix . $field;
3680 return $result;
3684 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3685 * @param string $field Field name, e.g. 'phone1'
3686 * @return string Text description taken from language file, e.g. 'Phone number'
3688 function get_user_field_name($field) {
3689 // Some fields have language strings which are not the same as field name.
3690 switch ($field) {
3691 case 'url' : {
3692 return get_string('webpage');
3694 case 'icq' : {
3695 return get_string('icqnumber');
3697 case 'skype' : {
3698 return get_string('skypeid');
3700 case 'aim' : {
3701 return get_string('aimid');
3703 case 'yahoo' : {
3704 return get_string('yahooid');
3706 case 'msn' : {
3707 return get_string('msnid');
3709 case 'picture' : {
3710 return get_string('pictureofuser');
3713 // Otherwise just use the same lang string.
3714 return get_string($field);
3718 * Returns whether a given authentication plugin exists.
3720 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3721 * @return boolean Whether the plugin is available.
3723 function exists_auth_plugin($auth) {
3724 global $CFG;
3726 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3727 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3729 return false;
3733 * Checks if a given plugin is in the list of enabled authentication plugins.
3735 * @param string $auth Authentication plugin.
3736 * @return boolean Whether the plugin is enabled.
3738 function is_enabled_auth($auth) {
3739 if (empty($auth)) {
3740 return false;
3743 $enabled = get_enabled_auth_plugins();
3745 return in_array($auth, $enabled);
3749 * Returns an authentication plugin instance.
3751 * @param string $auth name of authentication plugin
3752 * @return auth_plugin_base An instance of the required authentication plugin.
3754 function get_auth_plugin($auth) {
3755 global $CFG;
3757 // Check the plugin exists first.
3758 if (! exists_auth_plugin($auth)) {
3759 print_error('authpluginnotfound', 'debug', '', $auth);
3762 // Return auth plugin instance.
3763 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3764 $class = "auth_plugin_$auth";
3765 return new $class;
3769 * Returns array of active auth plugins.
3771 * @param bool $fix fix $CFG->auth if needed
3772 * @return array
3774 function get_enabled_auth_plugins($fix=false) {
3775 global $CFG;
3777 $default = array('manual', 'nologin');
3779 if (empty($CFG->auth)) {
3780 $auths = array();
3781 } else {
3782 $auths = explode(',', $CFG->auth);
3785 if ($fix) {
3786 $auths = array_unique($auths);
3787 foreach ($auths as $k => $authname) {
3788 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3789 unset($auths[$k]);
3792 $newconfig = implode(',', $auths);
3793 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3794 set_config('auth', $newconfig);
3798 return (array_merge($default, $auths));
3802 * Returns true if an internal authentication method is being used.
3803 * if method not specified then, global default is assumed
3805 * @param string $auth Form of authentication required
3806 * @return bool
3808 function is_internal_auth($auth) {
3809 // Throws error if bad $auth.
3810 $authplugin = get_auth_plugin($auth);
3811 return $authplugin->is_internal();
3815 * Returns true if the user is a 'restored' one.
3817 * Used in the login process to inform the user and allow him/her to reset the password
3819 * @param string $username username to be checked
3820 * @return bool
3822 function is_restored_user($username) {
3823 global $CFG, $DB;
3825 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3829 * Returns an array of user fields
3831 * @return array User field/column names
3833 function get_user_fieldnames() {
3834 global $DB;
3836 $fieldarray = $DB->get_columns('user');
3837 unset($fieldarray['id']);
3838 $fieldarray = array_keys($fieldarray);
3840 return $fieldarray;
3844 * Creates a bare-bones user record
3846 * @todo Outline auth types and provide code example
3848 * @param string $username New user's username to add to record
3849 * @param string $password New user's password to add to record
3850 * @param string $auth Form of authentication required
3851 * @return stdClass A complete user object
3853 function create_user_record($username, $password, $auth = 'manual') {
3854 global $CFG, $DB;
3855 require_once($CFG->dirroot.'/user/profile/lib.php');
3856 require_once($CFG->dirroot.'/user/lib.php');
3858 // Just in case check text case.
3859 $username = trim(core_text::strtolower($username));
3861 $authplugin = get_auth_plugin($auth);
3862 $customfields = $authplugin->get_custom_user_profile_fields();
3863 $newuser = new stdClass();
3864 if ($newinfo = $authplugin->get_userinfo($username)) {
3865 $newinfo = truncate_userinfo($newinfo);
3866 foreach ($newinfo as $key => $value) {
3867 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3868 $newuser->$key = $value;
3873 if (!empty($newuser->email)) {
3874 if (email_is_not_allowed($newuser->email)) {
3875 unset($newuser->email);
3879 if (!isset($newuser->city)) {
3880 $newuser->city = '';
3883 $newuser->auth = $auth;
3884 $newuser->username = $username;
3886 // Fix for MDL-8480
3887 // user CFG lang for user if $newuser->lang is empty
3888 // or $user->lang is not an installed language.
3889 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3890 $newuser->lang = $CFG->lang;
3892 $newuser->confirmed = 1;
3893 $newuser->lastip = getremoteaddr();
3894 $newuser->timecreated = time();
3895 $newuser->timemodified = $newuser->timecreated;
3896 $newuser->mnethostid = $CFG->mnet_localhost_id;
3898 $newuser->id = user_create_user($newuser, false, false);
3900 // Save user profile data.
3901 profile_save_data($newuser);
3903 $user = get_complete_user_data('id', $newuser->id);
3904 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3905 set_user_preference('auth_forcepasswordchange', 1, $user);
3907 // Set the password.
3908 update_internal_user_password($user, $password);
3910 // Trigger event.
3911 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3913 return $user;
3917 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3919 * @param string $username user's username to update the record
3920 * @return stdClass A complete user object
3922 function update_user_record($username) {
3923 global $DB, $CFG;
3924 // Just in case check text case.
3925 $username = trim(core_text::strtolower($username));
3927 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3928 return update_user_record_by_id($oldinfo->id);
3932 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3934 * @param int $id user id
3935 * @return stdClass A complete user object
3937 function update_user_record_by_id($id) {
3938 global $DB, $CFG;
3939 require_once($CFG->dirroot."/user/profile/lib.php");
3940 require_once($CFG->dirroot.'/user/lib.php');
3942 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3943 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3945 $newuser = array();
3946 $userauth = get_auth_plugin($oldinfo->auth);
3948 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3949 $newinfo = truncate_userinfo($newinfo);
3950 $customfields = $userauth->get_custom_user_profile_fields();
3952 foreach ($newinfo as $key => $value) {
3953 $iscustom = in_array($key, $customfields);
3954 if (!$iscustom) {
3955 $key = strtolower($key);
3957 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3958 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3959 // Unknown or must not be changed.
3960 continue;
3962 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
3963 continue;
3965 $confval = $userauth->config->{'field_updatelocal_' . $key};
3966 $lockval = $userauth->config->{'field_lock_' . $key};
3967 if ($confval === 'onlogin') {
3968 // MDL-4207 Don't overwrite modified user profile values with
3969 // empty LDAP values when 'unlocked if empty' is set. The purpose
3970 // of the setting 'unlocked if empty' is to allow the user to fill
3971 // in a value for the selected field _if LDAP is giving
3972 // nothing_ for this field. Thus it makes sense to let this value
3973 // stand in until LDAP is giving a value for this field.
3974 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3975 if ($iscustom || (in_array($key, $userauth->userfields) &&
3976 ((string)$oldinfo->$key !== (string)$value))) {
3977 $newuser[$key] = (string)$value;
3982 if ($newuser) {
3983 $newuser['id'] = $oldinfo->id;
3984 $newuser['timemodified'] = time();
3985 user_update_user((object) $newuser, false, false);
3987 // Save user profile data.
3988 profile_save_data((object) $newuser);
3990 // Trigger event.
3991 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
3995 return get_complete_user_data('id', $oldinfo->id);
3999 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4001 * @param array $info Array of user properties to truncate if needed
4002 * @return array The now truncated information that was passed in
4004 function truncate_userinfo(array $info) {
4005 // Define the limits.
4006 $limit = array(
4007 'username' => 100,
4008 'idnumber' => 255,
4009 'firstname' => 100,
4010 'lastname' => 100,
4011 'email' => 100,
4012 'icq' => 15,
4013 'phone1' => 20,
4014 'phone2' => 20,
4015 'institution' => 255,
4016 'department' => 255,
4017 'address' => 255,
4018 'city' => 120,
4019 'country' => 2,
4020 'url' => 255,
4023 // Apply where needed.
4024 foreach (array_keys($info) as $key) {
4025 if (!empty($limit[$key])) {
4026 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4030 return $info;
4034 * Marks user deleted in internal user database and notifies the auth plugin.
4035 * Also unenrols user from all roles and does other cleanup.
4037 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4039 * @param stdClass $user full user object before delete
4040 * @return boolean success
4041 * @throws coding_exception if invalid $user parameter detected
4043 function delete_user(stdClass $user) {
4044 global $CFG, $DB, $SESSION;
4045 require_once($CFG->libdir.'/grouplib.php');
4046 require_once($CFG->libdir.'/gradelib.php');
4047 require_once($CFG->dirroot.'/message/lib.php');
4048 require_once($CFG->dirroot.'/user/lib.php');
4050 // Make sure nobody sends bogus record type as parameter.
4051 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4052 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4055 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4056 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4057 debugging('Attempt to delete unknown user account.');
4058 return false;
4061 // There must be always exactly one guest record, originally the guest account was identified by username only,
4062 // now we use $CFG->siteguest for performance reasons.
4063 if ($user->username === 'guest' or isguestuser($user)) {
4064 debugging('Guest user account can not be deleted.');
4065 return false;
4068 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4069 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4070 if ($user->auth === 'manual' and is_siteadmin($user)) {
4071 debugging('Local administrator accounts can not be deleted.');
4072 return false;
4075 // Allow plugins to use this user object before we completely delete it.
4076 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4077 foreach ($pluginsfunction as $plugintype => $plugins) {
4078 foreach ($plugins as $pluginfunction) {
4079 $pluginfunction($user);
4084 // Keep user record before updating it, as we have to pass this to user_deleted event.
4085 $olduser = clone $user;
4087 // Keep a copy of user context, we need it for event.
4088 $usercontext = context_user::instance($user->id);
4090 // Delete all grades - backup is kept in grade_grades_history table.
4091 grade_user_delete($user->id);
4093 // TODO: remove from cohorts using standard API here.
4095 // Remove user tags.
4096 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4098 // Unconditionally unenrol from all courses.
4099 enrol_user_delete($user);
4101 // Unenrol from all roles in all contexts.
4102 // This might be slow but it is really needed - modules might do some extra cleanup!
4103 role_unassign_all(array('userid' => $user->id));
4105 // Now do a brute force cleanup.
4107 // Remove from all cohorts.
4108 $DB->delete_records('cohort_members', array('userid' => $user->id));
4110 // Remove from all groups.
4111 $DB->delete_records('groups_members', array('userid' => $user->id));
4113 // Brute force unenrol from all courses.
4114 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4116 // Purge user preferences.
4117 $DB->delete_records('user_preferences', array('userid' => $user->id));
4119 // Purge user extra profile info.
4120 $DB->delete_records('user_info_data', array('userid' => $user->id));
4122 // Purge log of previous password hashes.
4123 $DB->delete_records('user_password_history', array('userid' => $user->id));
4125 // Last course access not necessary either.
4126 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4127 // Remove all user tokens.
4128 $DB->delete_records('external_tokens', array('userid' => $user->id));
4130 // Unauthorise the user for all services.
4131 $DB->delete_records('external_services_users', array('userid' => $user->id));
4133 // Remove users private keys.
4134 $DB->delete_records('user_private_key', array('userid' => $user->id));
4136 // Remove users customised pages.
4137 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4139 // Delete user from $SESSION->bulk_users.
4140 if (isset($SESSION->bulk_users[$user->id])) {
4141 unset($SESSION->bulk_users[$user->id]);
4144 // Force logout - may fail if file based sessions used, sorry.
4145 \core\session\manager::kill_user_sessions($user->id);
4147 // Generate username from email address, or a fake email.
4148 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4149 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
4151 // Workaround for bulk deletes of users with the same email address.
4152 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4153 $delname++;
4156 // Mark internal user record as "deleted".
4157 $updateuser = new stdClass();
4158 $updateuser->id = $user->id;
4159 $updateuser->deleted = 1;
4160 $updateuser->username = $delname; // Remember it just in case.
4161 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4162 $updateuser->idnumber = ''; // Clear this field to free it up.
4163 $updateuser->picture = 0;
4164 $updateuser->timemodified = time();
4166 // Don't trigger update event, as user is being deleted.
4167 user_update_user($updateuser, false, false);
4169 // Delete all content associated with the user context, but not the context itself.
4170 $usercontext->delete_content();
4172 // Any plugin that needs to cleanup should register this event.
4173 // Trigger event.
4174 $event = \core\event\user_deleted::create(
4175 array(
4176 'objectid' => $user->id,
4177 'relateduserid' => $user->id,
4178 'context' => $usercontext,
4179 'other' => array(
4180 'username' => $user->username,
4181 'email' => $user->email,
4182 'idnumber' => $user->idnumber,
4183 'picture' => $user->picture,
4184 'mnethostid' => $user->mnethostid
4188 $event->add_record_snapshot('user', $olduser);
4189 $event->trigger();
4191 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4192 // should know about this updated property persisted to the user's table.
4193 $user->timemodified = $updateuser->timemodified;
4195 // Notify auth plugin - do not block the delete even when plugin fails.
4196 $authplugin = get_auth_plugin($user->auth);
4197 $authplugin->user_delete($user);
4199 return true;
4203 * Retrieve the guest user object.
4205 * @return stdClass A {@link $USER} object
4207 function guest_user() {
4208 global $CFG, $DB;
4210 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4211 $newuser->confirmed = 1;
4212 $newuser->lang = $CFG->lang;
4213 $newuser->lastip = getremoteaddr();
4216 return $newuser;
4220 * Authenticates a user against the chosen authentication mechanism
4222 * Given a username and password, this function looks them
4223 * up using the currently selected authentication mechanism,
4224 * and if the authentication is successful, it returns a
4225 * valid $user object from the 'user' table.
4227 * Uses auth_ functions from the currently active auth module
4229 * After authenticate_user_login() returns success, you will need to
4230 * log that the user has logged in, and call complete_user_login() to set
4231 * the session up.
4233 * Note: this function works only with non-mnet accounts!
4235 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4236 * @param string $password User's password
4237 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4238 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4239 * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4240 * @return stdClass|false A {@link $USER} object or false if error
4242 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4243 global $CFG, $DB;
4244 require_once("$CFG->libdir/authlib.php");
4246 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4247 // we have found the user
4249 } else if (!empty($CFG->authloginviaemail)) {
4250 if ($email = clean_param($username, PARAM_EMAIL)) {
4251 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4252 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4253 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4254 if (count($users) === 1) {
4255 // Use email for login only if unique.
4256 $user = reset($users);
4257 $user = get_complete_user_data('id', $user->id);
4258 $username = $user->username;
4260 unset($users);
4264 // Make sure this request came from the login form.
4265 if (!\core\session\manager::validate_login_token($logintoken)) {
4266 $failurereason = AUTH_LOGIN_FAILED;
4268 // Trigger login failed event.
4269 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4270 'other' => array('username' => $username, 'reason' => $failurereason)));
4271 $event->trigger();
4272 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
4273 return false;
4276 $authsenabled = get_enabled_auth_plugins();
4278 if ($user) {
4279 // Use manual if auth not set.
4280 $auth = empty($user->auth) ? 'manual' : $user->auth;
4282 if (in_array($user->auth, $authsenabled)) {
4283 $authplugin = get_auth_plugin($user->auth);
4284 $authplugin->pre_user_login_hook($user);
4287 if (!empty($user->suspended)) {
4288 $failurereason = AUTH_LOGIN_SUSPENDED;
4290 // Trigger login failed event.
4291 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4292 'other' => array('username' => $username, 'reason' => $failurereason)));
4293 $event->trigger();
4294 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4295 return false;
4297 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4298 // Legacy way to suspend user.
4299 $failurereason = AUTH_LOGIN_SUSPENDED;
4301 // Trigger login failed event.
4302 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4303 'other' => array('username' => $username, 'reason' => $failurereason)));
4304 $event->trigger();
4305 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4306 return false;
4308 $auths = array($auth);
4310 } else {
4311 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4312 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4313 $failurereason = AUTH_LOGIN_NOUSER;
4315 // Trigger login failed event.
4316 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4317 'reason' => $failurereason)));
4318 $event->trigger();
4319 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4320 return false;
4323 // User does not exist.
4324 $auths = $authsenabled;
4325 $user = new stdClass();
4326 $user->id = 0;
4329 if ($ignorelockout) {
4330 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4331 // or this function is called from a SSO script.
4332 } else if ($user->id) {
4333 // Verify login lockout after other ways that may prevent user login.
4334 if (login_is_lockedout($user)) {
4335 $failurereason = AUTH_LOGIN_LOCKOUT;
4337 // Trigger login failed event.
4338 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4339 'other' => array('username' => $username, 'reason' => $failurereason)));
4340 $event->trigger();
4342 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4343 return false;
4345 } else {
4346 // We can not lockout non-existing accounts.
4349 foreach ($auths as $auth) {
4350 $authplugin = get_auth_plugin($auth);
4352 // On auth fail fall through to the next plugin.
4353 if (!$authplugin->user_login($username, $password)) {
4354 continue;
4357 // Successful authentication.
4358 if ($user->id) {
4359 // User already exists in database.
4360 if (empty($user->auth)) {
4361 // For some reason auth isn't set yet.
4362 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4363 $user->auth = $auth;
4366 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4367 // the current hash algorithm while we have access to the user's password.
4368 update_internal_user_password($user, $password);
4370 if ($authplugin->is_synchronised_with_external()) {
4371 // Update user record from external DB.
4372 $user = update_user_record_by_id($user->id);
4374 } else {
4375 // The user is authenticated but user creation may be disabled.
4376 if (!empty($CFG->authpreventaccountcreation)) {
4377 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4379 // Trigger login failed event.
4380 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4381 'reason' => $failurereason)));
4382 $event->trigger();
4384 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4385 $_SERVER['HTTP_USER_AGENT']);
4386 return false;
4387 } else {
4388 $user = create_user_record($username, $password, $auth);
4392 $authplugin->sync_roles($user);
4394 foreach ($authsenabled as $hau) {
4395 $hauth = get_auth_plugin($hau);
4396 $hauth->user_authenticated_hook($user, $username, $password);
4399 if (empty($user->id)) {
4400 $failurereason = AUTH_LOGIN_NOUSER;
4401 // Trigger login failed event.
4402 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4403 'reason' => $failurereason)));
4404 $event->trigger();
4405 return false;
4408 if (!empty($user->suspended)) {
4409 // Just in case some auth plugin suspended account.
4410 $failurereason = AUTH_LOGIN_SUSPENDED;
4411 // Trigger login failed event.
4412 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4413 'other' => array('username' => $username, 'reason' => $failurereason)));
4414 $event->trigger();
4415 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4416 return false;
4419 login_attempt_valid($user);
4420 $failurereason = AUTH_LOGIN_OK;
4421 return $user;
4424 // Failed if all the plugins have failed.
4425 if (debugging('', DEBUG_ALL)) {
4426 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4429 if ($user->id) {
4430 login_attempt_failed($user);
4431 $failurereason = AUTH_LOGIN_FAILED;
4432 // Trigger login failed event.
4433 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4434 'other' => array('username' => $username, 'reason' => $failurereason)));
4435 $event->trigger();
4436 } else {
4437 $failurereason = AUTH_LOGIN_NOUSER;
4438 // Trigger login failed event.
4439 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4440 'reason' => $failurereason)));
4441 $event->trigger();
4444 return false;
4448 * Call to complete the user login process after authenticate_user_login()
4449 * has succeeded. It will setup the $USER variable and other required bits
4450 * and pieces.
4452 * NOTE:
4453 * - It will NOT log anything -- up to the caller to decide what to log.
4454 * - this function does not set any cookies any more!
4456 * @param stdClass $user
4457 * @return stdClass A {@link $USER} object - BC only, do not use
4459 function complete_user_login($user) {
4460 global $CFG, $DB, $USER, $SESSION;
4462 \core\session\manager::login_user($user);
4464 // Reload preferences from DB.
4465 unset($USER->preference);
4466 check_user_preferences_loaded($USER);
4468 // Update login times.
4469 update_user_login_times();
4471 // Extra session prefs init.
4472 set_login_session_preferences();
4474 // Trigger login event.
4475 $event = \core\event\user_loggedin::create(
4476 array(
4477 'userid' => $USER->id,
4478 'objectid' => $USER->id,
4479 'other' => array('username' => $USER->username),
4482 $event->trigger();
4484 // Queue migrating the messaging data, if we need to.
4485 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4486 // Check if there are any legacy messages to migrate.
4487 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4488 \core_message\task\migrate_message_data::queue_task($USER->id);
4489 } else {
4490 set_user_preference('core_message_migrate_data', true, $USER->id);
4494 if (isguestuser()) {
4495 // No need to continue when user is THE guest.
4496 return $USER;
4499 if (CLI_SCRIPT) {
4500 // We can redirect to password change URL only in browser.
4501 return $USER;
4504 // Select password change url.
4505 $userauth = get_auth_plugin($USER->auth);
4507 // Check whether the user should be changing password.
4508 if (get_user_preferences('auth_forcepasswordchange', false)) {
4509 if ($userauth->can_change_password()) {
4510 if ($changeurl = $userauth->change_password_url()) {
4511 redirect($changeurl);
4512 } else {
4513 require_once($CFG->dirroot . '/login/lib.php');
4514 $SESSION->wantsurl = core_login_get_return_url();
4515 redirect($CFG->wwwroot.'/login/change_password.php');
4517 } else {
4518 print_error('nopasswordchangeforced', 'auth');
4521 return $USER;
4525 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4527 * @param string $password String to check.
4528 * @return boolean True if the $password matches the format of an md5 sum.
4530 function password_is_legacy_hash($password) {
4531 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4535 * Compare password against hash stored in user object to determine if it is valid.
4537 * If necessary it also updates the stored hash to the current format.
4539 * @param stdClass $user (Password property may be updated).
4540 * @param string $password Plain text password.
4541 * @return bool True if password is valid.
4543 function validate_internal_user_password($user, $password) {
4544 global $CFG;
4546 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4547 // Internal password is not used at all, it can not validate.
4548 return false;
4551 // If hash isn't a legacy (md5) hash, validate using the library function.
4552 if (!password_is_legacy_hash($user->password)) {
4553 return password_verify($password, $user->password);
4556 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4557 // is valid we can then update it to the new algorithm.
4559 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4560 $validated = false;
4562 if ($user->password === md5($password.$sitesalt)
4563 or $user->password === md5($password)
4564 or $user->password === md5(addslashes($password).$sitesalt)
4565 or $user->password === md5(addslashes($password))) {
4566 // Note: we are intentionally using the addslashes() here because we
4567 // need to accept old password hashes of passwords with magic quotes.
4568 $validated = true;
4570 } else {
4571 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4572 $alt = 'passwordsaltalt'.$i;
4573 if (!empty($CFG->$alt)) {
4574 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4575 $validated = true;
4576 break;
4582 if ($validated) {
4583 // If the password matches the existing md5 hash, update to the
4584 // current hash algorithm while we have access to the user's password.
4585 update_internal_user_password($user, $password);
4588 return $validated;
4592 * Calculate hash for a plain text password.
4594 * @param string $password Plain text password to be hashed.
4595 * @param bool $fasthash If true, use a low cost factor when generating the hash
4596 * This is much faster to generate but makes the hash
4597 * less secure. It is used when lots of hashes need to
4598 * be generated quickly.
4599 * @return string The hashed password.
4601 * @throws moodle_exception If a problem occurs while generating the hash.
4603 function hash_internal_user_password($password, $fasthash = false) {
4604 global $CFG;
4606 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4607 $options = ($fasthash) ? array('cost' => 4) : array();
4609 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4611 if ($generatedhash === false || $generatedhash === null) {
4612 throw new moodle_exception('Failed to generate password hash.');
4615 return $generatedhash;
4619 * Update password hash in user object (if necessary).
4621 * The password is updated if:
4622 * 1. The password has changed (the hash of $user->password is different
4623 * to the hash of $password).
4624 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4625 * md5 algorithm).
4627 * Updating the password will modify the $user object and the database
4628 * record to use the current hashing algorithm.
4629 * It will remove Web Services user tokens too.
4631 * @param stdClass $user User object (password property may be updated).
4632 * @param string $password Plain text password.
4633 * @param bool $fasthash If true, use a low cost factor when generating the hash
4634 * This is much faster to generate but makes the hash
4635 * less secure. It is used when lots of hashes need to
4636 * be generated quickly.
4637 * @return bool Always returns true.
4639 function update_internal_user_password($user, $password, $fasthash = false) {
4640 global $CFG, $DB;
4642 // Figure out what the hashed password should be.
4643 if (!isset($user->auth)) {
4644 debugging('User record in update_internal_user_password() must include field auth',
4645 DEBUG_DEVELOPER);
4646 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4648 $authplugin = get_auth_plugin($user->auth);
4649 if ($authplugin->prevent_local_passwords()) {
4650 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4651 } else {
4652 $hashedpassword = hash_internal_user_password($password, $fasthash);
4655 $algorithmchanged = false;
4657 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4658 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4659 $passwordchanged = ($user->password !== $hashedpassword);
4661 } else if (isset($user->password)) {
4662 // If verification fails then it means the password has changed.
4663 $passwordchanged = !password_verify($password, $user->password);
4664 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4665 } else {
4666 // While creating new user, password in unset in $user object, to avoid
4667 // saving it with user_create()
4668 $passwordchanged = true;
4671 if ($passwordchanged || $algorithmchanged) {
4672 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4673 $user->password = $hashedpassword;
4675 // Trigger event.
4676 $user = $DB->get_record('user', array('id' => $user->id));
4677 \core\event\user_password_updated::create_from_user($user)->trigger();
4679 // Remove WS user tokens.
4680 if (!empty($CFG->passwordchangetokendeletion)) {
4681 require_once($CFG->dirroot.'/webservice/lib.php');
4682 webservice::delete_user_ws_tokens($user->id);
4686 return true;
4690 * Get a complete user record, which includes all the info in the user record.
4692 * Intended for setting as $USER session variable
4694 * @param string $field The user field to be checked for a given value.
4695 * @param string $value The value to match for $field.
4696 * @param int $mnethostid
4697 * @return mixed False, or A {@link $USER} object.
4699 function get_complete_user_data($field, $value, $mnethostid = null) {
4700 global $CFG, $DB;
4702 if (!$field || !$value) {
4703 return false;
4706 // Change the field to lowercase.
4707 $field = core_text::strtolower($field);
4709 // List of case insensitive fields.
4710 $caseinsensitivefields = ['username'];
4712 // Build the WHERE clause for an SQL query.
4713 $params = array('fieldval' => $value);
4715 // Do a case-insensitive query, if necessary.
4716 if (in_array($field, $caseinsensitivefields)) {
4717 $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4718 } else {
4719 $fieldselect = "$field = :fieldval";
4721 $constraints = "$fieldselect AND deleted <> 1";
4723 // If we are loading user data based on anything other than id,
4724 // we must also restrict our search based on mnet host.
4725 if ($field != 'id') {
4726 if (empty($mnethostid)) {
4727 // If empty, we restrict to local users.
4728 $mnethostid = $CFG->mnet_localhost_id;
4731 if (!empty($mnethostid)) {
4732 $params['mnethostid'] = $mnethostid;
4733 $constraints .= " AND mnethostid = :mnethostid";
4736 // Get all the basic user data.
4737 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4738 return false;
4741 // Get various settings and preferences.
4743 // Preload preference cache.
4744 check_user_preferences_loaded($user);
4746 // Load course enrolment related stuff.
4747 $user->lastcourseaccess = array(); // During last session.
4748 $user->currentcourseaccess = array(); // During current session.
4749 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4750 foreach ($lastaccesses as $lastaccess) {
4751 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4755 $sql = "SELECT g.id, g.courseid
4756 FROM {groups} g, {groups_members} gm
4757 WHERE gm.groupid=g.id AND gm.userid=?";
4759 // This is a special hack to speedup calendar display.
4760 $user->groupmember = array();
4761 if (!isguestuser($user)) {
4762 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4763 foreach ($groups as $group) {
4764 if (!array_key_exists($group->courseid, $user->groupmember)) {
4765 $user->groupmember[$group->courseid] = array();
4767 $user->groupmember[$group->courseid][$group->id] = $group->id;
4772 // Add cohort theme.
4773 if (!empty($CFG->allowcohortthemes)) {
4774 require_once($CFG->dirroot . '/cohort/lib.php');
4775 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4776 $user->cohorttheme = $cohorttheme;
4780 // Add the custom profile fields to the user record.
4781 $user->profile = array();
4782 if (!isguestuser($user)) {
4783 require_once($CFG->dirroot.'/user/profile/lib.php');
4784 profile_load_custom_fields($user);
4787 // Rewrite some variables if necessary.
4788 if (!empty($user->description)) {
4789 // No need to cart all of it around.
4790 $user->description = true;
4792 if (isguestuser($user)) {
4793 // Guest language always same as site.
4794 $user->lang = $CFG->lang;
4795 // Name always in current language.
4796 $user->firstname = get_string('guestuser');
4797 $user->lastname = ' ';
4800 return $user;
4804 * Validate a password against the configured password policy
4806 * @param string $password the password to be checked against the password policy
4807 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4808 * @return bool true if the password is valid according to the policy. false otherwise.
4810 function check_password_policy($password, &$errmsg) {
4811 global $CFG;
4813 if (empty($CFG->passwordpolicy)) {
4814 return true;
4817 $errmsg = '';
4818 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4819 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4822 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4823 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4826 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4827 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4830 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4831 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4834 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4835 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4837 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4838 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4841 if ($errmsg == '') {
4842 return true;
4843 } else {
4844 return false;
4850 * When logging in, this function is run to set certain preferences for the current SESSION.
4852 function set_login_session_preferences() {
4853 global $SESSION;
4855 $SESSION->justloggedin = true;
4857 unset($SESSION->lang);
4858 unset($SESSION->forcelang);
4859 unset($SESSION->load_navigation_admin);
4864 * Delete a course, including all related data from the database, and any associated files.
4866 * @param mixed $courseorid The id of the course or course object to delete.
4867 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4868 * @return bool true if all the removals succeeded. false if there were any failures. If this
4869 * method returns false, some of the removals will probably have succeeded, and others
4870 * failed, but you have no way of knowing which.
4872 function delete_course($courseorid, $showfeedback = true) {
4873 global $DB;
4875 if (is_object($courseorid)) {
4876 $courseid = $courseorid->id;
4877 $course = $courseorid;
4878 } else {
4879 $courseid = $courseorid;
4880 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4881 return false;
4884 $context = context_course::instance($courseid);
4886 // Frontpage course can not be deleted!!
4887 if ($courseid == SITEID) {
4888 return false;
4891 // Allow plugins to use this course before we completely delete it.
4892 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
4893 foreach ($pluginsfunction as $plugintype => $plugins) {
4894 foreach ($plugins as $pluginfunction) {
4895 $pluginfunction($course);
4900 // Make the course completely empty.
4901 remove_course_contents($courseid, $showfeedback);
4903 // Delete the course and related context instance.
4904 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4906 $DB->delete_records("course", array("id" => $courseid));
4907 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4909 // Reset all course related caches here.
4910 if (class_exists('format_base', false)) {
4911 format_base::reset_course_cache($courseid);
4914 // Trigger a course deleted event.
4915 $event = \core\event\course_deleted::create(array(
4916 'objectid' => $course->id,
4917 'context' => $context,
4918 'other' => array(
4919 'shortname' => $course->shortname,
4920 'fullname' => $course->fullname,
4921 'idnumber' => $course->idnumber
4924 $event->add_record_snapshot('course', $course);
4925 $event->trigger();
4927 return true;
4931 * Clear a course out completely, deleting all content but don't delete the course itself.
4933 * This function does not verify any permissions.
4935 * Please note this function also deletes all user enrolments,
4936 * enrolment instances and role assignments by default.
4938 * $options:
4939 * - 'keep_roles_and_enrolments' - false by default
4940 * - 'keep_groups_and_groupings' - false by default
4942 * @param int $courseid The id of the course that is being deleted
4943 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4944 * @param array $options extra options
4945 * @return bool true if all the removals succeeded. false if there were any failures. If this
4946 * method returns false, some of the removals will probably have succeeded, and others
4947 * failed, but you have no way of knowing which.
4949 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4950 global $CFG, $DB, $OUTPUT;
4952 require_once($CFG->libdir.'/badgeslib.php');
4953 require_once($CFG->libdir.'/completionlib.php');
4954 require_once($CFG->libdir.'/questionlib.php');
4955 require_once($CFG->libdir.'/gradelib.php');
4956 require_once($CFG->dirroot.'/group/lib.php');
4957 require_once($CFG->dirroot.'/comment/lib.php');
4958 require_once($CFG->dirroot.'/rating/lib.php');
4959 require_once($CFG->dirroot.'/notes/lib.php');
4961 // Handle course badges.
4962 badges_handle_course_deletion($courseid);
4964 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4965 $strdeleted = get_string('deleted').' - ';
4967 // Some crazy wishlist of stuff we should skip during purging of course content.
4968 $options = (array)$options;
4970 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
4971 $coursecontext = context_course::instance($courseid);
4972 $fs = get_file_storage();
4974 // Delete course completion information, this has to be done before grades and enrols.
4975 $cc = new completion_info($course);
4976 $cc->clear_criteria();
4977 if ($showfeedback) {
4978 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4981 // Remove all data from gradebook - this needs to be done before course modules
4982 // because while deleting this information, the system may need to reference
4983 // the course modules that own the grades.
4984 remove_course_grades($courseid, $showfeedback);
4985 remove_grade_letters($coursecontext, $showfeedback);
4987 // Delete course blocks in any all child contexts,
4988 // they may depend on modules so delete them first.
4989 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4990 foreach ($childcontexts as $childcontext) {
4991 blocks_delete_all_for_context($childcontext->id);
4993 unset($childcontexts);
4994 blocks_delete_all_for_context($coursecontext->id);
4995 if ($showfeedback) {
4996 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4999 // Get the list of all modules that are properly installed.
5000 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5002 // Delete every instance of every module,
5003 // this has to be done before deleting of course level stuff.
5004 $locations = core_component::get_plugin_list('mod');
5005 foreach ($locations as $modname => $moddir) {
5006 if ($modname === 'NEWMODULE') {
5007 continue;
5009 if (array_key_exists($modname, $allmodules)) {
5010 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5011 FROM {".$modname."} m
5012 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5013 WHERE m.course = :courseid";
5014 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5015 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5017 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5018 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5019 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
5021 if ($instances) {
5022 foreach ($instances as $cm) {
5023 if ($cm->id) {
5024 // Delete activity context questions and question categories.
5025 question_delete_activity($cm, $showfeedback);
5026 // Notify the competency subsystem.
5027 \core_competency\api::hook_course_module_deleted($cm);
5029 if (function_exists($moddelete)) {
5030 // This purges all module data in related tables, extra user prefs, settings, etc.
5031 $moddelete($cm->modinstance);
5032 } else {
5033 // NOTE: we should not allow installation of modules with missing delete support!
5034 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5035 $DB->delete_records($modname, array('id' => $cm->modinstance));
5038 if ($cm->id) {
5039 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5040 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5041 $DB->delete_records('course_modules', array('id' => $cm->id));
5045 if (function_exists($moddeletecourse)) {
5046 // Execute optional course cleanup callback. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
5047 debugging("Callback delete_course is deprecated. Function $moddeletecourse should be converted " .
5048 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER);
5049 $moddeletecourse($course, $showfeedback);
5051 if ($instances and $showfeedback) {
5052 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5054 } else {
5055 // Ooops, this module is not properly installed, force-delete it in the next block.
5059 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5061 // Delete completion defaults.
5062 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5064 // Remove all data from availability and completion tables that is associated
5065 // with course-modules belonging to this course. Note this is done even if the
5066 // features are not enabled now, in case they were enabled previously.
5067 $DB->delete_records_select('course_modules_completion',
5068 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5069 array($courseid));
5071 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5072 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5073 $allmodulesbyid = array_flip($allmodules);
5074 foreach ($cms as $cm) {
5075 if (array_key_exists($cm->module, $allmodulesbyid)) {
5076 try {
5077 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5078 } catch (Exception $e) {
5079 // Ignore weird or missing table problems.
5082 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5083 $DB->delete_records('course_modules', array('id' => $cm->id));
5086 if ($showfeedback) {
5087 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5090 // Cleanup the rest of plugins. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
5091 $cleanuplugintypes = array('report', 'coursereport', 'format');
5092 $callbacks = get_plugins_with_function('delete_course', 'lib.php');
5093 foreach ($cleanuplugintypes as $type) {
5094 if (!empty($callbacks[$type])) {
5095 foreach ($callbacks[$type] as $pluginfunction) {
5096 debugging("Callback delete_course is deprecated. Function $pluginfunction should be converted " .
5097 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER);
5098 $pluginfunction($course->id, $showfeedback);
5100 if ($showfeedback) {
5101 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5106 // Delete questions and question categories.
5107 question_delete_course($course, $showfeedback);
5108 if ($showfeedback) {
5109 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5112 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5113 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5114 foreach ($childcontexts as $childcontext) {
5115 $childcontext->delete();
5117 unset($childcontexts);
5119 // Remove all roles and enrolments by default.
5120 if (empty($options['keep_roles_and_enrolments'])) {
5121 // This hack is used in restore when deleting contents of existing course.
5122 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5123 enrol_course_delete($course);
5124 if ($showfeedback) {
5125 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5129 // Delete any groups, removing members and grouping/course links first.
5130 if (empty($options['keep_groups_and_groupings'])) {
5131 groups_delete_groupings($course->id, $showfeedback);
5132 groups_delete_groups($course->id, $showfeedback);
5135 // Filters be gone!
5136 filter_delete_all_for_context($coursecontext->id);
5138 // Notes, you shall not pass!
5139 note_delete_all($course->id);
5141 // Die comments!
5142 comment::delete_comments($coursecontext->id);
5144 // Ratings are history too.
5145 $delopt = new stdclass();
5146 $delopt->contextid = $coursecontext->id;
5147 $rm = new rating_manager();
5148 $rm->delete_ratings($delopt);
5150 // Delete course tags.
5151 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5153 // Notify the competency subsystem.
5154 \core_competency\api::hook_course_deleted($course);
5156 // Delete calendar events.
5157 $DB->delete_records('event', array('courseid' => $course->id));
5158 $fs->delete_area_files($coursecontext->id, 'calendar');
5160 // Delete all related records in other core tables that may have a courseid
5161 // This array stores the tables that need to be cleared, as
5162 // table_name => column_name that contains the course id.
5163 $tablestoclear = array(
5164 'backup_courses' => 'courseid', // Scheduled backup stuff.
5165 'user_lastaccess' => 'courseid', // User access info.
5167 foreach ($tablestoclear as $table => $col) {
5168 $DB->delete_records($table, array($col => $course->id));
5171 // Delete all course backup files.
5172 $fs->delete_area_files($coursecontext->id, 'backup');
5174 // Cleanup course record - remove links to deleted stuff.
5175 $oldcourse = new stdClass();
5176 $oldcourse->id = $course->id;
5177 $oldcourse->summary = '';
5178 $oldcourse->cacherev = 0;
5179 $oldcourse->legacyfiles = 0;
5180 if (!empty($options['keep_groups_and_groupings'])) {
5181 $oldcourse->defaultgroupingid = 0;
5183 $DB->update_record('course', $oldcourse);
5185 // Delete course sections.
5186 $DB->delete_records('course_sections', array('course' => $course->id));
5188 // Delete legacy, section and any other course files.
5189 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5191 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5192 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5193 // Easy, do not delete the context itself...
5194 $coursecontext->delete_content();
5195 } else {
5196 // Hack alert!!!!
5197 // We can not drop all context stuff because it would bork enrolments and roles,
5198 // there might be also files used by enrol plugins...
5201 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5202 // also some non-standard unsupported plugins may try to store something there.
5203 fulldelete($CFG->dataroot.'/'.$course->id);
5205 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5206 $cachemodinfo = cache::make('core', 'coursemodinfo');
5207 $cachemodinfo->delete($courseid);
5209 // Trigger a course content deleted event.
5210 $event = \core\event\course_content_deleted::create(array(
5211 'objectid' => $course->id,
5212 'context' => $coursecontext,
5213 'other' => array('shortname' => $course->shortname,
5214 'fullname' => $course->fullname,
5215 'options' => $options) // Passing this for legacy reasons.
5217 $event->add_record_snapshot('course', $course);
5218 $event->trigger();
5220 return true;
5224 * Change dates in module - used from course reset.
5226 * @param string $modname forum, assignment, etc
5227 * @param array $fields array of date fields from mod table
5228 * @param int $timeshift time difference
5229 * @param int $courseid
5230 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5231 * @return bool success
5233 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5234 global $CFG, $DB;
5235 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5237 $return = true;
5238 $params = array($timeshift, $courseid);
5239 foreach ($fields as $field) {
5240 $updatesql = "UPDATE {".$modname."}
5241 SET $field = $field + ?
5242 WHERE course=? AND $field<>0";
5243 if ($modid) {
5244 $updatesql .= ' AND id=?';
5245 $params[] = $modid;
5247 $return = $DB->execute($updatesql, $params) && $return;
5250 return $return;
5254 * This function will empty a course of user data.
5255 * It will retain the activities and the structure of the course.
5257 * @param object $data an object containing all the settings including courseid (without magic quotes)
5258 * @return array status array of array component, item, error
5260 function reset_course_userdata($data) {
5261 global $CFG, $DB;
5262 require_once($CFG->libdir.'/gradelib.php');
5263 require_once($CFG->libdir.'/completionlib.php');
5264 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5265 require_once($CFG->dirroot.'/group/lib.php');
5267 $data->courseid = $data->id;
5268 $context = context_course::instance($data->courseid);
5270 $eventparams = array(
5271 'context' => $context,
5272 'courseid' => $data->id,
5273 'other' => array(
5274 'reset_options' => (array) $data
5277 $event = \core\event\course_reset_started::create($eventparams);
5278 $event->trigger();
5280 // Calculate the time shift of dates.
5281 if (!empty($data->reset_start_date)) {
5282 // Time part of course startdate should be zero.
5283 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5284 } else {
5285 $data->timeshift = 0;
5288 // Result array: component, item, error.
5289 $status = array();
5291 // Start the resetting.
5292 $componentstr = get_string('general');
5294 // Move the course start time.
5295 if (!empty($data->reset_start_date) and $data->timeshift) {
5296 // Change course start data.
5297 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5298 // Update all course and group events - do not move activity events.
5299 $updatesql = "UPDATE {event}
5300 SET timestart = timestart + ?
5301 WHERE courseid=? AND instance=0";
5302 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5304 // Update any date activity restrictions.
5305 if ($CFG->enableavailability) {
5306 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5309 // Update completion expected dates.
5310 if ($CFG->enablecompletion) {
5311 $modinfo = get_fast_modinfo($data->courseid);
5312 $changed = false;
5313 foreach ($modinfo->get_cms() as $cm) {
5314 if ($cm->completion && !empty($cm->completionexpected)) {
5315 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5316 array('id' => $cm->id));
5317 $changed = true;
5321 // Clear course cache if changes made.
5322 if ($changed) {
5323 rebuild_course_cache($data->courseid, true);
5326 // Update course date completion criteria.
5327 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5330 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5333 if (!empty($data->reset_end_date)) {
5334 // If the user set a end date value respect it.
5335 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5336 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5337 // If there is a time shift apply it to the end date as well.
5338 $enddate = $data->reset_end_date_old + $data->timeshift;
5339 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5342 if (!empty($data->reset_events)) {
5343 $DB->delete_records('event', array('courseid' => $data->courseid));
5344 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5347 if (!empty($data->reset_notes)) {
5348 require_once($CFG->dirroot.'/notes/lib.php');
5349 note_delete_all($data->courseid);
5350 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5353 if (!empty($data->delete_blog_associations)) {
5354 require_once($CFG->dirroot.'/blog/lib.php');
5355 blog_remove_associations_for_course($data->courseid);
5356 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5359 if (!empty($data->reset_completion)) {
5360 // Delete course and activity completion information.
5361 $course = $DB->get_record('course', array('id' => $data->courseid));
5362 $cc = new completion_info($course);
5363 $cc->delete_all_completion_data();
5364 $status[] = array('component' => $componentstr,
5365 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5368 if (!empty($data->reset_competency_ratings)) {
5369 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5370 $status[] = array('component' => $componentstr,
5371 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5374 $componentstr = get_string('roles');
5376 if (!empty($data->reset_roles_overrides)) {
5377 $children = $context->get_child_contexts();
5378 foreach ($children as $child) {
5379 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5381 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5382 // Force refresh for logged in users.
5383 $context->mark_dirty();
5384 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5387 if (!empty($data->reset_roles_local)) {
5388 $children = $context->get_child_contexts();
5389 foreach ($children as $child) {
5390 role_unassign_all(array('contextid' => $child->id));
5392 // Force refresh for logged in users.
5393 $context->mark_dirty();
5394 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5397 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5398 $data->unenrolled = array();
5399 if (!empty($data->unenrol_users)) {
5400 $plugins = enrol_get_plugins(true);
5401 $instances = enrol_get_instances($data->courseid, true);
5402 foreach ($instances as $key => $instance) {
5403 if (!isset($plugins[$instance->enrol])) {
5404 unset($instances[$key]);
5405 continue;
5409 foreach ($data->unenrol_users as $withroleid) {
5410 if ($withroleid) {
5411 $sql = "SELECT ue.*
5412 FROM {user_enrolments} ue
5413 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5414 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5415 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5416 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5418 } else {
5419 // Without any role assigned at course context.
5420 $sql = "SELECT ue.*
5421 FROM {user_enrolments} ue
5422 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5423 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5424 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5425 WHERE ra.id IS null";
5426 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5429 $rs = $DB->get_recordset_sql($sql, $params);
5430 foreach ($rs as $ue) {
5431 if (!isset($instances[$ue->enrolid])) {
5432 continue;
5434 $instance = $instances[$ue->enrolid];
5435 $plugin = $plugins[$instance->enrol];
5436 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5437 continue;
5440 $plugin->unenrol_user($instance, $ue->userid);
5441 $data->unenrolled[$ue->userid] = $ue->userid;
5443 $rs->close();
5446 if (!empty($data->unenrolled)) {
5447 $status[] = array(
5448 'component' => $componentstr,
5449 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5450 'error' => false
5454 $componentstr = get_string('groups');
5456 // Remove all group members.
5457 if (!empty($data->reset_groups_members)) {
5458 groups_delete_group_members($data->courseid);
5459 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5462 // Remove all groups.
5463 if (!empty($data->reset_groups_remove)) {
5464 groups_delete_groups($data->courseid, false);
5465 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5468 // Remove all grouping members.
5469 if (!empty($data->reset_groupings_members)) {
5470 groups_delete_groupings_groups($data->courseid, false);
5471 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5474 // Remove all groupings.
5475 if (!empty($data->reset_groupings_remove)) {
5476 groups_delete_groupings($data->courseid, false);
5477 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5480 // Look in every instance of every module for data to delete.
5481 $unsupportedmods = array();
5482 if ($allmods = $DB->get_records('modules') ) {
5483 foreach ($allmods as $mod) {
5484 $modname = $mod->name;
5485 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5486 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5487 if (file_exists($modfile)) {
5488 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5489 continue; // Skip mods with no instances.
5491 include_once($modfile);
5492 if (function_exists($moddeleteuserdata)) {
5493 $modstatus = $moddeleteuserdata($data);
5494 if (is_array($modstatus)) {
5495 $status = array_merge($status, $modstatus);
5496 } else {
5497 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5499 } else {
5500 $unsupportedmods[] = $mod;
5502 } else {
5503 debugging('Missing lib.php in '.$modname.' module!');
5505 // Update calendar events for all modules.
5506 course_module_bulk_update_calendar_events($modname, $data->courseid);
5510 // Mention unsupported mods.
5511 if (!empty($unsupportedmods)) {
5512 foreach ($unsupportedmods as $mod) {
5513 $status[] = array(
5514 'component' => get_string('modulenameplural', $mod->name),
5515 'item' => '',
5516 'error' => get_string('resetnotimplemented')
5521 $componentstr = get_string('gradebook', 'grades');
5522 // Reset gradebook,.
5523 if (!empty($data->reset_gradebook_items)) {
5524 remove_course_grades($data->courseid, false);
5525 grade_grab_course_grades($data->courseid);
5526 grade_regrade_final_grades($data->courseid);
5527 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5529 } else if (!empty($data->reset_gradebook_grades)) {
5530 grade_course_reset($data->courseid);
5531 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5533 // Reset comments.
5534 if (!empty($data->reset_comments)) {
5535 require_once($CFG->dirroot.'/comment/lib.php');
5536 comment::reset_course_page_comments($context);
5539 $event = \core\event\course_reset_ended::create($eventparams);
5540 $event->trigger();
5542 return $status;
5546 * Generate an email processing address.
5548 * @param int $modid
5549 * @param string $modargs
5550 * @return string Returns email processing address
5552 function generate_email_processing_address($modid, $modargs) {
5553 global $CFG;
5555 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5556 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5562 * @todo Finish documenting this function
5564 * @param string $modargs
5565 * @param string $body Currently unused
5567 function moodle_process_email($modargs, $body) {
5568 global $DB;
5570 // The first char should be an unencoded letter. We'll take this as an action.
5571 switch ($modargs{0}) {
5572 case 'B': { // Bounce.
5573 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5574 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5575 // Check the half md5 of their email.
5576 $md5check = substr(md5($user->email), 0, 16);
5577 if ($md5check == substr($modargs, -16)) {
5578 set_bounce_count($user);
5580 // Else maybe they've already changed it?
5583 break;
5584 // Maybe more later?
5588 // CORRESPONDENCE.
5591 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5593 * @param string $action 'get', 'buffer', 'close' or 'flush'
5594 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5596 function get_mailer($action='get') {
5597 global $CFG;
5599 /** @var moodle_phpmailer $mailer */
5600 static $mailer = null;
5601 static $counter = 0;
5603 if (!isset($CFG->smtpmaxbulk)) {
5604 $CFG->smtpmaxbulk = 1;
5607 if ($action == 'get') {
5608 $prevkeepalive = false;
5610 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5611 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5612 $counter++;
5613 // Reset the mailer.
5614 $mailer->Priority = 3;
5615 $mailer->CharSet = 'UTF-8'; // Our default.
5616 $mailer->ContentType = "text/plain";
5617 $mailer->Encoding = "8bit";
5618 $mailer->From = "root@localhost";
5619 $mailer->FromName = "Root User";
5620 $mailer->Sender = "";
5621 $mailer->Subject = "";
5622 $mailer->Body = "";
5623 $mailer->AltBody = "";
5624 $mailer->ConfirmReadingTo = "";
5626 $mailer->clearAllRecipients();
5627 $mailer->clearReplyTos();
5628 $mailer->clearAttachments();
5629 $mailer->clearCustomHeaders();
5630 return $mailer;
5633 $prevkeepalive = $mailer->SMTPKeepAlive;
5634 get_mailer('flush');
5637 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5638 $mailer = new moodle_phpmailer();
5640 $counter = 1;
5642 if ($CFG->smtphosts == 'qmail') {
5643 // Use Qmail system.
5644 $mailer->isQmail();
5646 } else if (empty($CFG->smtphosts)) {
5647 // Use PHP mail() = sendmail.
5648 $mailer->isMail();
5650 } else {
5651 // Use SMTP directly.
5652 $mailer->isSMTP();
5653 if (!empty($CFG->debugsmtp)) {
5654 $mailer->SMTPDebug = 3;
5656 // Specify main and backup servers.
5657 $mailer->Host = $CFG->smtphosts;
5658 // Specify secure connection protocol.
5659 $mailer->SMTPSecure = $CFG->smtpsecure;
5660 // Use previous keepalive.
5661 $mailer->SMTPKeepAlive = $prevkeepalive;
5663 if ($CFG->smtpuser) {
5664 // Use SMTP authentication.
5665 $mailer->SMTPAuth = true;
5666 $mailer->Username = $CFG->smtpuser;
5667 $mailer->Password = $CFG->smtppass;
5671 return $mailer;
5674 $nothing = null;
5676 // Keep smtp session open after sending.
5677 if ($action == 'buffer') {
5678 if (!empty($CFG->smtpmaxbulk)) {
5679 get_mailer('flush');
5680 $m = get_mailer();
5681 if ($m->Mailer == 'smtp') {
5682 $m->SMTPKeepAlive = true;
5685 return $nothing;
5688 // Close smtp session, but continue buffering.
5689 if ($action == 'flush') {
5690 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5691 if (!empty($mailer->SMTPDebug)) {
5692 echo '<pre>'."\n";
5694 $mailer->SmtpClose();
5695 if (!empty($mailer->SMTPDebug)) {
5696 echo '</pre>';
5699 return $nothing;
5702 // Close smtp session, do not buffer anymore.
5703 if ($action == 'close') {
5704 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5705 get_mailer('flush');
5706 $mailer->SMTPKeepAlive = false;
5708 $mailer = null; // Better force new instance.
5709 return $nothing;
5714 * A helper function to test for email diversion
5716 * @param string $email
5717 * @return bool Returns true if the email should be diverted
5719 function email_should_be_diverted($email) {
5720 global $CFG;
5722 if (empty($CFG->divertallemailsto)) {
5723 return false;
5726 if (empty($CFG->divertallemailsexcept)) {
5727 return true;
5730 $patterns = array_map('trim', explode(',', $CFG->divertallemailsexcept));
5731 foreach ($patterns as $pattern) {
5732 if (preg_match("/$pattern/", $email)) {
5733 return false;
5737 return true;
5741 * Generate a unique email Message-ID using the moodle domain and install path
5743 * @param string $localpart An optional unique message id prefix.
5744 * @return string The formatted ID ready for appending to the email headers.
5746 function generate_email_messageid($localpart = null) {
5747 global $CFG;
5749 $urlinfo = parse_url($CFG->wwwroot);
5750 $base = '@' . $urlinfo['host'];
5752 // If multiple moodles are on the same domain we want to tell them
5753 // apart so we add the install path to the local part. This means
5754 // that the id local part should never contain a / character so
5755 // we can correctly parse the id to reassemble the wwwroot.
5756 if (isset($urlinfo['path'])) {
5757 $base = $urlinfo['path'] . $base;
5760 if (empty($localpart)) {
5761 $localpart = uniqid('', true);
5764 // Because we may have an option /installpath suffix to the local part
5765 // of the id we need to escape any / chars which are in the $localpart.
5766 $localpart = str_replace('/', '%2F', $localpart);
5768 return '<' . $localpart . $base . '>';
5772 * Send an email to a specified user
5774 * @param stdClass $user A {@link $USER} object
5775 * @param stdClass $from A {@link $USER} object
5776 * @param string $subject plain text subject line of the email
5777 * @param string $messagetext plain text version of the message
5778 * @param string $messagehtml complete html version of the message (optional)
5779 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5780 * @param string $attachname the name of the file (extension indicates MIME)
5781 * @param bool $usetrueaddress determines whether $from email address should
5782 * be sent out. Will be overruled by user profile setting for maildisplay
5783 * @param string $replyto Email address to reply to
5784 * @param string $replytoname Name of reply to recipient
5785 * @param int $wordwrapwidth custom word wrap width, default 79
5786 * @return bool Returns true if mail was sent OK and false if there was an error.
5788 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5789 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5791 global $CFG, $PAGE, $SITE;
5793 if (empty($user) or empty($user->id)) {
5794 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5795 return false;
5798 if (empty($user->email)) {
5799 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5800 return false;
5803 if (!empty($user->deleted)) {
5804 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5805 return false;
5808 if (defined('BEHAT_SITE_RUNNING')) {
5809 // Fake email sending in behat.
5810 return true;
5813 if (!empty($CFG->noemailever)) {
5814 // Hidden setting for development sites, set in config.php if needed.
5815 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5816 return true;
5819 if (email_should_be_diverted($user->email)) {
5820 $subject = "[DIVERTED {$user->email}] $subject";
5821 $user = clone($user);
5822 $user->email = $CFG->divertallemailsto;
5825 // Skip mail to suspended users.
5826 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5827 return true;
5830 if (!validate_email($user->email)) {
5831 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5832 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5833 return false;
5836 if (over_bounce_threshold($user)) {
5837 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5838 return false;
5841 // TLD .invalid is specifically reserved for invalid domain names.
5842 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5843 if (substr($user->email, -8) == '.invalid') {
5844 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5845 return true; // This is not an error.
5848 // If the user is a remote mnet user, parse the email text for URL to the
5849 // wwwroot and modify the url to direct the user's browser to login at their
5850 // home site (identity provider - idp) before hitting the link itself.
5851 if (is_mnet_remote_user($user)) {
5852 require_once($CFG->dirroot.'/mnet/lib.php');
5854 $jumpurl = mnet_get_idp_jump_url($user);
5855 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5857 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5858 $callback,
5859 $messagetext);
5860 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5861 $callback,
5862 $messagehtml);
5864 $mail = get_mailer();
5866 if (!empty($mail->SMTPDebug)) {
5867 echo '<pre>' . "\n";
5870 $temprecipients = array();
5871 $tempreplyto = array();
5873 // Make sure that we fall back onto some reasonable no-reply address.
5874 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
5875 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
5877 if (!validate_email($noreplyaddress)) {
5878 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
5879 $noreplyaddress = $noreplyaddressdefault;
5882 // Make up an email address for handling bounces.
5883 if (!empty($CFG->handlebounces)) {
5884 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5885 $mail->Sender = generate_email_processing_address(0, $modargs);
5886 } else {
5887 $mail->Sender = $noreplyaddress;
5890 // Make sure that the explicit replyto is valid, fall back to the implicit one.
5891 if (!empty($replyto) && !validate_email($replyto)) {
5892 debugging('email_to_user: Invalid replyto-email '.s($replyto));
5893 $replyto = $noreplyaddress;
5896 if (is_string($from)) { // So we can pass whatever we want if there is need.
5897 $mail->From = $noreplyaddress;
5898 $mail->FromName = $from;
5899 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
5900 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
5901 // in a course with the sender.
5902 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
5903 if (!validate_email($from->email)) {
5904 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
5905 // Better not to use $noreplyaddress in this case.
5906 return false;
5908 $mail->From = $from->email;
5909 $fromdetails = new stdClass();
5910 $fromdetails->name = fullname($from);
5911 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5912 $fromdetails->siteshortname = format_string($SITE->shortname);
5913 $fromstring = $fromdetails->name;
5914 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
5915 $fromstring = get_string('emailvia', 'core', $fromdetails);
5917 $mail->FromName = $fromstring;
5918 if (empty($replyto)) {
5919 $tempreplyto[] = array($from->email, fullname($from));
5921 } else {
5922 $mail->From = $noreplyaddress;
5923 $fromdetails = new stdClass();
5924 $fromdetails->name = fullname($from);
5925 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5926 $fromdetails->siteshortname = format_string($SITE->shortname);
5927 $fromstring = $fromdetails->name;
5928 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
5929 $fromstring = get_string('emailvia', 'core', $fromdetails);
5931 $mail->FromName = $fromstring;
5932 if (empty($replyto)) {
5933 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
5937 if (!empty($replyto)) {
5938 $tempreplyto[] = array($replyto, $replytoname);
5941 $temprecipients[] = array($user->email, fullname($user));
5943 // Set word wrap.
5944 $mail->WordWrap = $wordwrapwidth;
5946 if (!empty($from->customheaders)) {
5947 // Add custom headers.
5948 if (is_array($from->customheaders)) {
5949 foreach ($from->customheaders as $customheader) {
5950 $mail->addCustomHeader($customheader);
5952 } else {
5953 $mail->addCustomHeader($from->customheaders);
5957 // If the X-PHP-Originating-Script email header is on then also add an additional
5958 // header with details of where exactly in moodle the email was triggered from,
5959 // either a call to message_send() or to email_to_user().
5960 if (ini_get('mail.add_x_header')) {
5962 $stack = debug_backtrace(false);
5963 $origin = $stack[0];
5965 foreach ($stack as $depth => $call) {
5966 if ($call['function'] == 'message_send') {
5967 $origin = $call;
5971 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
5972 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
5973 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
5976 if (!empty($from->priority)) {
5977 $mail->Priority = $from->priority;
5980 $renderer = $PAGE->get_renderer('core');
5981 $context = array(
5982 'sitefullname' => $SITE->fullname,
5983 'siteshortname' => $SITE->shortname,
5984 'sitewwwroot' => $CFG->wwwroot,
5985 'subject' => $subject,
5986 'to' => $user->email,
5987 'toname' => fullname($user),
5988 'from' => $mail->From,
5989 'fromname' => $mail->FromName,
5991 if (!empty($tempreplyto[0])) {
5992 $context['replyto'] = $tempreplyto[0][0];
5993 $context['replytoname'] = $tempreplyto[0][1];
5995 if ($user->id > 0) {
5996 $context['touserid'] = $user->id;
5997 $context['tousername'] = $user->username;
6000 if (!empty($user->mailformat) && $user->mailformat == 1) {
6001 // Only process html templates if the user preferences allow html email.
6003 if ($messagehtml) {
6004 // If html has been given then pass it through the template.
6005 $context['body'] = $messagehtml;
6006 $messagehtml = $renderer->render_from_template('core/email_html', $context);
6008 } else {
6009 // If no html has been given, BUT there is an html wrapping template then
6010 // auto convert the text to html and then wrap it.
6011 $autohtml = trim(text_to_html($messagetext));
6012 $context['body'] = $autohtml;
6013 $temphtml = $renderer->render_from_template('core/email_html', $context);
6014 if ($autohtml != $temphtml) {
6015 $messagehtml = $temphtml;
6020 $context['body'] = $messagetext;
6021 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
6022 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
6023 $messagetext = $renderer->render_from_template('core/email_text', $context);
6025 // Autogenerate a MessageID if it's missing.
6026 if (empty($mail->MessageID)) {
6027 $mail->MessageID = generate_email_messageid();
6030 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6031 // Don't ever send HTML to users who don't want it.
6032 $mail->isHTML(true);
6033 $mail->Encoding = 'quoted-printable';
6034 $mail->Body = $messagehtml;
6035 $mail->AltBody = "\n$messagetext\n";
6036 } else {
6037 $mail->IsHTML(false);
6038 $mail->Body = "\n$messagetext\n";
6041 if ($attachment && $attachname) {
6042 if (preg_match( "~\\.\\.~" , $attachment )) {
6043 // Security check for ".." in dir path.
6044 $supportuser = core_user::get_support_user();
6045 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6046 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6047 } else {
6048 require_once($CFG->libdir.'/filelib.php');
6049 $mimetype = mimeinfo('type', $attachname);
6051 $attachmentpath = $attachment;
6053 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6054 $attachpath = str_replace('\\', '/', $attachmentpath);
6055 // Make sure both variables are normalised before comparing.
6056 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
6058 // If the attachment is a full path to a file in the tempdir, use it as is,
6059 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6060 if (strpos($attachpath, $temppath) !== 0) {
6061 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
6064 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
6068 // Check if the email should be sent in an other charset then the default UTF-8.
6069 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6071 // Use the defined site mail charset or eventually the one preferred by the recipient.
6072 $charset = $CFG->sitemailcharset;
6073 if (!empty($CFG->allowusermailcharset)) {
6074 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6075 $charset = $useremailcharset;
6079 // Convert all the necessary strings if the charset is supported.
6080 $charsets = get_list_of_charsets();
6081 unset($charsets['UTF-8']);
6082 if (in_array($charset, $charsets)) {
6083 $mail->CharSet = $charset;
6084 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6085 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6086 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6087 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6089 foreach ($temprecipients as $key => $values) {
6090 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6092 foreach ($tempreplyto as $key => $values) {
6093 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6098 foreach ($temprecipients as $values) {
6099 $mail->addAddress($values[0], $values[1]);
6101 foreach ($tempreplyto as $values) {
6102 $mail->addReplyTo($values[0], $values[1]);
6105 if ($mail->send()) {
6106 set_send_count($user);
6107 if (!empty($mail->SMTPDebug)) {
6108 echo '</pre>';
6110 return true;
6111 } else {
6112 // Trigger event for failing to send email.
6113 $event = \core\event\email_failed::create(array(
6114 'context' => context_system::instance(),
6115 'userid' => $from->id,
6116 'relateduserid' => $user->id,
6117 'other' => array(
6118 'subject' => $subject,
6119 'message' => $messagetext,
6120 'errorinfo' => $mail->ErrorInfo
6123 $event->trigger();
6124 if (CLI_SCRIPT) {
6125 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6127 if (!empty($mail->SMTPDebug)) {
6128 echo '</pre>';
6130 return false;
6135 * Check to see if a user's real email address should be used for the "From" field.
6137 * @param object $from The user object for the user we are sending the email from.
6138 * @param object $user The user object that we are sending the email to.
6139 * @param array $unused No longer used.
6140 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6142 function can_send_from_real_email_address($from, $user, $unused = null) {
6143 global $CFG;
6144 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6145 return false;
6147 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6148 // Email is in the list of allowed domains for sending email,
6149 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6150 // in a course with the sender.
6151 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6152 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6153 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6154 && enrol_get_shared_courses($user, $from, false, true)))) {
6155 return true;
6157 return false;
6161 * Generate a signoff for emails based on support settings
6163 * @return string
6165 function generate_email_signoff() {
6166 global $CFG;
6168 $signoff = "\n";
6169 if (!empty($CFG->supportname)) {
6170 $signoff .= $CFG->supportname."\n";
6172 if (!empty($CFG->supportemail)) {
6173 $signoff .= $CFG->supportemail."\n";
6175 if (!empty($CFG->supportpage)) {
6176 $signoff .= $CFG->supportpage."\n";
6178 return $signoff;
6182 * Sets specified user's password and send the new password to the user via email.
6184 * @param stdClass $user A {@link $USER} object
6185 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6186 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6188 function setnew_password_and_mail($user, $fasthash = false) {
6189 global $CFG, $DB;
6191 // We try to send the mail in language the user understands,
6192 // unfortunately the filter_string() does not support alternative langs yet
6193 // so multilang will not work properly for site->fullname.
6194 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6196 $site = get_site();
6198 $supportuser = core_user::get_support_user();
6200 $newpassword = generate_password();
6202 update_internal_user_password($user, $newpassword, $fasthash);
6204 $a = new stdClass();
6205 $a->firstname = fullname($user, true);
6206 $a->sitename = format_string($site->fullname);
6207 $a->username = $user->username;
6208 $a->newpassword = $newpassword;
6209 $a->link = $CFG->wwwroot .'/login/?lang='.$lang;
6210 $a->signoff = generate_email_signoff();
6212 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6214 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6216 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6217 return email_to_user($user, $supportuser, $subject, $message);
6222 * Resets specified user's password and send the new password to the user via email.
6224 * @param stdClass $user A {@link $USER} object
6225 * @return bool Returns true if mail was sent OK and false if there was an error.
6227 function reset_password_and_mail($user) {
6228 global $CFG;
6230 $site = get_site();
6231 $supportuser = core_user::get_support_user();
6233 $userauth = get_auth_plugin($user->auth);
6234 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6235 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6236 return false;
6239 $newpassword = generate_password();
6241 if (!$userauth->user_update_password($user, $newpassword)) {
6242 print_error("cannotsetpassword");
6245 $a = new stdClass();
6246 $a->firstname = $user->firstname;
6247 $a->lastname = $user->lastname;
6248 $a->sitename = format_string($site->fullname);
6249 $a->username = $user->username;
6250 $a->newpassword = $newpassword;
6251 $a->link = $CFG->wwwroot .'/login/change_password.php';
6252 $a->signoff = generate_email_signoff();
6254 $message = get_string('newpasswordtext', '', $a);
6256 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6258 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6260 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6261 return email_to_user($user, $supportuser, $subject, $message);
6265 * Send email to specified user with confirmation text and activation link.
6267 * @param stdClass $user A {@link $USER} object
6268 * @param string $confirmationurl user confirmation URL
6269 * @return bool Returns true if mail was sent OK and false if there was an error.
6271 function send_confirmation_email($user, $confirmationurl = null) {
6272 global $CFG;
6274 $site = get_site();
6275 $supportuser = core_user::get_support_user();
6277 $data = new stdClass();
6278 $data->firstname = fullname($user);
6279 $data->sitename = format_string($site->fullname);
6280 $data->admin = generate_email_signoff();
6282 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6284 if (empty($confirmationurl)) {
6285 $confirmationurl = '/login/confirm.php';
6288 $confirmationurl = new moodle_url($confirmationurl);
6289 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6290 $confirmationurl->remove_params('data');
6291 $confirmationpath = $confirmationurl->out(false);
6293 // We need to custom encode the username to include trailing dots in the link.
6294 // Because of this custom encoding we can't use moodle_url directly.
6295 // Determine if a query string is present in the confirmation url.
6296 $hasquerystring = strpos($confirmationpath, '?') !== false;
6297 // Perform normal url encoding of the username first.
6298 $username = urlencode($user->username);
6299 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6300 $username = str_replace('.', '%2E', $username);
6302 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6304 $message = get_string('emailconfirmation', '', $data);
6305 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6307 $user->mailformat = 1; // Always send HTML version as well.
6309 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6310 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6314 * Sends a password change confirmation email.
6316 * @param stdClass $user A {@link $USER} object
6317 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6318 * @return bool Returns true if mail was sent OK and false if there was an error.
6320 function send_password_change_confirmation_email($user, $resetrecord) {
6321 global $CFG;
6323 $site = get_site();
6324 $supportuser = core_user::get_support_user();
6325 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6327 $data = new stdClass();
6328 $data->firstname = $user->firstname;
6329 $data->lastname = $user->lastname;
6330 $data->username = $user->username;
6331 $data->sitename = format_string($site->fullname);
6332 $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6333 $data->admin = generate_email_signoff();
6334 $data->resetminutes = $pwresetmins;
6336 $message = get_string('emailresetconfirmation', '', $data);
6337 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6339 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6340 return email_to_user($user, $supportuser, $subject, $message);
6345 * Sends an email containinginformation on how to change your password.
6347 * @param stdClass $user A {@link $USER} object
6348 * @return bool Returns true if mail was sent OK and false if there was an error.
6350 function send_password_change_info($user) {
6351 global $CFG;
6353 $site = get_site();
6354 $supportuser = core_user::get_support_user();
6355 $systemcontext = context_system::instance();
6357 $data = new stdClass();
6358 $data->firstname = $user->firstname;
6359 $data->lastname = $user->lastname;
6360 $data->username = $user->username;
6361 $data->sitename = format_string($site->fullname);
6362 $data->admin = generate_email_signoff();
6364 $userauth = get_auth_plugin($user->auth);
6366 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6367 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6368 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6369 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6370 return email_to_user($user, $supportuser, $subject, $message);
6373 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6374 // We have some external url for password changing.
6375 $data->link .= $userauth->change_password_url();
6377 } else {
6378 // No way to change password, sorry.
6379 $data->link = '';
6382 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6383 $message = get_string('emailpasswordchangeinfo', '', $data);
6384 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6385 } else {
6386 $message = get_string('emailpasswordchangeinfofail', '', $data);
6387 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6390 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6391 return email_to_user($user, $supportuser, $subject, $message);
6396 * Check that an email is allowed. It returns an error message if there was a problem.
6398 * @param string $email Content of email
6399 * @return string|false
6401 function email_is_not_allowed($email) {
6402 global $CFG;
6404 // Comparing lowercase domains.
6405 $email = strtolower($email);
6406 if (!empty($CFG->allowemailaddresses)) {
6407 $allowed = explode(' ', strtolower($CFG->allowemailaddresses));
6408 foreach ($allowed as $allowedpattern) {
6409 $allowedpattern = trim($allowedpattern);
6410 if (!$allowedpattern) {
6411 continue;
6413 if (strpos($allowedpattern, '.') === 0) {
6414 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6415 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6416 return false;
6419 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6420 return false;
6423 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6425 } else if (!empty($CFG->denyemailaddresses)) {
6426 $denied = explode(' ', strtolower($CFG->denyemailaddresses));
6427 foreach ($denied as $deniedpattern) {
6428 $deniedpattern = trim($deniedpattern);
6429 if (!$deniedpattern) {
6430 continue;
6432 if (strpos($deniedpattern, '.') === 0) {
6433 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6434 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6435 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6438 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6439 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6444 return false;
6447 // FILE HANDLING.
6450 * Returns local file storage instance
6452 * @return file_storage
6454 function get_file_storage($reset = false) {
6455 global $CFG;
6457 static $fs = null;
6459 if ($reset) {
6460 $fs = null;
6461 return;
6464 if ($fs) {
6465 return $fs;
6468 require_once("$CFG->libdir/filelib.php");
6470 $fs = new file_storage();
6472 return $fs;
6476 * Returns local file storage instance
6478 * @return file_browser
6480 function get_file_browser() {
6481 global $CFG;
6483 static $fb = null;
6485 if ($fb) {
6486 return $fb;
6489 require_once("$CFG->libdir/filelib.php");
6491 $fb = new file_browser();
6493 return $fb;
6497 * Returns file packer
6499 * @param string $mimetype default application/zip
6500 * @return file_packer
6502 function get_file_packer($mimetype='application/zip') {
6503 global $CFG;
6505 static $fp = array();
6507 if (isset($fp[$mimetype])) {
6508 return $fp[$mimetype];
6511 switch ($mimetype) {
6512 case 'application/zip':
6513 case 'application/vnd.moodle.profiling':
6514 $classname = 'zip_packer';
6515 break;
6517 case 'application/x-gzip' :
6518 $classname = 'tgz_packer';
6519 break;
6521 case 'application/vnd.moodle.backup':
6522 $classname = 'mbz_packer';
6523 break;
6525 default:
6526 return false;
6529 require_once("$CFG->libdir/filestorage/$classname.php");
6530 $fp[$mimetype] = new $classname();
6532 return $fp[$mimetype];
6536 * Returns current name of file on disk if it exists.
6538 * @param string $newfile File to be verified
6539 * @return string Current name of file on disk if true
6541 function valid_uploaded_file($newfile) {
6542 if (empty($newfile)) {
6543 return '';
6545 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6546 return $newfile['tmp_name'];
6547 } else {
6548 return '';
6553 * Returns the maximum size for uploading files.
6555 * There are seven possible upload limits:
6556 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6557 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6558 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6559 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6560 * 5. by the Moodle admin in $CFG->maxbytes
6561 * 6. by the teacher in the current course $course->maxbytes
6562 * 7. by the teacher for the current module, eg $assignment->maxbytes
6564 * These last two are passed to this function as arguments (in bytes).
6565 * Anything defined as 0 is ignored.
6566 * The smallest of all the non-zero numbers is returned.
6568 * @todo Finish documenting this function
6570 * @param int $sitebytes Set maximum size
6571 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6572 * @param int $modulebytes Current module ->maxbytes (in bytes)
6573 * @param bool $unused This parameter has been deprecated and is not used any more.
6574 * @return int The maximum size for uploading files.
6576 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6578 if (! $filesize = ini_get('upload_max_filesize')) {
6579 $filesize = '5M';
6581 $minimumsize = get_real_size($filesize);
6583 if ($postsize = ini_get('post_max_size')) {
6584 $postsize = get_real_size($postsize);
6585 if ($postsize < $minimumsize) {
6586 $minimumsize = $postsize;
6590 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6591 $minimumsize = $sitebytes;
6594 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6595 $minimumsize = $coursebytes;
6598 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6599 $minimumsize = $modulebytes;
6602 return $minimumsize;
6606 * Returns the maximum size for uploading files for the current user
6608 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6610 * @param context $context The context in which to check user capabilities
6611 * @param int $sitebytes Set maximum size
6612 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6613 * @param int $modulebytes Current module ->maxbytes (in bytes)
6614 * @param stdClass $user The user
6615 * @param bool $unused This parameter has been deprecated and is not used any more.
6616 * @return int The maximum size for uploading files.
6618 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6619 $unused = false) {
6620 global $USER;
6622 if (empty($user)) {
6623 $user = $USER;
6626 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6627 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6630 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6634 * Returns an array of possible sizes in local language
6636 * Related to {@link get_max_upload_file_size()} - this function returns an
6637 * array of possible sizes in an array, translated to the
6638 * local language.
6640 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6642 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6643 * with the value set to 0. This option will be the first in the list.
6645 * @uses SORT_NUMERIC
6646 * @param int $sitebytes Set maximum size
6647 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6648 * @param int $modulebytes Current module ->maxbytes (in bytes)
6649 * @param int|array $custombytes custom upload size/s which will be added to list,
6650 * Only value/s smaller then maxsize will be added to list.
6651 * @return array
6653 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6654 global $CFG;
6656 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6657 return array();
6660 if ($sitebytes == 0) {
6661 // Will get the minimum of upload_max_filesize or post_max_size.
6662 $sitebytes = get_max_upload_file_size();
6665 $filesize = array();
6666 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6667 5242880, 10485760, 20971520, 52428800, 104857600,
6668 262144000, 524288000, 786432000, 1073741824,
6669 2147483648, 4294967296, 8589934592);
6671 // If custombytes is given and is valid then add it to the list.
6672 if (is_number($custombytes) and $custombytes > 0) {
6673 $custombytes = (int)$custombytes;
6674 if (!in_array($custombytes, $sizelist)) {
6675 $sizelist[] = $custombytes;
6677 } else if (is_array($custombytes)) {
6678 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6681 // Allow maxbytes to be selected if it falls outside the above boundaries.
6682 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6683 // Note: get_real_size() is used in order to prevent problems with invalid values.
6684 $sizelist[] = get_real_size($CFG->maxbytes);
6687 foreach ($sizelist as $sizebytes) {
6688 if ($sizebytes < $maxsize && $sizebytes > 0) {
6689 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6693 $limitlevel = '';
6694 $displaysize = '';
6695 if ($modulebytes &&
6696 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6697 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6698 $limitlevel = get_string('activity', 'core');
6699 $displaysize = display_size($modulebytes);
6700 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6702 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6703 $limitlevel = get_string('course', 'core');
6704 $displaysize = display_size($coursebytes);
6705 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6707 } else if ($sitebytes) {
6708 $limitlevel = get_string('site', 'core');
6709 $displaysize = display_size($sitebytes);
6710 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6713 krsort($filesize, SORT_NUMERIC);
6714 if ($limitlevel) {
6715 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6716 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6719 return $filesize;
6723 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6725 * If excludefiles is defined, then that file/directory is ignored
6726 * If getdirs is true, then (sub)directories are included in the output
6727 * If getfiles is true, then files are included in the output
6728 * (at least one of these must be true!)
6730 * @todo Finish documenting this function. Add examples of $excludefile usage.
6732 * @param string $rootdir A given root directory to start from
6733 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6734 * @param bool $descend If true then subdirectories are recursed as well
6735 * @param bool $getdirs If true then (sub)directories are included in the output
6736 * @param bool $getfiles If true then files are included in the output
6737 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6739 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6741 $dirs = array();
6743 if (!$getdirs and !$getfiles) { // Nothing to show.
6744 return $dirs;
6747 if (!is_dir($rootdir)) { // Must be a directory.
6748 return $dirs;
6751 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6752 return $dirs;
6755 if (!is_array($excludefiles)) {
6756 $excludefiles = array($excludefiles);
6759 while (false !== ($file = readdir($dir))) {
6760 $firstchar = substr($file, 0, 1);
6761 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6762 continue;
6764 $fullfile = $rootdir .'/'. $file;
6765 if (filetype($fullfile) == 'dir') {
6766 if ($getdirs) {
6767 $dirs[] = $file;
6769 if ($descend) {
6770 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6771 foreach ($subdirs as $subdir) {
6772 $dirs[] = $file .'/'. $subdir;
6775 } else if ($getfiles) {
6776 $dirs[] = $file;
6779 closedir($dir);
6781 asort($dirs);
6783 return $dirs;
6788 * Adds up all the files in a directory and works out the size.
6790 * @param string $rootdir The directory to start from
6791 * @param string $excludefile A file to exclude when summing directory size
6792 * @return int The summed size of all files and subfiles within the root directory
6794 function get_directory_size($rootdir, $excludefile='') {
6795 global $CFG;
6797 // Do it this way if we can, it's much faster.
6798 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6799 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6800 $output = null;
6801 $return = null;
6802 exec($command, $output, $return);
6803 if (is_array($output)) {
6804 // We told it to return k.
6805 return get_real_size(intval($output[0]).'k');
6809 if (!is_dir($rootdir)) {
6810 // Must be a directory.
6811 return 0;
6814 if (!$dir = @opendir($rootdir)) {
6815 // Can't open it for some reason.
6816 return 0;
6819 $size = 0;
6821 while (false !== ($file = readdir($dir))) {
6822 $firstchar = substr($file, 0, 1);
6823 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6824 continue;
6826 $fullfile = $rootdir .'/'. $file;
6827 if (filetype($fullfile) == 'dir') {
6828 $size += get_directory_size($fullfile, $excludefile);
6829 } else {
6830 $size += filesize($fullfile);
6833 closedir($dir);
6835 return $size;
6839 * Converts bytes into display form
6841 * @static string $gb Localized string for size in gigabytes
6842 * @static string $mb Localized string for size in megabytes
6843 * @static string $kb Localized string for size in kilobytes
6844 * @static string $b Localized string for size in bytes
6845 * @param int $size The size to convert to human readable form
6846 * @return string
6848 function display_size($size) {
6850 static $gb, $mb, $kb, $b;
6852 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6853 return get_string('unlimited');
6856 if (empty($gb)) {
6857 $gb = get_string('sizegb');
6858 $mb = get_string('sizemb');
6859 $kb = get_string('sizekb');
6860 $b = get_string('sizeb');
6863 if ($size >= 1073741824) {
6864 $size = round($size / 1073741824 * 10) / 10 . $gb;
6865 } else if ($size >= 1048576) {
6866 $size = round($size / 1048576 * 10) / 10 . $mb;
6867 } else if ($size >= 1024) {
6868 $size = round($size / 1024 * 10) / 10 . $kb;
6869 } else {
6870 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6872 return $size;
6876 * Cleans a given filename by removing suspicious or troublesome characters
6878 * @see clean_param()
6879 * @param string $string file name
6880 * @return string cleaned file name
6882 function clean_filename($string) {
6883 return clean_param($string, PARAM_FILE);
6886 // STRING TRANSLATION.
6889 * Returns the code for the current language
6891 * @category string
6892 * @return string
6894 function current_language() {
6895 global $CFG, $USER, $SESSION, $COURSE;
6897 if (!empty($SESSION->forcelang)) {
6898 // Allows overriding course-forced language (useful for admins to check
6899 // issues in courses whose language they don't understand).
6900 // Also used by some code to temporarily get language-related information in a
6901 // specific language (see force_current_language()).
6902 $return = $SESSION->forcelang;
6904 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6905 // Course language can override all other settings for this page.
6906 $return = $COURSE->lang;
6908 } else if (!empty($SESSION->lang)) {
6909 // Session language can override other settings.
6910 $return = $SESSION->lang;
6912 } else if (!empty($USER->lang)) {
6913 $return = $USER->lang;
6915 } else if (isset($CFG->lang)) {
6916 $return = $CFG->lang;
6918 } else {
6919 $return = 'en';
6922 // Just in case this slipped in from somewhere by accident.
6923 $return = str_replace('_utf8', '', $return);
6925 return $return;
6929 * Returns parent language of current active language if defined
6931 * @category string
6932 * @param string $lang null means current language
6933 * @return string
6935 function get_parent_language($lang=null) {
6937 // Let's hack around the current language.
6938 if (!empty($lang)) {
6939 $oldforcelang = force_current_language($lang);
6942 $parentlang = get_string('parentlanguage', 'langconfig');
6943 if ($parentlang === 'en') {
6944 $parentlang = '';
6947 // Let's hack around the current language.
6948 if (!empty($lang)) {
6949 force_current_language($oldforcelang);
6952 return $parentlang;
6956 * Force the current language to get strings and dates localised in the given language.
6958 * After calling this function, all strings will be provided in the given language
6959 * until this function is called again, or equivalent code is run.
6961 * @param string $language
6962 * @return string previous $SESSION->forcelang value
6964 function force_current_language($language) {
6965 global $SESSION;
6966 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6967 if ($language !== $sessionforcelang) {
6968 // Seting forcelang to null or an empty string disables it's effect.
6969 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6970 $SESSION->forcelang = $language;
6971 moodle_setlocale();
6974 return $sessionforcelang;
6978 * Returns current string_manager instance.
6980 * The param $forcereload is needed for CLI installer only where the string_manager instance
6981 * must be replaced during the install.php script life time.
6983 * @category string
6984 * @param bool $forcereload shall the singleton be released and new instance created instead?
6985 * @return core_string_manager
6987 function get_string_manager($forcereload=false) {
6988 global $CFG;
6990 static $singleton = null;
6992 if ($forcereload) {
6993 $singleton = null;
6995 if ($singleton === null) {
6996 if (empty($CFG->early_install_lang)) {
6998 if (empty($CFG->langlist)) {
6999 $translist = array();
7000 } else {
7001 $translist = explode(',', $CFG->langlist);
7002 $translist = array_map('trim', $translist);
7005 if (!empty($CFG->config_php_settings['customstringmanager'])) {
7006 $classname = $CFG->config_php_settings['customstringmanager'];
7008 if (class_exists($classname)) {
7009 $implements = class_implements($classname);
7011 if (isset($implements['core_string_manager'])) {
7012 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist);
7013 return $singleton;
7015 } else {
7016 debugging('Unable to instantiate custom string manager: class '.$classname.
7017 ' does not implement the core_string_manager interface.');
7020 } else {
7021 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7025 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
7027 } else {
7028 $singleton = new core_string_manager_install();
7032 return $singleton;
7036 * Returns a localized string.
7038 * Returns the translated string specified by $identifier as
7039 * for $module. Uses the same format files as STphp.
7040 * $a is an object, string or number that can be used
7041 * within translation strings
7043 * eg 'hello {$a->firstname} {$a->lastname}'
7044 * or 'hello {$a}'
7046 * If you would like to directly echo the localized string use
7047 * the function {@link print_string()}
7049 * Example usage of this function involves finding the string you would
7050 * like a local equivalent of and using its identifier and module information
7051 * to retrieve it.<br/>
7052 * If you open moodle/lang/en/moodle.php and look near line 278
7053 * you will find a string to prompt a user for their word for 'course'
7054 * <code>
7055 * $string['course'] = 'Course';
7056 * </code>
7057 * So if you want to display the string 'Course'
7058 * in any language that supports it on your site
7059 * you just need to use the identifier 'course'
7060 * <code>
7061 * $mystring = '<strong>'. get_string('course') .'</strong>';
7062 * or
7063 * </code>
7064 * If the string you want is in another file you'd take a slightly
7065 * different approach. Looking in moodle/lang/en/calendar.php you find
7066 * around line 75:
7067 * <code>
7068 * $string['typecourse'] = 'Course event';
7069 * </code>
7070 * If you want to display the string "Course event" in any language
7071 * supported you would use the identifier 'typecourse' and the module 'calendar'
7072 * (because it is in the file calendar.php):
7073 * <code>
7074 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7075 * </code>
7077 * As a last resort, should the identifier fail to map to a string
7078 * the returned string will be [[ $identifier ]]
7080 * In Moodle 2.3 there is a new argument to this function $lazyload.
7081 * Setting $lazyload to true causes get_string to return a lang_string object
7082 * rather than the string itself. The fetching of the string is then put off until
7083 * the string object is first used. The object can be used by calling it's out
7084 * method or by casting the object to a string, either directly e.g.
7085 * (string)$stringobject
7086 * or indirectly by using the string within another string or echoing it out e.g.
7087 * echo $stringobject
7088 * return "<p>{$stringobject}</p>";
7089 * It is worth noting that using $lazyload and attempting to use the string as an
7090 * array key will cause a fatal error as objects cannot be used as array keys.
7091 * But you should never do that anyway!
7092 * For more information {@link lang_string}
7094 * @category string
7095 * @param string $identifier The key identifier for the localized string
7096 * @param string $component The module where the key identifier is stored,
7097 * usually expressed as the filename in the language pack without the
7098 * .php on the end but can also be written as mod/forum or grade/export/xls.
7099 * If none is specified then moodle.php is used.
7100 * @param string|object|array $a An object, string or number that can be used
7101 * within translation strings
7102 * @param bool $lazyload If set to true a string object is returned instead of
7103 * the string itself. The string then isn't calculated until it is first used.
7104 * @return string The localized string.
7105 * @throws coding_exception
7107 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7108 global $CFG;
7110 // If the lazy load argument has been supplied return a lang_string object
7111 // instead.
7112 // We need to make sure it is true (and a bool) as you will see below there
7113 // used to be a forth argument at one point.
7114 if ($lazyload === true) {
7115 return new lang_string($identifier, $component, $a);
7118 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7119 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7122 // There is now a forth argument again, this time it is a boolean however so
7123 // we can still check for the old extralocations parameter.
7124 if (!is_bool($lazyload) && !empty($lazyload)) {
7125 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7128 if (strpos($component, '/') !== false) {
7129 debugging('The module name you passed to get_string is the deprecated format ' .
7130 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7131 $componentpath = explode('/', $component);
7133 switch ($componentpath[0]) {
7134 case 'mod':
7135 $component = $componentpath[1];
7136 break;
7137 case 'blocks':
7138 case 'block':
7139 $component = 'block_'.$componentpath[1];
7140 break;
7141 case 'enrol':
7142 $component = 'enrol_'.$componentpath[1];
7143 break;
7144 case 'format':
7145 $component = 'format_'.$componentpath[1];
7146 break;
7147 case 'grade':
7148 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7149 break;
7153 $result = get_string_manager()->get_string($identifier, $component, $a);
7155 // Debugging feature lets you display string identifier and component.
7156 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7157 $result .= ' {' . $identifier . '/' . $component . '}';
7159 return $result;
7163 * Converts an array of strings to their localized value.
7165 * @param array $array An array of strings
7166 * @param string $component The language module that these strings can be found in.
7167 * @return stdClass translated strings.
7169 function get_strings($array, $component = '') {
7170 $string = new stdClass;
7171 foreach ($array as $item) {
7172 $string->$item = get_string($item, $component);
7174 return $string;
7178 * Prints out a translated string.
7180 * Prints out a translated string using the return value from the {@link get_string()} function.
7182 * Example usage of this function when the string is in the moodle.php file:<br/>
7183 * <code>
7184 * echo '<strong>';
7185 * print_string('course');
7186 * echo '</strong>';
7187 * </code>
7189 * Example usage of this function when the string is not in the moodle.php file:<br/>
7190 * <code>
7191 * echo '<h1>';
7192 * print_string('typecourse', 'calendar');
7193 * echo '</h1>';
7194 * </code>
7196 * @category string
7197 * @param string $identifier The key identifier for the localized string
7198 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7199 * @param string|object|array $a An object, string or number that can be used within translation strings
7201 function print_string($identifier, $component = '', $a = null) {
7202 echo get_string($identifier, $component, $a);
7206 * Returns a list of charset codes
7208 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7209 * (checking that such charset is supported by the texlib library!)
7211 * @return array And associative array with contents in the form of charset => charset
7213 function get_list_of_charsets() {
7215 $charsets = array(
7216 'EUC-JP' => 'EUC-JP',
7217 'ISO-2022-JP'=> 'ISO-2022-JP',
7218 'ISO-8859-1' => 'ISO-8859-1',
7219 'SHIFT-JIS' => 'SHIFT-JIS',
7220 'GB2312' => 'GB2312',
7221 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7222 'UTF-8' => 'UTF-8');
7224 asort($charsets);
7226 return $charsets;
7230 * Returns a list of valid and compatible themes
7232 * @return array
7234 function get_list_of_themes() {
7235 global $CFG;
7237 $themes = array();
7239 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7240 $themelist = explode(',', $CFG->themelist);
7241 } else {
7242 $themelist = array_keys(core_component::get_plugin_list("theme"));
7245 foreach ($themelist as $key => $themename) {
7246 $theme = theme_config::load($themename);
7247 $themes[$themename] = $theme;
7250 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7252 return $themes;
7256 * Factory function for emoticon_manager
7258 * @return emoticon_manager singleton
7260 function get_emoticon_manager() {
7261 static $singleton = null;
7263 if (is_null($singleton)) {
7264 $singleton = new emoticon_manager();
7267 return $singleton;
7271 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7273 * Whenever this manager mentiones 'emoticon object', the following data
7274 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7275 * altidentifier and altcomponent
7277 * @see admin_setting_emoticons
7279 * @copyright 2010 David Mudrak
7280 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7282 class emoticon_manager {
7285 * Returns the currently enabled emoticons
7287 * @return array of emoticon objects
7289 public function get_emoticons() {
7290 global $CFG;
7292 if (empty($CFG->emoticons)) {
7293 return array();
7296 $emoticons = $this->decode_stored_config($CFG->emoticons);
7298 if (!is_array($emoticons)) {
7299 // Something is wrong with the format of stored setting.
7300 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7301 return array();
7304 return $emoticons;
7308 * Converts emoticon object into renderable pix_emoticon object
7310 * @param stdClass $emoticon emoticon object
7311 * @param array $attributes explicit HTML attributes to set
7312 * @return pix_emoticon
7314 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7315 $stringmanager = get_string_manager();
7316 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7317 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7318 } else {
7319 $alt = s($emoticon->text);
7321 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7325 * Encodes the array of emoticon objects into a string storable in config table
7327 * @see self::decode_stored_config()
7328 * @param array $emoticons array of emtocion objects
7329 * @return string
7331 public function encode_stored_config(array $emoticons) {
7332 return json_encode($emoticons);
7336 * Decodes the string into an array of emoticon objects
7338 * @see self::encode_stored_config()
7339 * @param string $encoded
7340 * @return string|null
7342 public function decode_stored_config($encoded) {
7343 $decoded = json_decode($encoded);
7344 if (!is_array($decoded)) {
7345 return null;
7347 return $decoded;
7351 * Returns default set of emoticons supported by Moodle
7353 * @return array of sdtClasses
7355 public function default_emoticons() {
7356 return array(
7357 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7358 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7359 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7360 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7361 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7362 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7363 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7364 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7365 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7366 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7367 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7368 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7369 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7370 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7371 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7372 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7373 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7374 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7375 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7376 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7377 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7378 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7379 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7380 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7381 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7382 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7383 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7384 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7385 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7386 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7391 * Helper method preparing the stdClass with the emoticon properties
7393 * @param string|array $text or array of strings
7394 * @param string $imagename to be used by {@link pix_emoticon}
7395 * @param string $altidentifier alternative string identifier, null for no alt
7396 * @param string $altcomponent where the alternative string is defined
7397 * @param string $imagecomponent to be used by {@link pix_emoticon}
7398 * @return stdClass
7400 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7401 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7402 return (object)array(
7403 'text' => $text,
7404 'imagename' => $imagename,
7405 'imagecomponent' => $imagecomponent,
7406 'altidentifier' => $altidentifier,
7407 'altcomponent' => $altcomponent,
7412 // ENCRYPTION.
7415 * rc4encrypt
7417 * @param string $data Data to encrypt.
7418 * @return string The now encrypted data.
7420 function rc4encrypt($data) {
7421 return endecrypt(get_site_identifier(), $data, '');
7425 * rc4decrypt
7427 * @param string $data Data to decrypt.
7428 * @return string The now decrypted data.
7430 function rc4decrypt($data) {
7431 return endecrypt(get_site_identifier(), $data, 'de');
7435 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7437 * @todo Finish documenting this function
7439 * @param string $pwd The password to use when encrypting or decrypting
7440 * @param string $data The data to be decrypted/encrypted
7441 * @param string $case Either 'de' for decrypt or '' for encrypt
7442 * @return string
7444 function endecrypt ($pwd, $data, $case) {
7446 if ($case == 'de') {
7447 $data = urldecode($data);
7450 $key[] = '';
7451 $box[] = '';
7452 $pwdlength = strlen($pwd);
7454 for ($i = 0; $i <= 255; $i++) {
7455 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7456 $box[$i] = $i;
7459 $x = 0;
7461 for ($i = 0; $i <= 255; $i++) {
7462 $x = ($x + $box[$i] + $key[$i]) % 256;
7463 $tempswap = $box[$i];
7464 $box[$i] = $box[$x];
7465 $box[$x] = $tempswap;
7468 $cipher = '';
7470 $a = 0;
7471 $j = 0;
7473 for ($i = 0; $i < strlen($data); $i++) {
7474 $a = ($a + 1) % 256;
7475 $j = ($j + $box[$a]) % 256;
7476 $temp = $box[$a];
7477 $box[$a] = $box[$j];
7478 $box[$j] = $temp;
7479 $k = $box[(($box[$a] + $box[$j]) % 256)];
7480 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7481 $cipher .= chr($cipherby);
7484 if ($case == 'de') {
7485 $cipher = urldecode(urlencode($cipher));
7486 } else {
7487 $cipher = urlencode($cipher);
7490 return $cipher;
7493 // ENVIRONMENT CHECKING.
7496 * This method validates a plug name. It is much faster than calling clean_param.
7498 * @param string $name a string that might be a plugin name.
7499 * @return bool if this string is a valid plugin name.
7501 function is_valid_plugin_name($name) {
7502 // This does not work for 'mod', bad luck, use any other type.
7503 return core_component::is_valid_plugin_name('tool', $name);
7507 * Get a list of all the plugins of a given type that define a certain API function
7508 * in a certain file. The plugin component names and function names are returned.
7510 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7511 * @param string $function the part of the name of the function after the
7512 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7513 * names like report_courselist_hook.
7514 * @param string $file the name of file within the plugin that defines the
7515 * function. Defaults to lib.php.
7516 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7517 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7519 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7520 global $CFG;
7522 // We don't include here as all plugin types files would be included.
7523 $plugins = get_plugins_with_function($function, $file, false);
7525 if (empty($plugins[$plugintype])) {
7526 return array();
7529 $allplugins = core_component::get_plugin_list($plugintype);
7531 // Reformat the array and include the files.
7532 $pluginfunctions = array();
7533 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7535 // Check that it has not been removed and the file is still available.
7536 if (!empty($allplugins[$pluginname])) {
7538 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7539 if (file_exists($filepath)) {
7540 include_once($filepath);
7541 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7546 return $pluginfunctions;
7550 * Get a list of all the plugins that define a certain API function in a certain file.
7552 * @param string $function the part of the name of the function after the
7553 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7554 * names like report_courselist_hook.
7555 * @param string $file the name of file within the plugin that defines the
7556 * function. Defaults to lib.php.
7557 * @param bool $include Whether to include the files that contain the functions or not.
7558 * @return array with [plugintype][plugin] = functionname
7560 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7561 global $CFG;
7563 if (during_initial_install() || isset($CFG->upgraderunning)) {
7564 // API functions _must not_ be called during an installation or upgrade.
7565 return [];
7568 $cache = \cache::make('core', 'plugin_functions');
7570 // Including both although I doubt that we will find two functions definitions with the same name.
7571 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7572 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7573 $pluginfunctions = $cache->get($key);
7575 // Use the plugin manager to check that plugins are currently installed.
7576 $pluginmanager = \core_plugin_manager::instance();
7578 if ($pluginfunctions !== false) {
7580 // Checking that the files are still available.
7581 foreach ($pluginfunctions as $plugintype => $plugins) {
7583 $allplugins = \core_component::get_plugin_list($plugintype);
7584 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7585 foreach ($plugins as $plugin => $function) {
7586 if (!isset($installedplugins[$plugin])) {
7587 // Plugin code is still present on disk but it is not installed.
7588 unset($pluginfunctions[$plugintype][$plugin]);
7589 continue;
7592 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7593 if (empty($allplugins[$plugin])) {
7594 unset($pluginfunctions[$plugintype][$plugin]);
7595 continue;
7598 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7599 if ($include && $fileexists) {
7600 // Include the files if it was requested.
7601 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7602 } else if (!$fileexists) {
7603 // If the file is not available any more it should not be returned.
7604 unset($pluginfunctions[$plugintype][$plugin]);
7608 return $pluginfunctions;
7611 $pluginfunctions = array();
7613 // To fill the cached. Also, everything should continue working with cache disabled.
7614 $plugintypes = \core_component::get_plugin_types();
7615 foreach ($plugintypes as $plugintype => $unused) {
7617 // We need to include files here.
7618 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7619 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7620 foreach ($pluginswithfile as $plugin => $notused) {
7622 if (!isset($installedplugins[$plugin])) {
7623 continue;
7626 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7628 $pluginfunction = false;
7629 if (function_exists($fullfunction)) {
7630 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7631 $pluginfunction = $fullfunction;
7633 } else if ($plugintype === 'mod') {
7634 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7635 $shortfunction = $plugin . '_' . $function;
7636 if (function_exists($shortfunction)) {
7637 $pluginfunction = $shortfunction;
7641 if ($pluginfunction) {
7642 if (empty($pluginfunctions[$plugintype])) {
7643 $pluginfunctions[$plugintype] = array();
7645 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7650 $cache->set($key, $pluginfunctions);
7652 return $pluginfunctions;
7657 * Lists plugin-like directories within specified directory
7659 * This function was originally used for standard Moodle plugins, please use
7660 * new core_component::get_plugin_list() now.
7662 * This function is used for general directory listing and backwards compatility.
7664 * @param string $directory relative directory from root
7665 * @param string $exclude dir name to exclude from the list (defaults to none)
7666 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7667 * @return array Sorted array of directory names found under the requested parameters
7669 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7670 global $CFG;
7672 $plugins = array();
7674 if (empty($basedir)) {
7675 $basedir = $CFG->dirroot .'/'. $directory;
7677 } else {
7678 $basedir = $basedir .'/'. $directory;
7681 if ($CFG->debugdeveloper and empty($exclude)) {
7682 // Make sure devs do not use this to list normal plugins,
7683 // this is intended for general directories that are not plugins!
7685 $subtypes = core_component::get_plugin_types();
7686 if (in_array($basedir, $subtypes)) {
7687 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7689 unset($subtypes);
7692 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7693 if (!$dirhandle = opendir($basedir)) {
7694 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7695 return array();
7697 while (false !== ($dir = readdir($dirhandle))) {
7698 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7699 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7700 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7701 continue;
7703 if (filetype($basedir .'/'. $dir) != 'dir') {
7704 continue;
7706 $plugins[] = $dir;
7708 closedir($dirhandle);
7710 if ($plugins) {
7711 asort($plugins);
7713 return $plugins;
7717 * Invoke plugin's callback functions
7719 * @param string $type plugin type e.g. 'mod'
7720 * @param string $name plugin name
7721 * @param string $feature feature name
7722 * @param string $action feature's action
7723 * @param array $params parameters of callback function, should be an array
7724 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7725 * @return mixed
7727 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7729 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7730 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7734 * Invoke component's callback functions
7736 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7737 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7738 * @param array $params parameters of callback function
7739 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7740 * @return mixed
7742 function component_callback($component, $function, array $params = array(), $default = null) {
7744 $functionname = component_callback_exists($component, $function);
7746 if ($functionname) {
7747 // Function exists, so just return function result.
7748 $ret = call_user_func_array($functionname, $params);
7749 if (is_null($ret)) {
7750 return $default;
7751 } else {
7752 return $ret;
7755 return $default;
7759 * Determine if a component callback exists and return the function name to call. Note that this
7760 * function will include the required library files so that the functioname returned can be
7761 * called directly.
7763 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7764 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7765 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7766 * @throws coding_exception if invalid component specfied
7768 function component_callback_exists($component, $function) {
7769 global $CFG; // This is needed for the inclusions.
7771 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7772 if (empty($cleancomponent)) {
7773 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7775 $component = $cleancomponent;
7777 list($type, $name) = core_component::normalize_component($component);
7778 $component = $type . '_' . $name;
7780 $oldfunction = $name.'_'.$function;
7781 $function = $component.'_'.$function;
7783 $dir = core_component::get_component_directory($component);
7784 if (empty($dir)) {
7785 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7788 // Load library and look for function.
7789 if (file_exists($dir.'/lib.php')) {
7790 require_once($dir.'/lib.php');
7793 if (!function_exists($function) and function_exists($oldfunction)) {
7794 if ($type !== 'mod' and $type !== 'core') {
7795 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7797 $function = $oldfunction;
7800 if (function_exists($function)) {
7801 return $function;
7803 return false;
7807 * Call the specified callback method on the provided class.
7809 * If the callback returns null, then the default value is returned instead.
7810 * If the class does not exist, then the default value is returned.
7812 * @param string $classname The name of the class to call upon.
7813 * @param string $methodname The name of the staticically defined method on the class.
7814 * @param array $params The arguments to pass into the method.
7815 * @param mixed $default The default value.
7816 * @return mixed The return value.
7818 function component_class_callback($classname, $methodname, array $params, $default = null) {
7819 if (!class_exists($classname)) {
7820 return $default;
7823 if (!method_exists($classname, $methodname)) {
7824 return $default;
7827 $fullfunction = $classname . '::' . $methodname;
7828 $result = call_user_func_array($fullfunction, $params);
7830 if (null === $result) {
7831 return $default;
7832 } else {
7833 return $result;
7838 * Checks whether a plugin supports a specified feature.
7840 * @param string $type Plugin type e.g. 'mod'
7841 * @param string $name Plugin name e.g. 'forum'
7842 * @param string $feature Feature code (FEATURE_xx constant)
7843 * @param mixed $default default value if feature support unknown
7844 * @return mixed Feature result (false if not supported, null if feature is unknown,
7845 * otherwise usually true but may have other feature-specific value such as array)
7846 * @throws coding_exception
7848 function plugin_supports($type, $name, $feature, $default = null) {
7849 global $CFG;
7851 if ($type === 'mod' and $name === 'NEWMODULE') {
7852 // Somebody forgot to rename the module template.
7853 return false;
7856 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7857 if (empty($component)) {
7858 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7861 $function = null;
7863 if ($type === 'mod') {
7864 // We need this special case because we support subplugins in modules,
7865 // otherwise it would end up in infinite loop.
7866 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7867 include_once("$CFG->dirroot/mod/$name/lib.php");
7868 $function = $component.'_supports';
7869 if (!function_exists($function)) {
7870 // Legacy non-frankenstyle function name.
7871 $function = $name.'_supports';
7875 } else {
7876 if (!$path = core_component::get_plugin_directory($type, $name)) {
7877 // Non existent plugin type.
7878 return false;
7880 if (file_exists("$path/lib.php")) {
7881 include_once("$path/lib.php");
7882 $function = $component.'_supports';
7886 if ($function and function_exists($function)) {
7887 $supports = $function($feature);
7888 if (is_null($supports)) {
7889 // Plugin does not know - use default.
7890 return $default;
7891 } else {
7892 return $supports;
7896 // Plugin does not care, so use default.
7897 return $default;
7901 * Returns true if the current version of PHP is greater that the specified one.
7903 * @todo Check PHP version being required here is it too low?
7905 * @param string $version The version of php being tested.
7906 * @return bool
7908 function check_php_version($version='5.2.4') {
7909 return (version_compare(phpversion(), $version) >= 0);
7913 * Determine if moodle installation requires update.
7915 * Checks version numbers of main code and all plugins to see
7916 * if there are any mismatches.
7918 * @return bool
7920 function moodle_needs_upgrading() {
7921 global $CFG;
7923 if (empty($CFG->version)) {
7924 return true;
7927 // There is no need to purge plugininfo caches here because
7928 // these caches are not used during upgrade and they are purged after
7929 // every upgrade.
7931 if (empty($CFG->allversionshash)) {
7932 return true;
7935 $hash = core_component::get_all_versions_hash();
7937 return ($hash !== $CFG->allversionshash);
7941 * Returns the major version of this site
7943 * Moodle version numbers consist of three numbers separated by a dot, for
7944 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7945 * called major version. This function extracts the major version from either
7946 * $CFG->release (default) or eventually from the $release variable defined in
7947 * the main version.php.
7949 * @param bool $fromdisk should the version if source code files be used
7950 * @return string|false the major version like '2.3', false if could not be determined
7952 function moodle_major_version($fromdisk = false) {
7953 global $CFG;
7955 if ($fromdisk) {
7956 $release = null;
7957 require($CFG->dirroot.'/version.php');
7958 if (empty($release)) {
7959 return false;
7962 } else {
7963 if (empty($CFG->release)) {
7964 return false;
7966 $release = $CFG->release;
7969 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7970 return $matches[0];
7971 } else {
7972 return false;
7976 // MISCELLANEOUS.
7979 * Sets the system locale
7981 * @category string
7982 * @param string $locale Can be used to force a locale
7984 function moodle_setlocale($locale='') {
7985 global $CFG;
7987 static $currentlocale = ''; // Last locale caching.
7989 $oldlocale = $currentlocale;
7991 // Fetch the correct locale based on ostype.
7992 if ($CFG->ostype == 'WINDOWS') {
7993 $stringtofetch = 'localewin';
7994 } else {
7995 $stringtofetch = 'locale';
7998 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7999 if (!empty($locale)) {
8000 $currentlocale = $locale;
8001 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
8002 $currentlocale = $CFG->locale;
8003 } else {
8004 $currentlocale = get_string($stringtofetch, 'langconfig');
8007 // Do nothing if locale already set up.
8008 if ($oldlocale == $currentlocale) {
8009 return;
8012 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8013 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8014 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8016 // Get current values.
8017 $monetary= setlocale (LC_MONETARY, 0);
8018 $numeric = setlocale (LC_NUMERIC, 0);
8019 $ctype = setlocale (LC_CTYPE, 0);
8020 if ($CFG->ostype != 'WINDOWS') {
8021 $messages= setlocale (LC_MESSAGES, 0);
8023 // Set locale to all.
8024 $result = setlocale (LC_ALL, $currentlocale);
8025 // If setting of locale fails try the other utf8 or utf-8 variant,
8026 // some operating systems support both (Debian), others just one (OSX).
8027 if ($result === false) {
8028 if (stripos($currentlocale, '.UTF-8') !== false) {
8029 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8030 setlocale (LC_ALL, $newlocale);
8031 } else if (stripos($currentlocale, '.UTF8') !== false) {
8032 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8033 setlocale (LC_ALL, $newlocale);
8036 // Set old values.
8037 setlocale (LC_MONETARY, $monetary);
8038 setlocale (LC_NUMERIC, $numeric);
8039 if ($CFG->ostype != 'WINDOWS') {
8040 setlocale (LC_MESSAGES, $messages);
8042 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8043 // To workaround a well-known PHP problem with Turkish letter Ii.
8044 setlocale (LC_CTYPE, $ctype);
8049 * Count words in a string.
8051 * Words are defined as things between whitespace.
8053 * @category string
8054 * @param string $string The text to be searched for words.
8055 * @return int The count of words in the specified string
8057 function count_words($string) {
8058 $string = strip_tags($string);
8059 // Decode HTML entities.
8060 $string = html_entity_decode($string);
8061 // Replace underscores (which are classed as word characters) with spaces.
8062 $string = preg_replace('/_/u', ' ', $string);
8063 // Remove any characters that shouldn't be treated as word boundaries.
8064 $string = preg_replace('/[\'"’-]/u', '', $string);
8065 // Remove dots and commas from within numbers only.
8066 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
8068 return count(preg_split('/\w\b/u', $string)) - 1;
8072 * Count letters in a string.
8074 * Letters are defined as chars not in tags and different from whitespace.
8076 * @category string
8077 * @param string $string The text to be searched for letters.
8078 * @return int The count of letters in the specified text.
8080 function count_letters($string) {
8081 $string = strip_tags($string); // Tags are out now.
8082 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8084 return core_text::strlen($string);
8088 * Generate and return a random string of the specified length.
8090 * @param int $length The length of the string to be created.
8091 * @return string
8093 function random_string($length=15) {
8094 $randombytes = random_bytes_emulate($length);
8095 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8096 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8097 $pool .= '0123456789';
8098 $poollen = strlen($pool);
8099 $string = '';
8100 for ($i = 0; $i < $length; $i++) {
8101 $rand = ord($randombytes[$i]);
8102 $string .= substr($pool, ($rand%($poollen)), 1);
8104 return $string;
8108 * Generate a complex random string (useful for md5 salts)
8110 * This function is based on the above {@link random_string()} however it uses a
8111 * larger pool of characters and generates a string between 24 and 32 characters
8113 * @param int $length Optional if set generates a string to exactly this length
8114 * @return string
8116 function complex_random_string($length=null) {
8117 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8118 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8119 $poollen = strlen($pool);
8120 if ($length===null) {
8121 $length = floor(rand(24, 32));
8123 $randombytes = random_bytes_emulate($length);
8124 $string = '';
8125 for ($i = 0; $i < $length; $i++) {
8126 $rand = ord($randombytes[$i]);
8127 $string .= $pool[($rand%$poollen)];
8129 return $string;
8133 * Try to generates cryptographically secure pseudo-random bytes.
8135 * Note this is achieved by fallbacking between:
8136 * - PHP 7 random_bytes().
8137 * - OpenSSL openssl_random_pseudo_bytes().
8138 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8140 * @param int $length requested length in bytes
8141 * @return string binary data
8143 function random_bytes_emulate($length) {
8144 global $CFG;
8145 if ($length <= 0) {
8146 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8147 return '';
8149 if (function_exists('random_bytes')) {
8150 // Use PHP 7 goodness.
8151 $hash = @random_bytes($length);
8152 if ($hash !== false) {
8153 return $hash;
8156 if (function_exists('openssl_random_pseudo_bytes')) {
8157 // If you have the openssl extension enabled.
8158 $hash = openssl_random_pseudo_bytes($length);
8159 if ($hash !== false) {
8160 return $hash;
8164 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8165 $staticdata = serialize($CFG) . serialize($_SERVER);
8166 $hash = '';
8167 do {
8168 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8169 } while (strlen($hash) < $length);
8171 return substr($hash, 0, $length);
8175 * Given some text (which may contain HTML) and an ideal length,
8176 * this function truncates the text neatly on a word boundary if possible
8178 * @category string
8179 * @param string $text text to be shortened
8180 * @param int $ideal ideal string length
8181 * @param boolean $exact if false, $text will not be cut mid-word
8182 * @param string $ending The string to append if the passed string is truncated
8183 * @return string $truncate shortened string
8185 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8186 // If the plain text is shorter than the maximum length, return the whole text.
8187 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8188 return $text;
8191 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8192 // and only tag in its 'line'.
8193 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8195 $totallength = core_text::strlen($ending);
8196 $truncate = '';
8198 // This array stores information about open and close tags and their position
8199 // in the truncated string. Each item in the array is an object with fields
8200 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8201 // (byte position in truncated text).
8202 $tagdetails = array();
8204 foreach ($lines as $linematchings) {
8205 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8206 if (!empty($linematchings[1])) {
8207 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8208 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8209 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8210 // Record closing tag.
8211 $tagdetails[] = (object) array(
8212 'open' => false,
8213 'tag' => core_text::strtolower($tagmatchings[1]),
8214 'pos' => core_text::strlen($truncate),
8217 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8218 // Record opening tag.
8219 $tagdetails[] = (object) array(
8220 'open' => true,
8221 'tag' => core_text::strtolower($tagmatchings[1]),
8222 'pos' => core_text::strlen($truncate),
8224 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8225 $tagdetails[] = (object) array(
8226 'open' => true,
8227 'tag' => core_text::strtolower('if'),
8228 'pos' => core_text::strlen($truncate),
8230 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8231 $tagdetails[] = (object) array(
8232 'open' => false,
8233 'tag' => core_text::strtolower('if'),
8234 'pos' => core_text::strlen($truncate),
8238 // Add html-tag to $truncate'd text.
8239 $truncate .= $linematchings[1];
8242 // Calculate the length of the plain text part of the line; handle entities as one character.
8243 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8244 if ($totallength + $contentlength > $ideal) {
8245 // The number of characters which are left.
8246 $left = $ideal - $totallength;
8247 $entitieslength = 0;
8248 // Search for html entities.
8249 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)) {
8250 // Calculate the real length of all entities in the legal range.
8251 foreach ($entities[0] as $entity) {
8252 if ($entity[1]+1-$entitieslength <= $left) {
8253 $left--;
8254 $entitieslength += core_text::strlen($entity[0]);
8255 } else {
8256 // No more characters left.
8257 break;
8261 $breakpos = $left + $entitieslength;
8263 // If the words shouldn't be cut in the middle...
8264 if (!$exact) {
8265 // Search the last occurence of a space.
8266 for (; $breakpos > 0; $breakpos--) {
8267 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8268 if ($char === '.' or $char === ' ') {
8269 $breakpos += 1;
8270 break;
8271 } else if (strlen($char) > 2) {
8272 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8273 $breakpos += 1;
8274 break;
8279 if ($breakpos == 0) {
8280 // This deals with the test_shorten_text_no_spaces case.
8281 $breakpos = $left + $entitieslength;
8282 } else if ($breakpos > $left + $entitieslength) {
8283 // This deals with the previous for loop breaking on the first char.
8284 $breakpos = $left + $entitieslength;
8287 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8288 // Maximum length is reached, so get off the loop.
8289 break;
8290 } else {
8291 $truncate .= $linematchings[2];
8292 $totallength += $contentlength;
8295 // If the maximum length is reached, get off the loop.
8296 if ($totallength >= $ideal) {
8297 break;
8301 // Add the defined ending to the text.
8302 $truncate .= $ending;
8304 // Now calculate the list of open html tags based on the truncate position.
8305 $opentags = array();
8306 foreach ($tagdetails as $taginfo) {
8307 if ($taginfo->open) {
8308 // Add tag to the beginning of $opentags list.
8309 array_unshift($opentags, $taginfo->tag);
8310 } else {
8311 // Can have multiple exact same open tags, close the last one.
8312 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8313 if ($pos !== false) {
8314 unset($opentags[$pos]);
8319 // Close all unclosed html-tags.
8320 foreach ($opentags as $tag) {
8321 if ($tag === 'if') {
8322 $truncate .= '<!--<![endif]-->';
8323 } else {
8324 $truncate .= '</' . $tag . '>';
8328 return $truncate;
8332 * Shortens a given filename by removing characters positioned after the ideal string length.
8333 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8334 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8336 * @param string $filename file name
8337 * @param int $length ideal string length
8338 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8339 * @return string $shortened shortened file name
8341 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8342 $shortened = $filename;
8343 // Extract a part of the filename if it's char size exceeds the ideal string length.
8344 if (core_text::strlen($filename) > $length) {
8345 // Exclude extension if present in filename.
8346 $mimetypes = get_mimetypes_array();
8347 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8348 if ($extension && !empty($mimetypes[$extension])) {
8349 $basename = pathinfo($filename, PATHINFO_FILENAME);
8350 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8351 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8352 $shortened .= '.' . $extension;
8353 } else {
8354 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8355 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8358 return $shortened;
8362 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8364 * @param array $path The paths to reduce the length.
8365 * @param int $length Ideal string length
8366 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8367 * @return array $result Shortened paths in array.
8369 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8370 $result = null;
8372 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8373 $carry[] = shorten_filename($singlepath, $length, $includehash);
8374 return $carry;
8375 }, []);
8377 return $result;
8381 * Given dates in seconds, how many weeks is the date from startdate
8382 * The first week is 1, the second 2 etc ...
8384 * @param int $startdate Timestamp for the start date
8385 * @param int $thedate Timestamp for the end date
8386 * @return string
8388 function getweek ($startdate, $thedate) {
8389 if ($thedate < $startdate) {
8390 return 0;
8393 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8397 * Returns a randomly generated password of length $maxlen. inspired by
8399 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8400 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8402 * @param int $maxlen The maximum size of the password being generated.
8403 * @return string
8405 function generate_password($maxlen=10) {
8406 global $CFG;
8408 if (empty($CFG->passwordpolicy)) {
8409 $fillers = PASSWORD_DIGITS;
8410 $wordlist = file($CFG->wordlist);
8411 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8412 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8413 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8414 $password = $word1 . $filler1 . $word2;
8415 } else {
8416 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8417 $digits = $CFG->minpassworddigits;
8418 $lower = $CFG->minpasswordlower;
8419 $upper = $CFG->minpasswordupper;
8420 $nonalphanum = $CFG->minpasswordnonalphanum;
8421 $total = $lower + $upper + $digits + $nonalphanum;
8422 // Var minlength should be the greater one of the two ( $minlen and $total ).
8423 $minlen = $minlen < $total ? $total : $minlen;
8424 // Var maxlen can never be smaller than minlen.
8425 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8426 $additional = $maxlen - $total;
8428 // Make sure we have enough characters to fulfill
8429 // complexity requirements.
8430 $passworddigits = PASSWORD_DIGITS;
8431 while ($digits > strlen($passworddigits)) {
8432 $passworddigits .= PASSWORD_DIGITS;
8434 $passwordlower = PASSWORD_LOWER;
8435 while ($lower > strlen($passwordlower)) {
8436 $passwordlower .= PASSWORD_LOWER;
8438 $passwordupper = PASSWORD_UPPER;
8439 while ($upper > strlen($passwordupper)) {
8440 $passwordupper .= PASSWORD_UPPER;
8442 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8443 while ($nonalphanum > strlen($passwordnonalphanum)) {
8444 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8447 // Now mix and shuffle it all.
8448 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8449 substr(str_shuffle ($passwordupper), 0, $upper) .
8450 substr(str_shuffle ($passworddigits), 0, $digits) .
8451 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8452 substr(str_shuffle ($passwordlower .
8453 $passwordupper .
8454 $passworddigits .
8455 $passwordnonalphanum), 0 , $additional));
8458 return substr ($password, 0, $maxlen);
8462 * Given a float, prints it nicely.
8463 * Localized floats must not be used in calculations!
8465 * The stripzeros feature is intended for making numbers look nicer in small
8466 * areas where it is not necessary to indicate the degree of accuracy by showing
8467 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8468 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8470 * @param float $float The float to print
8471 * @param int $decimalpoints The number of decimal places to print.
8472 * @param bool $localized use localized decimal separator
8473 * @param bool $stripzeros If true, removes final zeros after decimal point
8474 * @return string locale float
8476 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8477 if (is_null($float)) {
8478 return '';
8480 if ($localized) {
8481 $separator = get_string('decsep', 'langconfig');
8482 } else {
8483 $separator = '.';
8485 $result = number_format($float, $decimalpoints, $separator, '');
8486 if ($stripzeros) {
8487 // Remove zeros and final dot if not needed.
8488 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8490 return $result;
8494 * Converts locale specific floating point/comma number back to standard PHP float value
8495 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8497 * @param string $localefloat locale aware float representation
8498 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8499 * @return mixed float|bool - false or the parsed float.
8501 function unformat_float($localefloat, $strict = false) {
8502 $localefloat = trim($localefloat);
8504 if ($localefloat == '') {
8505 return null;
8508 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8509 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8511 if ($strict && !is_numeric($localefloat)) {
8512 return false;
8515 return (float)$localefloat;
8519 * Given a simple array, this shuffles it up just like shuffle()
8520 * Unlike PHP's shuffle() this function works on any machine.
8522 * @param array $array The array to be rearranged
8523 * @return array
8525 function swapshuffle($array) {
8527 $last = count($array) - 1;
8528 for ($i = 0; $i <= $last; $i++) {
8529 $from = rand(0, $last);
8530 $curr = $array[$i];
8531 $array[$i] = $array[$from];
8532 $array[$from] = $curr;
8534 return $array;
8538 * Like {@link swapshuffle()}, but works on associative arrays
8540 * @param array $array The associative array to be rearranged
8541 * @return array
8543 function swapshuffle_assoc($array) {
8545 $newarray = array();
8546 $newkeys = swapshuffle(array_keys($array));
8548 foreach ($newkeys as $newkey) {
8549 $newarray[$newkey] = $array[$newkey];
8551 return $newarray;
8555 * Given an arbitrary array, and a number of draws,
8556 * this function returns an array with that amount
8557 * of items. The indexes are retained.
8559 * @todo Finish documenting this function
8561 * @param array $array
8562 * @param int $draws
8563 * @return array
8565 function draw_rand_array($array, $draws) {
8567 $return = array();
8569 $last = count($array);
8571 if ($draws > $last) {
8572 $draws = $last;
8575 while ($draws > 0) {
8576 $last--;
8578 $keys = array_keys($array);
8579 $rand = rand(0, $last);
8581 $return[$keys[$rand]] = $array[$keys[$rand]];
8582 unset($array[$keys[$rand]]);
8584 $draws--;
8587 return $return;
8591 * Calculate the difference between two microtimes
8593 * @param string $a The first Microtime
8594 * @param string $b The second Microtime
8595 * @return string
8597 function microtime_diff($a, $b) {
8598 list($adec, $asec) = explode(' ', $a);
8599 list($bdec, $bsec) = explode(' ', $b);
8600 return $bsec - $asec + $bdec - $adec;
8604 * Given a list (eg a,b,c,d,e) this function returns
8605 * an array of 1->a, 2->b, 3->c etc
8607 * @param string $list The string to explode into array bits
8608 * @param string $separator The separator used within the list string
8609 * @return array The now assembled array
8611 function make_menu_from_list($list, $separator=',') {
8613 $array = array_reverse(explode($separator, $list), true);
8614 foreach ($array as $key => $item) {
8615 $outarray[$key+1] = trim($item);
8617 return $outarray;
8621 * Creates an array that represents all the current grades that
8622 * can be chosen using the given grading type.
8624 * Negative numbers
8625 * are scales, zero is no grade, and positive numbers are maximum
8626 * grades.
8628 * @todo Finish documenting this function or better deprecated this completely!
8630 * @param int $gradingtype
8631 * @return array
8633 function make_grades_menu($gradingtype) {
8634 global $DB;
8636 $grades = array();
8637 if ($gradingtype < 0) {
8638 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8639 return make_menu_from_list($scale->scale);
8641 } else if ($gradingtype > 0) {
8642 for ($i=$gradingtype; $i>=0; $i--) {
8643 $grades[$i] = $i .' / '. $gradingtype;
8645 return $grades;
8647 return $grades;
8651 * make_unique_id_code
8653 * @todo Finish documenting this function
8655 * @uses $_SERVER
8656 * @param string $extra Extra string to append to the end of the code
8657 * @return string
8659 function make_unique_id_code($extra = '') {
8661 $hostname = 'unknownhost';
8662 if (!empty($_SERVER['HTTP_HOST'])) {
8663 $hostname = $_SERVER['HTTP_HOST'];
8664 } else if (!empty($_ENV['HTTP_HOST'])) {
8665 $hostname = $_ENV['HTTP_HOST'];
8666 } else if (!empty($_SERVER['SERVER_NAME'])) {
8667 $hostname = $_SERVER['SERVER_NAME'];
8668 } else if (!empty($_ENV['SERVER_NAME'])) {
8669 $hostname = $_ENV['SERVER_NAME'];
8672 $date = gmdate("ymdHis");
8674 $random = random_string(6);
8676 if ($extra) {
8677 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8678 } else {
8679 return $hostname .'+'. $date .'+'. $random;
8685 * Function to check the passed address is within the passed subnet
8687 * The parameter is a comma separated string of subnet definitions.
8688 * Subnet strings can be in one of three formats:
8689 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8690 * 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)
8691 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8692 * Code for type 1 modified from user posted comments by mediator at
8693 * {@link http://au.php.net/manual/en/function.ip2long.php}
8695 * @param string $addr The address you are checking
8696 * @param string $subnetstr The string of subnet addresses
8697 * @return bool
8699 function address_in_subnet($addr, $subnetstr) {
8701 if ($addr == '0.0.0.0') {
8702 return false;
8704 $subnets = explode(',', $subnetstr);
8705 $found = false;
8706 $addr = trim($addr);
8707 $addr = cleanremoteaddr($addr, false); // Normalise.
8708 if ($addr === null) {
8709 return false;
8711 $addrparts = explode(':', $addr);
8713 $ipv6 = strpos($addr, ':');
8715 foreach ($subnets as $subnet) {
8716 $subnet = trim($subnet);
8717 if ($subnet === '') {
8718 continue;
8721 if (strpos($subnet, '/') !== false) {
8722 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8723 list($ip, $mask) = explode('/', $subnet);
8724 $mask = trim($mask);
8725 if (!is_number($mask)) {
8726 continue; // Incorect mask number, eh?
8728 $ip = cleanremoteaddr($ip, false); // Normalise.
8729 if ($ip === null) {
8730 continue;
8732 if (strpos($ip, ':') !== false) {
8733 // IPv6.
8734 if (!$ipv6) {
8735 continue;
8737 if ($mask > 128 or $mask < 0) {
8738 continue; // Nonsense.
8740 if ($mask == 0) {
8741 return true; // Any address.
8743 if ($mask == 128) {
8744 if ($ip === $addr) {
8745 return true;
8747 continue;
8749 $ipparts = explode(':', $ip);
8750 $modulo = $mask % 16;
8751 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8752 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8753 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8754 if ($modulo == 0) {
8755 return true;
8757 $pos = ($mask-$modulo)/16;
8758 $ipnet = hexdec($ipparts[$pos]);
8759 $addrnet = hexdec($addrparts[$pos]);
8760 $mask = 0xffff << (16 - $modulo);
8761 if (($addrnet & $mask) == ($ipnet & $mask)) {
8762 return true;
8766 } else {
8767 // IPv4.
8768 if ($ipv6) {
8769 continue;
8771 if ($mask > 32 or $mask < 0) {
8772 continue; // Nonsense.
8774 if ($mask == 0) {
8775 return true;
8777 if ($mask == 32) {
8778 if ($ip === $addr) {
8779 return true;
8781 continue;
8783 $mask = 0xffffffff << (32 - $mask);
8784 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8785 return true;
8789 } else if (strpos($subnet, '-') !== false) {
8790 // 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.
8791 $parts = explode('-', $subnet);
8792 if (count($parts) != 2) {
8793 continue;
8796 if (strpos($subnet, ':') !== false) {
8797 // IPv6.
8798 if (!$ipv6) {
8799 continue;
8801 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8802 if ($ipstart === null) {
8803 continue;
8805 $ipparts = explode(':', $ipstart);
8806 $start = hexdec(array_pop($ipparts));
8807 $ipparts[] = trim($parts[1]);
8808 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8809 if ($ipend === null) {
8810 continue;
8812 $ipparts[7] = '';
8813 $ipnet = implode(':', $ipparts);
8814 if (strpos($addr, $ipnet) !== 0) {
8815 continue;
8817 $ipparts = explode(':', $ipend);
8818 $end = hexdec($ipparts[7]);
8820 $addrend = hexdec($addrparts[7]);
8822 if (($addrend >= $start) and ($addrend <= $end)) {
8823 return true;
8826 } else {
8827 // IPv4.
8828 if ($ipv6) {
8829 continue;
8831 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8832 if ($ipstart === null) {
8833 continue;
8835 $ipparts = explode('.', $ipstart);
8836 $ipparts[3] = trim($parts[1]);
8837 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8838 if ($ipend === null) {
8839 continue;
8842 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8843 return true;
8847 } else {
8848 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8849 if (strpos($subnet, ':') !== false) {
8850 // IPv6.
8851 if (!$ipv6) {
8852 continue;
8854 $parts = explode(':', $subnet);
8855 $count = count($parts);
8856 if ($parts[$count-1] === '') {
8857 unset($parts[$count-1]); // Trim trailing :'s.
8858 $count--;
8859 $subnet = implode('.', $parts);
8861 $isip = cleanremoteaddr($subnet, false); // Normalise.
8862 if ($isip !== null) {
8863 if ($isip === $addr) {
8864 return true;
8866 continue;
8867 } else if ($count > 8) {
8868 continue;
8870 $zeros = array_fill(0, 8-$count, '0');
8871 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8872 if (address_in_subnet($addr, $subnet)) {
8873 return true;
8876 } else {
8877 // IPv4.
8878 if ($ipv6) {
8879 continue;
8881 $parts = explode('.', $subnet);
8882 $count = count($parts);
8883 if ($parts[$count-1] === '') {
8884 unset($parts[$count-1]); // Trim trailing .
8885 $count--;
8886 $subnet = implode('.', $parts);
8888 if ($count == 4) {
8889 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8890 if ($subnet === $addr) {
8891 return true;
8893 continue;
8894 } else if ($count > 4) {
8895 continue;
8897 $zeros = array_fill(0, 4-$count, '0');
8898 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8899 if (address_in_subnet($addr, $subnet)) {
8900 return true;
8906 return false;
8910 * For outputting debugging info
8912 * @param string $string The string to write
8913 * @param string $eol The end of line char(s) to use
8914 * @param string $sleep Period to make the application sleep
8915 * This ensures any messages have time to display before redirect
8917 function mtrace($string, $eol="\n", $sleep=0) {
8918 global $CFG;
8920 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
8921 $fn = $CFG->mtrace_wrapper;
8922 $fn($string, $eol);
8923 return;
8924 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
8925 fwrite(STDOUT, $string.$eol);
8926 } else {
8927 echo $string . $eol;
8930 flush();
8932 // Delay to keep message on user's screen in case of subsequent redirect.
8933 if ($sleep) {
8934 sleep($sleep);
8939 * Replace 1 or more slashes or backslashes to 1 slash
8941 * @param string $path The path to strip
8942 * @return string the path with double slashes removed
8944 function cleardoubleslashes ($path) {
8945 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8949 * Is current ip in give list?
8951 * @param string $list
8952 * @return bool
8954 function remoteip_in_list($list) {
8955 $inlist = false;
8956 $clientip = getremoteaddr(null);
8958 if (!$clientip) {
8959 // Ensure access on cli.
8960 return true;
8963 $list = explode("\n", $list);
8964 foreach ($list as $subnet) {
8965 $subnet = trim($subnet);
8966 if (address_in_subnet($clientip, $subnet)) {
8967 $inlist = true;
8968 break;
8971 return $inlist;
8975 * Returns most reliable client address
8977 * @param string $default If an address can't be determined, then return this
8978 * @return string The remote IP address
8980 function getremoteaddr($default='0.0.0.0') {
8981 global $CFG;
8983 if (empty($CFG->getremoteaddrconf)) {
8984 // This will happen, for example, before just after the upgrade, as the
8985 // user is redirected to the admin screen.
8986 $variablestoskip = 0;
8987 } else {
8988 $variablestoskip = $CFG->getremoteaddrconf;
8990 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8991 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8992 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8993 return $address ? $address : $default;
8996 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8997 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8998 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8999 $address = $forwardedaddresses[0];
9001 if (substr_count($address, ":") > 1) {
9002 // Remove port and brackets from IPv6.
9003 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9004 $address = $matches[1];
9006 } else {
9007 // Remove port from IPv4.
9008 if (substr_count($address, ":") == 1) {
9009 $parts = explode(":", $address);
9010 $address = $parts[0];
9014 $address = cleanremoteaddr($address);
9015 return $address ? $address : $default;
9018 if (!empty($_SERVER['REMOTE_ADDR'])) {
9019 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9020 return $address ? $address : $default;
9021 } else {
9022 return $default;
9027 * Cleans an ip address. Internal addresses are now allowed.
9028 * (Originally local addresses were not allowed.)
9030 * @param string $addr IPv4 or IPv6 address
9031 * @param bool $compress use IPv6 address compression
9032 * @return string normalised ip address string, null if error
9034 function cleanremoteaddr($addr, $compress=false) {
9035 $addr = trim($addr);
9037 if (strpos($addr, ':') !== false) {
9038 // Can be only IPv6.
9039 $parts = explode(':', $addr);
9040 $count = count($parts);
9042 if (strpos($parts[$count-1], '.') !== false) {
9043 // Legacy ipv4 notation.
9044 $last = array_pop($parts);
9045 $ipv4 = cleanremoteaddr($last, true);
9046 if ($ipv4 === null) {
9047 return null;
9049 $bits = explode('.', $ipv4);
9050 $parts[] = dechex($bits[0]).dechex($bits[1]);
9051 $parts[] = dechex($bits[2]).dechex($bits[3]);
9052 $count = count($parts);
9053 $addr = implode(':', $parts);
9056 if ($count < 3 or $count > 8) {
9057 return null; // Severly malformed.
9060 if ($count != 8) {
9061 if (strpos($addr, '::') === false) {
9062 return null; // Malformed.
9064 // Uncompress.
9065 $insertat = array_search('', $parts, true);
9066 $missing = array_fill(0, 1 + 8 - $count, '0');
9067 array_splice($parts, $insertat, 1, $missing);
9068 foreach ($parts as $key => $part) {
9069 if ($part === '') {
9070 $parts[$key] = '0';
9075 $adr = implode(':', $parts);
9076 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9077 return null; // Incorrect format - sorry.
9080 // Normalise 0s and case.
9081 $parts = array_map('hexdec', $parts);
9082 $parts = array_map('dechex', $parts);
9084 $result = implode(':', $parts);
9086 if (!$compress) {
9087 return $result;
9090 if ($result === '0:0:0:0:0:0:0:0') {
9091 return '::'; // All addresses.
9094 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9095 if ($compressed !== $result) {
9096 return $compressed;
9099 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9100 if ($compressed !== $result) {
9101 return $compressed;
9104 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9105 if ($compressed !== $result) {
9106 return $compressed;
9109 return $result;
9112 // First get all things that look like IPv4 addresses.
9113 $parts = array();
9114 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9115 return null;
9117 unset($parts[0]);
9119 foreach ($parts as $key => $match) {
9120 if ($match > 255) {
9121 return null;
9123 $parts[$key] = (int)$match; // Normalise 0s.
9126 return implode('.', $parts);
9131 * Is IP address a public address?
9133 * @param string $ip The ip to check
9134 * @return bool true if the ip is public
9136 function ip_is_public($ip) {
9137 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9141 * This function will make a complete copy of anything it's given,
9142 * regardless of whether it's an object or not.
9144 * @param mixed $thing Something you want cloned
9145 * @return mixed What ever it is you passed it
9147 function fullclone($thing) {
9148 return unserialize(serialize($thing));
9152 * Used to make sure that $min <= $value <= $max
9154 * Make sure that value is between min, and max
9156 * @param int $min The minimum value
9157 * @param int $value The value to check
9158 * @param int $max The maximum value
9159 * @return int
9161 function bounded_number($min, $value, $max) {
9162 if ($value < $min) {
9163 return $min;
9165 if ($value > $max) {
9166 return $max;
9168 return $value;
9172 * Check if there is a nested array within the passed array
9174 * @param array $array
9175 * @return bool true if there is a nested array false otherwise
9177 function array_is_nested($array) {
9178 foreach ($array as $value) {
9179 if (is_array($value)) {
9180 return true;
9183 return false;
9187 * get_performance_info() pairs up with init_performance_info()
9188 * loaded in setup.php. Returns an array with 'html' and 'txt'
9189 * values ready for use, and each of the individual stats provided
9190 * separately as well.
9192 * @return array
9194 function get_performance_info() {
9195 global $CFG, $PERF, $DB, $PAGE;
9197 $info = array();
9198 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9200 $info['html'] = '';
9201 if (!empty($CFG->themedesignermode)) {
9202 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9203 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9205 $info['html'] .= '<ul class="list-unstyled m-l-1 row">'; // Holds userfriendly HTML representation.
9207 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9209 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9210 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9212 if (function_exists('memory_get_usage')) {
9213 $info['memory_total'] = memory_get_usage();
9214 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9215 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9216 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9217 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9220 if (function_exists('memory_get_peak_usage')) {
9221 $info['memory_peak'] = memory_get_peak_usage();
9222 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9223 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9226 $info['html'] .= '</ul><ul class="list-unstyled m-l-1 row">';
9227 $inc = get_included_files();
9228 $info['includecount'] = count($inc);
9229 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9230 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9232 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9233 // We can not track more performance before installation or before PAGE init, sorry.
9234 return $info;
9237 $filtermanager = filter_manager::instance();
9238 if (method_exists($filtermanager, 'get_performance_summary')) {
9239 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9240 $info = array_merge($filterinfo, $info);
9241 foreach ($filterinfo as $key => $value) {
9242 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9243 $info['txt'] .= "$key: $value ";
9247 $stringmanager = get_string_manager();
9248 if (method_exists($stringmanager, 'get_performance_summary')) {
9249 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9250 $info = array_merge($filterinfo, $info);
9251 foreach ($filterinfo as $key => $value) {
9252 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9253 $info['txt'] .= "$key: $value ";
9257 if (!empty($PERF->logwrites)) {
9258 $info['logwrites'] = $PERF->logwrites;
9259 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9260 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9263 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9264 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9265 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9267 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9268 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9269 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9271 if (function_exists('posix_times')) {
9272 $ptimes = posix_times();
9273 if (is_array($ptimes)) {
9274 foreach ($ptimes as $key => $val) {
9275 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9277 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9278 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9279 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9283 // Grab the load average for the last minute.
9284 // /proc will only work under some linux configurations
9285 // while uptime is there under MacOSX/Darwin and other unices.
9286 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9287 list($serverload) = explode(' ', $loadavg[0]);
9288 unset($loadavg);
9289 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9290 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9291 $serverload = $matches[1];
9292 } else {
9293 trigger_error('Could not parse uptime output!');
9296 if (!empty($serverload)) {
9297 $info['serverload'] = $serverload;
9298 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9299 $info['txt'] .= "serverload: {$info['serverload']} ";
9302 // Display size of session if session started.
9303 if ($si = \core\session\manager::get_performance_info()) {
9304 $info['sessionsize'] = $si['size'];
9305 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9306 $info['txt'] .= $si['txt'];
9309 $info['html'] .= '</ul>';
9310 if ($stats = cache_helper::get_stats()) {
9311 $html = '<ul class="cachesused list-unstyled m-l-1 row">';
9312 $html .= '<li class="cache-stats-heading font-weight-bold">Caches used (hits/misses/sets)</li>';
9313 $html .= '</ul><ul class="cachesused list-unstyled m-l-1">';
9314 $text = 'Caches used (hits/misses/sets): ';
9315 $hits = 0;
9316 $misses = 0;
9317 $sets = 0;
9318 foreach ($stats as $definition => $details) {
9319 switch ($details['mode']) {
9320 case cache_store::MODE_APPLICATION:
9321 $modeclass = 'application';
9322 $mode = ' <span title="application cache">[a]</span>';
9323 break;
9324 case cache_store::MODE_SESSION:
9325 $modeclass = 'session';
9326 $mode = ' <span title="session cache">[s]</span>';
9327 break;
9328 case cache_store::MODE_REQUEST:
9329 $modeclass = 'request';
9330 $mode = ' <span title="request cache">[r]</span>';
9331 break;
9333 $html .= '<ul class="cache-definition-stats list-unstyled m-l-1 m-b-1 cache-mode-'.$modeclass.' card d-inline-block">';
9334 $html .= '<li class="cache-definition-stats-heading p-t-1 card-header bg-dark bg-inverse font-weight-bold">' .
9335 $definition . $mode.'</li>';
9336 $text .= "$definition {";
9337 foreach ($details['stores'] as $store => $data) {
9338 $hits += $data['hits'];
9339 $misses += $data['misses'];
9340 $sets += $data['sets'];
9341 if ($data['hits'] == 0 and $data['misses'] > 0) {
9342 $cachestoreclass = 'nohits text-danger';
9343 } else if ($data['hits'] < $data['misses']) {
9344 $cachestoreclass = 'lowhits text-warning';
9345 } else {
9346 $cachestoreclass = 'hihits text-success';
9348 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9349 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">" .
9350 "$store: $data[hits] / $data[misses] / $data[sets]</li>";
9351 // This makes boxes of same sizes.
9352 if (count($details['stores']) == 1) {
9353 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">&nbsp;</li>";
9356 $html .= '</ul>';
9357 $text .= '} ';
9359 $html .= '</ul> ';
9360 $html .= "<div class='cache-total-stats row'>Total: $hits / $misses / $sets</div>";
9361 $info['cachesused'] = "$hits / $misses / $sets";
9362 $info['html'] .= $html;
9363 $info['txt'] .= $text.'. ';
9364 } else {
9365 $info['cachesused'] = '0 / 0 / 0';
9366 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9367 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9370 $info['html'] = '<div class="performanceinfo siteinfo container-fluid">'.$info['html'].'</div>';
9371 return $info;
9375 * Delete directory or only its content
9377 * @param string $dir directory path
9378 * @param bool $contentonly
9379 * @return bool success, true also if dir does not exist
9381 function remove_dir($dir, $contentonly=false) {
9382 if (!file_exists($dir)) {
9383 // Nothing to do.
9384 return true;
9386 if (!$handle = opendir($dir)) {
9387 return false;
9389 $result = true;
9390 while (false!==($item = readdir($handle))) {
9391 if ($item != '.' && $item != '..') {
9392 if (is_dir($dir.'/'.$item)) {
9393 $result = remove_dir($dir.'/'.$item) && $result;
9394 } else {
9395 $result = unlink($dir.'/'.$item) && $result;
9399 closedir($handle);
9400 if ($contentonly) {
9401 clearstatcache(); // Make sure file stat cache is properly invalidated.
9402 return $result;
9404 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9405 clearstatcache(); // Make sure file stat cache is properly invalidated.
9406 return $result;
9410 * Detect if an object or a class contains a given property
9411 * will take an actual object or the name of a class
9413 * @param mix $obj Name of class or real object to test
9414 * @param string $property name of property to find
9415 * @return bool true if property exists
9417 function object_property_exists( $obj, $property ) {
9418 if (is_string( $obj )) {
9419 $properties = get_class_vars( $obj );
9420 } else {
9421 $properties = get_object_vars( $obj );
9423 return array_key_exists( $property, $properties );
9427 * Converts an object into an associative array
9429 * This function converts an object into an associative array by iterating
9430 * over its public properties. Because this function uses the foreach
9431 * construct, Iterators are respected. It works recursively on arrays of objects.
9432 * Arrays and simple values are returned as is.
9434 * If class has magic properties, it can implement IteratorAggregate
9435 * and return all available properties in getIterator()
9437 * @param mixed $var
9438 * @return array
9440 function convert_to_array($var) {
9441 $result = array();
9443 // Loop over elements/properties.
9444 foreach ($var as $key => $value) {
9445 // Recursively convert objects.
9446 if (is_object($value) || is_array($value)) {
9447 $result[$key] = convert_to_array($value);
9448 } else {
9449 // Simple values are untouched.
9450 $result[$key] = $value;
9453 return $result;
9457 * Detect a custom script replacement in the data directory that will
9458 * replace an existing moodle script
9460 * @return string|bool full path name if a custom script exists, false if no custom script exists
9462 function custom_script_path() {
9463 global $CFG, $SCRIPT;
9465 if ($SCRIPT === null) {
9466 // Probably some weird external script.
9467 return false;
9470 $scriptpath = $CFG->customscripts . $SCRIPT;
9472 // Check the custom script exists.
9473 if (file_exists($scriptpath) and is_file($scriptpath)) {
9474 return $scriptpath;
9475 } else {
9476 return false;
9481 * Returns whether or not the user object is a remote MNET user. This function
9482 * is in moodlelib because it does not rely on loading any of the MNET code.
9484 * @param object $user A valid user object
9485 * @return bool True if the user is from a remote Moodle.
9487 function is_mnet_remote_user($user) {
9488 global $CFG;
9490 if (!isset($CFG->mnet_localhost_id)) {
9491 include_once($CFG->dirroot . '/mnet/lib.php');
9492 $env = new mnet_environment();
9493 $env->init();
9494 unset($env);
9497 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9501 * This function will search for browser prefereed languages, setting Moodle
9502 * to use the best one available if $SESSION->lang is undefined
9504 function setup_lang_from_browser() {
9505 global $CFG, $SESSION, $USER;
9507 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9508 // Lang is defined in session or user profile, nothing to do.
9509 return;
9512 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9513 return;
9516 // Extract and clean langs from headers.
9517 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9518 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9519 $rawlangs = explode(',', $rawlangs); // Convert to array.
9520 $langs = array();
9522 $order = 1.0;
9523 foreach ($rawlangs as $lang) {
9524 if (strpos($lang, ';') === false) {
9525 $langs[(string)$order] = $lang;
9526 $order = $order-0.01;
9527 } else {
9528 $parts = explode(';', $lang);
9529 $pos = strpos($parts[1], '=');
9530 $langs[substr($parts[1], $pos+1)] = $parts[0];
9533 krsort($langs, SORT_NUMERIC);
9535 // Look for such langs under standard locations.
9536 foreach ($langs as $lang) {
9537 // Clean it properly for include.
9538 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9539 if (get_string_manager()->translation_exists($lang, false)) {
9540 // Lang exists, set it in session.
9541 $SESSION->lang = $lang;
9542 // We have finished. Go out.
9543 break;
9546 return;
9550 * Check if $url matches anything in proxybypass list
9552 * Any errors just result in the proxy being used (least bad)
9554 * @param string $url url to check
9555 * @return boolean true if we should bypass the proxy
9557 function is_proxybypass( $url ) {
9558 global $CFG;
9560 // Sanity check.
9561 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9562 return false;
9565 // Get the host part out of the url.
9566 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9567 return false;
9570 // Get the possible bypass hosts into an array.
9571 $matches = explode( ',', $CFG->proxybypass );
9573 // Check for a match.
9574 // (IPs need to match the left hand side and hosts the right of the url,
9575 // but we can recklessly check both as there can't be a false +ve).
9576 foreach ($matches as $match) {
9577 $match = trim($match);
9579 // Try for IP match (Left side).
9580 $lhs = substr($host, 0, strlen($match));
9581 if (strcasecmp($match, $lhs)==0) {
9582 return true;
9585 // Try for host match (Right side).
9586 $rhs = substr($host, -strlen($match));
9587 if (strcasecmp($match, $rhs)==0) {
9588 return true;
9592 // Nothing matched.
9593 return false;
9597 * Check if the passed navigation is of the new style
9599 * @param mixed $navigation
9600 * @return bool true for yes false for no
9602 function is_newnav($navigation) {
9603 if (is_array($navigation) && !empty($navigation['newnav'])) {
9604 return true;
9605 } else {
9606 return false;
9611 * Checks whether the given variable name is defined as a variable within the given object.
9613 * This will NOT work with stdClass objects, which have no class variables.
9615 * @param string $var The variable name
9616 * @param object $object The object to check
9617 * @return boolean
9619 function in_object_vars($var, $object) {
9620 $classvars = get_class_vars(get_class($object));
9621 $classvars = array_keys($classvars);
9622 return in_array($var, $classvars);
9626 * Returns an array without repeated objects.
9627 * This function is similar to array_unique, but for arrays that have objects as values
9629 * @param array $array
9630 * @param bool $keepkeyassoc
9631 * @return array
9633 function object_array_unique($array, $keepkeyassoc = true) {
9634 $duplicatekeys = array();
9635 $tmp = array();
9637 foreach ($array as $key => $val) {
9638 // Convert objects to arrays, in_array() does not support objects.
9639 if (is_object($val)) {
9640 $val = (array)$val;
9643 if (!in_array($val, $tmp)) {
9644 $tmp[] = $val;
9645 } else {
9646 $duplicatekeys[] = $key;
9650 foreach ($duplicatekeys as $key) {
9651 unset($array[$key]);
9654 return $keepkeyassoc ? $array : array_values($array);
9658 * Is a userid the primary administrator?
9660 * @param int $userid int id of user to check
9661 * @return boolean
9663 function is_primary_admin($userid) {
9664 $primaryadmin = get_admin();
9666 if ($userid == $primaryadmin->id) {
9667 return true;
9668 } else {
9669 return false;
9674 * Returns the site identifier
9676 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9678 function get_site_identifier() {
9679 global $CFG;
9680 // Check to see if it is missing. If so, initialise it.
9681 if (empty($CFG->siteidentifier)) {
9682 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9684 // Return it.
9685 return $CFG->siteidentifier;
9689 * Check whether the given password has no more than the specified
9690 * number of consecutive identical characters.
9692 * @param string $password password to be checked against the password policy
9693 * @param integer $maxchars maximum number of consecutive identical characters
9694 * @return bool
9696 function check_consecutive_identical_characters($password, $maxchars) {
9698 if ($maxchars < 1) {
9699 return true; // Zero 0 is to disable this check.
9701 if (strlen($password) <= $maxchars) {
9702 return true; // Too short to fail this test.
9705 $previouschar = '';
9706 $consecutivecount = 1;
9707 foreach (str_split($password) as $char) {
9708 if ($char != $previouschar) {
9709 $consecutivecount = 1;
9710 } else {
9711 $consecutivecount++;
9712 if ($consecutivecount > $maxchars) {
9713 return false; // Check failed already.
9717 $previouschar = $char;
9720 return true;
9724 * Helper function to do partial function binding.
9725 * so we can use it for preg_replace_callback, for example
9726 * this works with php functions, user functions, static methods and class methods
9727 * it returns you a callback that you can pass on like so:
9729 * $callback = partial('somefunction', $arg1, $arg2);
9730 * or
9731 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9732 * or even
9733 * $obj = new someclass();
9734 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9736 * and then the arguments that are passed through at calltime are appended to the argument list.
9738 * @param mixed $function a php callback
9739 * @param mixed $arg1,... $argv arguments to partially bind with
9740 * @return array Array callback
9742 function partial() {
9743 if (!class_exists('partial')) {
9745 * Used to manage function binding.
9746 * @copyright 2009 Penny Leach
9747 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9749 class partial{
9750 /** @var array */
9751 public $values = array();
9752 /** @var string The function to call as a callback. */
9753 public $func;
9755 * Constructor
9756 * @param string $func
9757 * @param array $args
9759 public function __construct($func, $args) {
9760 $this->values = $args;
9761 $this->func = $func;
9764 * Calls the callback function.
9765 * @return mixed
9767 public function method() {
9768 $args = func_get_args();
9769 return call_user_func_array($this->func, array_merge($this->values, $args));
9773 $args = func_get_args();
9774 $func = array_shift($args);
9775 $p = new partial($func, $args);
9776 return array($p, 'method');
9780 * helper function to load up and initialise the mnet environment
9781 * this must be called before you use mnet functions.
9783 * @return mnet_environment the equivalent of old $MNET global
9785 function get_mnet_environment() {
9786 global $CFG;
9787 require_once($CFG->dirroot . '/mnet/lib.php');
9788 static $instance = null;
9789 if (empty($instance)) {
9790 $instance = new mnet_environment();
9791 $instance->init();
9793 return $instance;
9797 * during xmlrpc server code execution, any code wishing to access
9798 * information about the remote peer must use this to get it.
9800 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9802 function get_mnet_remote_client() {
9803 if (!defined('MNET_SERVER')) {
9804 debugging(get_string('notinxmlrpcserver', 'mnet'));
9805 return false;
9807 global $MNET_REMOTE_CLIENT;
9808 if (isset($MNET_REMOTE_CLIENT)) {
9809 return $MNET_REMOTE_CLIENT;
9811 return false;
9815 * during the xmlrpc server code execution, this will be called
9816 * to setup the object returned by {@link get_mnet_remote_client}
9818 * @param mnet_remote_client $client the client to set up
9819 * @throws moodle_exception
9821 function set_mnet_remote_client($client) {
9822 if (!defined('MNET_SERVER')) {
9823 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9825 global $MNET_REMOTE_CLIENT;
9826 $MNET_REMOTE_CLIENT = $client;
9830 * return the jump url for a given remote user
9831 * this is used for rewriting forum post links in emails, etc
9833 * @param stdclass $user the user to get the idp url for
9835 function mnet_get_idp_jump_url($user) {
9836 global $CFG;
9838 static $mnetjumps = array();
9839 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9840 $idp = mnet_get_peer_host($user->mnethostid);
9841 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9842 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9844 return $mnetjumps[$user->mnethostid];
9848 * Gets the homepage to use for the current user
9850 * @return int One of HOMEPAGE_*
9852 function get_home_page() {
9853 global $CFG;
9855 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9856 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9857 return HOMEPAGE_MY;
9858 } else {
9859 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9862 return HOMEPAGE_SITE;
9866 * Gets the name of a course to be displayed when showing a list of courses.
9867 * By default this is just $course->fullname but user can configure it. The
9868 * result of this function should be passed through print_string.
9869 * @param stdClass|course_in_list $course Moodle course object
9870 * @return string Display name of course (either fullname or short + fullname)
9872 function get_course_display_name_for_list($course) {
9873 global $CFG;
9874 if (!empty($CFG->courselistshortnames)) {
9875 if (!($course instanceof stdClass)) {
9876 $course = (object)convert_to_array($course);
9878 return get_string('courseextendednamedisplay', '', $course);
9879 } else {
9880 return $course->fullname;
9885 * Safe analogue of unserialize() that can only parse arrays
9887 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
9888 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
9889 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
9891 * @param string $expression
9892 * @return array|bool either parsed array or false if parsing was impossible.
9894 function unserialize_array($expression) {
9895 $subs = [];
9896 // Find nested arrays, parse them and store in $subs , substitute with special string.
9897 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
9898 $key = '--SUB' . count($subs) . '--';
9899 $subs[$key] = unserialize_array($matches[2]);
9900 if ($subs[$key] === false) {
9901 return false;
9903 $expression = str_replace($matches[2], $key . ';', $expression);
9906 // Check the expression is an array.
9907 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
9908 return false;
9910 // Get the size and elements of an array (key;value;key;value;....).
9911 $parts = explode(';', $matches1[2]);
9912 $size = intval($matches1[1]);
9913 if (count($parts) < $size * 2 + 1) {
9914 return false;
9916 // Analyze each part and make sure it is an integer or string or a substitute.
9917 $value = [];
9918 for ($i = 0; $i < $size * 2; $i++) {
9919 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
9920 $parts[$i] = (int)$matches2[1];
9921 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
9922 $parts[$i] = $matches3[2];
9923 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
9924 $parts[$i] = $subs[$parts[$i]];
9925 } else {
9926 return false;
9929 // Combine keys and values.
9930 for ($i = 0; $i < $size * 2; $i += 2) {
9931 $value[$parts[$i]] = $parts[$i+1];
9933 return $value;
9937 * The lang_string class
9939 * This special class is used to create an object representation of a string request.
9940 * It is special because processing doesn't occur until the object is first used.
9941 * The class was created especially to aid performance in areas where strings were
9942 * required to be generated but were not necessarily used.
9943 * As an example the admin tree when generated uses over 1500 strings, of which
9944 * normally only 1/3 are ever actually printed at any time.
9945 * The performance advantage is achieved by not actually processing strings that
9946 * arn't being used, as such reducing the processing required for the page.
9948 * How to use the lang_string class?
9949 * There are two methods of using the lang_string class, first through the
9950 * forth argument of the get_string function, and secondly directly.
9951 * The following are examples of both.
9952 * 1. Through get_string calls e.g.
9953 * $string = get_string($identifier, $component, $a, true);
9954 * $string = get_string('yes', 'moodle', null, true);
9955 * 2. Direct instantiation
9956 * $string = new lang_string($identifier, $component, $a, $lang);
9957 * $string = new lang_string('yes');
9959 * How do I use a lang_string object?
9960 * The lang_string object makes use of a magic __toString method so that you
9961 * are able to use the object exactly as you would use a string in most cases.
9962 * This means you are able to collect it into a variable and then directly
9963 * echo it, or concatenate it into another string, or similar.
9964 * The other thing you can do is manually get the string by calling the
9965 * lang_strings out method e.g.
9966 * $string = new lang_string('yes');
9967 * $string->out();
9968 * Also worth noting is that the out method can take one argument, $lang which
9969 * allows the developer to change the language on the fly.
9971 * When should I use a lang_string object?
9972 * The lang_string object is designed to be used in any situation where a
9973 * string may not be needed, but needs to be generated.
9974 * The admin tree is a good example of where lang_string objects should be
9975 * used.
9976 * A more practical example would be any class that requries strings that may
9977 * not be printed (after all classes get renderer by renderers and who knows
9978 * what they will do ;))
9980 * When should I not use a lang_string object?
9981 * Don't use lang_strings when you are going to use a string immediately.
9982 * There is no need as it will be processed immediately and there will be no
9983 * advantage, and in fact perhaps a negative hit as a class has to be
9984 * instantiated for a lang_string object, however get_string won't require
9985 * that.
9987 * Limitations:
9988 * 1. You cannot use a lang_string object as an array offset. Doing so will
9989 * result in PHP throwing an error. (You can use it as an object property!)
9991 * @package core
9992 * @category string
9993 * @copyright 2011 Sam Hemelryk
9994 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9996 class lang_string {
9998 /** @var string The strings identifier */
9999 protected $identifier;
10000 /** @var string The strings component. Default '' */
10001 protected $component = '';
10002 /** @var array|stdClass Any arguments required for the string. Default null */
10003 protected $a = null;
10004 /** @var string The language to use when processing the string. Default null */
10005 protected $lang = null;
10007 /** @var string The processed string (once processed) */
10008 protected $string = null;
10011 * A special boolean. If set to true then the object has been woken up and
10012 * cannot be regenerated. If this is set then $this->string MUST be used.
10013 * @var bool
10015 protected $forcedstring = false;
10018 * Constructs a lang_string object
10020 * This function should do as little processing as possible to ensure the best
10021 * performance for strings that won't be used.
10023 * @param string $identifier The strings identifier
10024 * @param string $component The strings component
10025 * @param stdClass|array $a Any arguments the string requires
10026 * @param string $lang The language to use when processing the string.
10027 * @throws coding_exception
10029 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10030 if (empty($component)) {
10031 $component = 'moodle';
10034 $this->identifier = $identifier;
10035 $this->component = $component;
10036 $this->lang = $lang;
10038 // We MUST duplicate $a to ensure that it if it changes by reference those
10039 // changes are not carried across.
10040 // To do this we always ensure $a or its properties/values are strings
10041 // and that any properties/values that arn't convertable are forgotten.
10042 if (!empty($a)) {
10043 if (is_scalar($a)) {
10044 $this->a = $a;
10045 } else if ($a instanceof lang_string) {
10046 $this->a = $a->out();
10047 } else if (is_object($a) or is_array($a)) {
10048 $a = (array)$a;
10049 $this->a = array();
10050 foreach ($a as $key => $value) {
10051 // Make sure conversion errors don't get displayed (results in '').
10052 if (is_array($value)) {
10053 $this->a[$key] = '';
10054 } else if (is_object($value)) {
10055 if (method_exists($value, '__toString')) {
10056 $this->a[$key] = $value->__toString();
10057 } else {
10058 $this->a[$key] = '';
10060 } else {
10061 $this->a[$key] = (string)$value;
10067 if (debugging(false, DEBUG_DEVELOPER)) {
10068 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10069 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10071 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10072 throw new coding_exception('Invalid string compontent. Please check your string definition');
10074 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10075 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10081 * Processes the string.
10083 * This function actually processes the string, stores it in the string property
10084 * and then returns it.
10085 * You will notice that this function is VERY similar to the get_string method.
10086 * That is because it is pretty much doing the same thing.
10087 * However as this function is an upgrade it isn't as tolerant to backwards
10088 * compatibility.
10090 * @return string
10091 * @throws coding_exception
10093 protected function get_string() {
10094 global $CFG;
10096 // Check if we need to process the string.
10097 if ($this->string === null) {
10098 // Check the quality of the identifier.
10099 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10100 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition', DEBUG_DEVELOPER);
10103 // Process the string.
10104 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10105 // Debugging feature lets you display string identifier and component.
10106 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10107 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10110 // Return the string.
10111 return $this->string;
10115 * Returns the string
10117 * @param string $lang The langauge to use when processing the string
10118 * @return string
10120 public function out($lang = null) {
10121 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10122 if ($this->forcedstring) {
10123 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10124 return $this->get_string();
10126 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10127 return $translatedstring->out();
10129 return $this->get_string();
10133 * Magic __toString method for printing a string
10135 * @return string
10137 public function __toString() {
10138 return $this->get_string();
10142 * Magic __set_state method used for var_export
10144 * @return string
10146 public function __set_state() {
10147 return $this->get_string();
10151 * Prepares the lang_string for sleep and stores only the forcedstring and
10152 * string properties... the string cannot be regenerated so we need to ensure
10153 * it is generated for this.
10155 * @return string
10157 public function __sleep() {
10158 $this->get_string();
10159 $this->forcedstring = true;
10160 return array('forcedstring', 'string', 'lang');
10164 * Returns the identifier.
10166 * @return string
10168 public function get_identifier() {
10169 return $this->identifier;
10173 * Returns the component.
10175 * @return string
10177 public function get_component() {
10178 return $this->component;
10183 * Get human readable name describing the given callable.
10185 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10186 * It does not check if the callable actually exists.
10188 * @param callable|string|array $callable
10189 * @return string|bool Human readable name of callable, or false if not a valid callable.
10191 function get_callable_name($callable) {
10193 if (!is_callable($callable, true, $name)) {
10194 return false;
10196 } else {
10197 return $name;