Merge branch 'MDL-59642-master' of git://github.com/andrewnicols/moodle
[moodle.git] / lib / moodlelib.php
blob9e5ede0ded3d1069721d2a444321a450db272ff3
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 recieving
119 * the input (required/optional_param or formslib) and then sanitse 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');
442 /** Unspecified module archetype */
443 define('MOD_ARCHETYPE_OTHER', 0);
444 /** Resource-like type module */
445 define('MOD_ARCHETYPE_RESOURCE', 1);
446 /** Assignment module archetype */
447 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
448 /** System (not user-addable) module archetype */
449 define('MOD_ARCHETYPE_SYSTEM', 3);
452 * Return this from modname_get_types callback to use default display in activity chooser.
453 * Deprecated, will be removed in 3.5, TODO MDL-53697.
454 * @deprecated since Moodle 3.1
456 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
459 * Security token used for allowing access
460 * from external application such as web services.
461 * Scripts do not use any session, performance is relatively
462 * low because we need to load access info in each request.
463 * Scripts are executed in parallel.
465 define('EXTERNAL_TOKEN_PERMANENT', 0);
468 * Security token used for allowing access
469 * of embedded applications, the code is executed in the
470 * active user session. Token is invalidated after user logs out.
471 * Scripts are executed serially - normal session locking is used.
473 define('EXTERNAL_TOKEN_EMBEDDED', 1);
476 * The home page should be the site home
478 define('HOMEPAGE_SITE', 0);
480 * The home page should be the users my page
482 define('HOMEPAGE_MY', 1);
484 * The home page can be chosen by the user
486 define('HOMEPAGE_USER', 2);
489 * Hub directory url (should be moodle.org)
491 define('HUB_HUBDIRECTORYURL', "https://hubdirectory.moodle.org");
495 * Moodle.net url (should be moodle.net)
497 define('HUB_MOODLEORGHUBURL', "https://moodle.net");
498 define('HUB_OLDMOODLEORGHUBURL', "http://hub.moodle.org");
501 * Moodle mobile app service name
503 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
506 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
508 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
511 * Course display settings: display all sections on one page.
513 define('COURSE_DISPLAY_SINGLEPAGE', 0);
515 * Course display settings: split pages into a page per section.
517 define('COURSE_DISPLAY_MULTIPAGE', 1);
520 * Authentication constant: String used in password field when password is not stored.
522 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
525 * Email from header to never include via information.
527 define('EMAIL_VIA_NEVER', 0);
530 * Email from header to always include via information.
532 define('EMAIL_VIA_ALWAYS', 1);
535 * Email from header to only include via information if the address is no-reply.
537 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
539 // PARAMETER HANDLING.
542 * Returns a particular value for the named variable, taken from
543 * POST or GET. If the parameter doesn't exist then an error is
544 * thrown because we require this variable.
546 * This function should be used to initialise all required values
547 * in a script that are based on parameters. Usually it will be
548 * used like this:
549 * $id = required_param('id', PARAM_INT);
551 * Please note the $type parameter is now required and the value can not be array.
553 * @param string $parname the name of the page parameter we want
554 * @param string $type expected type of parameter
555 * @return mixed
556 * @throws coding_exception
558 function required_param($parname, $type) {
559 if (func_num_args() != 2 or empty($parname) or empty($type)) {
560 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
562 // POST has precedence.
563 if (isset($_POST[$parname])) {
564 $param = $_POST[$parname];
565 } else if (isset($_GET[$parname])) {
566 $param = $_GET[$parname];
567 } else {
568 print_error('missingparam', '', '', $parname);
571 if (is_array($param)) {
572 debugging('Invalid array parameter detected in required_param(): '.$parname);
573 // TODO: switch to fatal error in Moodle 2.3.
574 return required_param_array($parname, $type);
577 return clean_param($param, $type);
581 * Returns a particular array value for the named variable, taken from
582 * POST or GET. If the parameter doesn't exist then an error is
583 * thrown because we require this variable.
585 * This function should be used to initialise all required values
586 * in a script that are based on parameters. Usually it will be
587 * used like this:
588 * $ids = required_param_array('ids', PARAM_INT);
590 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
592 * @param string $parname the name of the page parameter we want
593 * @param string $type expected type of parameter
594 * @return array
595 * @throws coding_exception
597 function required_param_array($parname, $type) {
598 if (func_num_args() != 2 or empty($parname) or empty($type)) {
599 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
601 // POST has precedence.
602 if (isset($_POST[$parname])) {
603 $param = $_POST[$parname];
604 } else if (isset($_GET[$parname])) {
605 $param = $_GET[$parname];
606 } else {
607 print_error('missingparam', '', '', $parname);
609 if (!is_array($param)) {
610 print_error('missingparam', '', '', $parname);
613 $result = array();
614 foreach ($param as $key => $value) {
615 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
616 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
617 continue;
619 $result[$key] = clean_param($value, $type);
622 return $result;
626 * Returns a particular value for the named variable, taken from
627 * POST or GET, otherwise returning a given default.
629 * This function should be used to initialise all optional values
630 * in a script that are based on parameters. Usually it will be
631 * used like this:
632 * $name = optional_param('name', 'Fred', PARAM_TEXT);
634 * Please note the $type parameter is now required and the value can not be array.
636 * @param string $parname the name of the page parameter we want
637 * @param mixed $default the default value to return if nothing is found
638 * @param string $type expected type of parameter
639 * @return mixed
640 * @throws coding_exception
642 function optional_param($parname, $default, $type) {
643 if (func_num_args() != 3 or empty($parname) or empty($type)) {
644 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
647 // POST has precedence.
648 if (isset($_POST[$parname])) {
649 $param = $_POST[$parname];
650 } else if (isset($_GET[$parname])) {
651 $param = $_GET[$parname];
652 } else {
653 return $default;
656 if (is_array($param)) {
657 debugging('Invalid array parameter detected in required_param(): '.$parname);
658 // TODO: switch to $default in Moodle 2.3.
659 return optional_param_array($parname, $default, $type);
662 return clean_param($param, $type);
666 * Returns a particular array value for the named variable, taken from
667 * POST or GET, otherwise returning a given default.
669 * This function should be used to initialise all optional values
670 * in a script that are based on parameters. Usually it will be
671 * used like this:
672 * $ids = optional_param('id', array(), PARAM_INT);
674 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
676 * @param string $parname the name of the page parameter we want
677 * @param mixed $default the default value to return if nothing is found
678 * @param string $type expected type of parameter
679 * @return array
680 * @throws coding_exception
682 function optional_param_array($parname, $default, $type) {
683 if (func_num_args() != 3 or empty($parname) or empty($type)) {
684 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
687 // POST has precedence.
688 if (isset($_POST[$parname])) {
689 $param = $_POST[$parname];
690 } else if (isset($_GET[$parname])) {
691 $param = $_GET[$parname];
692 } else {
693 return $default;
695 if (!is_array($param)) {
696 debugging('optional_param_array() expects array parameters only: '.$parname);
697 return $default;
700 $result = array();
701 foreach ($param as $key => $value) {
702 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
703 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
704 continue;
706 $result[$key] = clean_param($value, $type);
709 return $result;
713 * Strict validation of parameter values, the values are only converted
714 * to requested PHP type. Internally it is using clean_param, the values
715 * before and after cleaning must be equal - otherwise
716 * an invalid_parameter_exception is thrown.
717 * Objects and classes are not accepted.
719 * @param mixed $param
720 * @param string $type PARAM_ constant
721 * @param bool $allownull are nulls valid value?
722 * @param string $debuginfo optional debug information
723 * @return mixed the $param value converted to PHP type
724 * @throws invalid_parameter_exception if $param is not of given type
726 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
727 if (is_null($param)) {
728 if ($allownull == NULL_ALLOWED) {
729 return null;
730 } else {
731 throw new invalid_parameter_exception($debuginfo);
734 if (is_array($param) or is_object($param)) {
735 throw new invalid_parameter_exception($debuginfo);
738 $cleaned = clean_param($param, $type);
740 if ($type == PARAM_FLOAT) {
741 // Do not detect precision loss here.
742 if (is_float($param) or is_int($param)) {
743 // These always fit.
744 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
745 throw new invalid_parameter_exception($debuginfo);
747 } else if ((string)$param !== (string)$cleaned) {
748 // Conversion to string is usually lossless.
749 throw new invalid_parameter_exception($debuginfo);
752 return $cleaned;
756 * Makes sure array contains only the allowed types, this function does not validate array key names!
758 * <code>
759 * $options = clean_param($options, PARAM_INT);
760 * </code>
762 * @param array $param the variable array we are cleaning
763 * @param string $type expected format of param after cleaning.
764 * @param bool $recursive clean recursive arrays
765 * @return array
766 * @throws coding_exception
768 function clean_param_array(array $param = null, $type, $recursive = false) {
769 // Convert null to empty array.
770 $param = (array)$param;
771 foreach ($param as $key => $value) {
772 if (is_array($value)) {
773 if ($recursive) {
774 $param[$key] = clean_param_array($value, $type, true);
775 } else {
776 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
778 } else {
779 $param[$key] = clean_param($value, $type);
782 return $param;
786 * Used by {@link optional_param()} and {@link required_param()} to
787 * clean the variables and/or cast to specific types, based on
788 * an options field.
789 * <code>
790 * $course->format = clean_param($course->format, PARAM_ALPHA);
791 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
792 * </code>
794 * @param mixed $param the variable we are cleaning
795 * @param string $type expected format of param after cleaning.
796 * @return mixed
797 * @throws coding_exception
799 function clean_param($param, $type) {
800 global $CFG;
802 if (is_array($param)) {
803 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
804 } else if (is_object($param)) {
805 if (method_exists($param, '__toString')) {
806 $param = $param->__toString();
807 } else {
808 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
812 switch ($type) {
813 case PARAM_RAW:
814 // No cleaning at all.
815 $param = fix_utf8($param);
816 return $param;
818 case PARAM_RAW_TRIMMED:
819 // No cleaning, but strip leading and trailing whitespace.
820 $param = fix_utf8($param);
821 return trim($param);
823 case PARAM_CLEAN:
824 // General HTML cleaning, try to use more specific type if possible this is deprecated!
825 // Please use more specific type instead.
826 if (is_numeric($param)) {
827 return $param;
829 $param = fix_utf8($param);
830 // Sweep for scripts, etc.
831 return clean_text($param);
833 case PARAM_CLEANHTML:
834 // Clean html fragment.
835 $param = fix_utf8($param);
836 // Sweep for scripts, etc.
837 $param = clean_text($param, FORMAT_HTML);
838 return trim($param);
840 case PARAM_INT:
841 // Convert to integer.
842 return (int)$param;
844 case PARAM_FLOAT:
845 // Convert to float.
846 return (float)$param;
848 case PARAM_ALPHA:
849 // Remove everything not `a-z`.
850 return preg_replace('/[^a-zA-Z]/i', '', $param);
852 case PARAM_ALPHAEXT:
853 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
854 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
856 case PARAM_ALPHANUM:
857 // Remove everything not `a-zA-Z0-9`.
858 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
860 case PARAM_ALPHANUMEXT:
861 // Remove everything not `a-zA-Z0-9_-`.
862 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
864 case PARAM_SEQUENCE:
865 // Remove everything not `0-9,`.
866 return preg_replace('/[^0-9,]/i', '', $param);
868 case PARAM_BOOL:
869 // Convert to 1 or 0.
870 $tempstr = strtolower($param);
871 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
872 $param = 1;
873 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
874 $param = 0;
875 } else {
876 $param = empty($param) ? 0 : 1;
878 return $param;
880 case PARAM_NOTAGS:
881 // Strip all tags.
882 $param = fix_utf8($param);
883 return strip_tags($param);
885 case PARAM_TEXT:
886 // Leave only tags needed for multilang.
887 $param = fix_utf8($param);
888 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
889 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
890 do {
891 if (strpos($param, '</lang>') !== false) {
892 // Old and future mutilang syntax.
893 $param = strip_tags($param, '<lang>');
894 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
895 break;
897 $open = false;
898 foreach ($matches[0] as $match) {
899 if ($match === '</lang>') {
900 if ($open) {
901 $open = false;
902 continue;
903 } else {
904 break 2;
907 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
908 break 2;
909 } else {
910 $open = true;
913 if ($open) {
914 break;
916 return $param;
918 } else if (strpos($param, '</span>') !== false) {
919 // Current problematic multilang syntax.
920 $param = strip_tags($param, '<span>');
921 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
922 break;
924 $open = false;
925 foreach ($matches[0] as $match) {
926 if ($match === '</span>') {
927 if ($open) {
928 $open = false;
929 continue;
930 } else {
931 break 2;
934 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
935 break 2;
936 } else {
937 $open = true;
940 if ($open) {
941 break;
943 return $param;
945 } while (false);
946 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
947 return strip_tags($param);
949 case PARAM_COMPONENT:
950 // We do not want any guessing here, either the name is correct or not
951 // please note only normalised component names are accepted.
952 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
953 return '';
955 if (strpos($param, '__') !== false) {
956 return '';
958 if (strpos($param, 'mod_') === 0) {
959 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
960 if (substr_count($param, '_') != 1) {
961 return '';
964 return $param;
966 case PARAM_PLUGIN:
967 case PARAM_AREA:
968 // We do not want any guessing here, either the name is correct or not.
969 if (!is_valid_plugin_name($param)) {
970 return '';
972 return $param;
974 case PARAM_SAFEDIR:
975 // Remove everything not a-zA-Z0-9_- .
976 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
978 case PARAM_SAFEPATH:
979 // Remove everything not a-zA-Z0-9/_- .
980 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
982 case PARAM_FILE:
983 // Strip all suspicious characters from filename.
984 $param = fix_utf8($param);
985 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
986 if ($param === '.' || $param === '..') {
987 $param = '';
989 return $param;
991 case PARAM_PATH:
992 // Strip all suspicious characters from file path.
993 $param = fix_utf8($param);
994 $param = str_replace('\\', '/', $param);
996 // Explode the path and clean each element using the PARAM_FILE rules.
997 $breadcrumb = explode('/', $param);
998 foreach ($breadcrumb as $key => $crumb) {
999 if ($crumb === '.' && $key === 0) {
1000 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1001 } else {
1002 $crumb = clean_param($crumb, PARAM_FILE);
1004 $breadcrumb[$key] = $crumb;
1006 $param = implode('/', $breadcrumb);
1008 // Remove multiple current path (./././) and multiple slashes (///).
1009 $param = preg_replace('~//+~', '/', $param);
1010 $param = preg_replace('~/(\./)+~', '/', $param);
1011 return $param;
1013 case PARAM_HOST:
1014 // Allow FQDN or IPv4 dotted quad.
1015 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1016 // Match ipv4 dotted quad.
1017 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1018 // Confirm values are ok.
1019 if ( $match[0] > 255
1020 || $match[1] > 255
1021 || $match[3] > 255
1022 || $match[4] > 255 ) {
1023 // Hmmm, what kind of dotted quad is this?
1024 $param = '';
1026 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1027 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1028 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1030 // All is ok - $param is respected.
1031 } else {
1032 // All is not ok...
1033 $param='';
1035 return $param;
1037 case PARAM_URL: // Allow safe ftp, http, mailto urls.
1038 $param = fix_utf8($param);
1039 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1040 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1041 // All is ok, param is respected.
1042 } else {
1043 // Not really ok.
1044 $param ='';
1046 return $param;
1048 case PARAM_LOCALURL:
1049 // Allow http absolute, root relative and relative URLs within wwwroot.
1050 $param = clean_param($param, PARAM_URL);
1051 if (!empty($param)) {
1053 // Simulate the HTTPS version of the site.
1054 $httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot);
1056 if ($param === $CFG->wwwroot) {
1057 // Exact match;
1058 } else if (!empty($CFG->loginhttps) && $param === $httpswwwroot) {
1059 // Exact match;
1060 } else if (preg_match(':^/:', $param)) {
1061 // Root-relative, ok!
1062 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1063 // Absolute, and matches our wwwroot.
1064 } else if (!empty($CFG->loginhttps) && preg_match('/^' . preg_quote($httpswwwroot . '/', '/') . '/i', $param)) {
1065 // Absolute, and matches our httpswwwroot.
1066 } else {
1067 // Relative - let's make sure there are no tricks.
1068 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1069 // Looks ok.
1070 } else {
1071 $param = '';
1075 return $param;
1077 case PARAM_PEM:
1078 $param = trim($param);
1079 // PEM formatted strings may contain letters/numbers and the symbols:
1080 // forward slash: /
1081 // plus sign: +
1082 // equal sign: =
1083 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1084 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1085 list($wholething, $body) = $matches;
1086 unset($wholething, $matches);
1087 $b64 = clean_param($body, PARAM_BASE64);
1088 if (!empty($b64)) {
1089 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1090 } else {
1091 return '';
1094 return '';
1096 case PARAM_BASE64:
1097 if (!empty($param)) {
1098 // PEM formatted strings may contain letters/numbers and the symbols
1099 // forward slash: /
1100 // plus sign: +
1101 // equal sign: =.
1102 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1103 return '';
1105 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1106 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1107 // than (or equal to) 64 characters long.
1108 for ($i=0, $j=count($lines); $i < $j; $i++) {
1109 if ($i + 1 == $j) {
1110 if (64 < strlen($lines[$i])) {
1111 return '';
1113 continue;
1116 if (64 != strlen($lines[$i])) {
1117 return '';
1120 return implode("\n", $lines);
1121 } else {
1122 return '';
1125 case PARAM_TAG:
1126 $param = fix_utf8($param);
1127 // Please note it is not safe to use the tag name directly anywhere,
1128 // it must be processed with s(), urlencode() before embedding anywhere.
1129 // Remove some nasties.
1130 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1131 // Convert many whitespace chars into one.
1132 $param = preg_replace('/\s+/u', ' ', $param);
1133 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1134 return $param;
1136 case PARAM_TAGLIST:
1137 $param = fix_utf8($param);
1138 $tags = explode(',', $param);
1139 $result = array();
1140 foreach ($tags as $tag) {
1141 $res = clean_param($tag, PARAM_TAG);
1142 if ($res !== '') {
1143 $result[] = $res;
1146 if ($result) {
1147 return implode(',', $result);
1148 } else {
1149 return '';
1152 case PARAM_CAPABILITY:
1153 if (get_capability_info($param)) {
1154 return $param;
1155 } else {
1156 return '';
1159 case PARAM_PERMISSION:
1160 $param = (int)$param;
1161 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1162 return $param;
1163 } else {
1164 return CAP_INHERIT;
1167 case PARAM_AUTH:
1168 $param = clean_param($param, PARAM_PLUGIN);
1169 if (empty($param)) {
1170 return '';
1171 } else if (exists_auth_plugin($param)) {
1172 return $param;
1173 } else {
1174 return '';
1177 case PARAM_LANG:
1178 $param = clean_param($param, PARAM_SAFEDIR);
1179 if (get_string_manager()->translation_exists($param)) {
1180 return $param;
1181 } else {
1182 // Specified language is not installed or param malformed.
1183 return '';
1186 case PARAM_THEME:
1187 $param = clean_param($param, PARAM_PLUGIN);
1188 if (empty($param)) {
1189 return '';
1190 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1191 return $param;
1192 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1193 return $param;
1194 } else {
1195 // Specified theme is not installed.
1196 return '';
1199 case PARAM_USERNAME:
1200 $param = fix_utf8($param);
1201 $param = trim($param);
1202 // Convert uppercase to lowercase MDL-16919.
1203 $param = core_text::strtolower($param);
1204 if (empty($CFG->extendedusernamechars)) {
1205 $param = str_replace(" " , "", $param);
1206 // Regular expression, eliminate all chars EXCEPT:
1207 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1208 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1210 return $param;
1212 case PARAM_EMAIL:
1213 $param = fix_utf8($param);
1214 if (validate_email($param)) {
1215 return $param;
1216 } else {
1217 return '';
1220 case PARAM_STRINGID:
1221 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1222 return $param;
1223 } else {
1224 return '';
1227 case PARAM_TIMEZONE:
1228 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1229 $param = fix_utf8($param);
1230 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1231 if (preg_match($timezonepattern, $param)) {
1232 return $param;
1233 } else {
1234 return '';
1237 default:
1238 // Doh! throw error, switched parameters in optional_param or another serious problem.
1239 print_error("unknownparamtype", '', '', $type);
1244 * Whether the PARAM_* type is compatible in RTL.
1246 * Being compatible with RTL means that the data they contain can flow
1247 * from right-to-left or left-to-right without compromising the user experience.
1249 * Take URLs for example, they are not RTL compatible as they should always
1250 * flow from the left to the right. This also applies to numbers, email addresses,
1251 * configuration snippets, base64 strings, etc...
1253 * This function tries to best guess which parameters can contain localised strings.
1255 * @param string $paramtype Constant PARAM_*.
1256 * @return bool
1258 function is_rtl_compatible($paramtype) {
1259 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1263 * Makes sure the data is using valid utf8, invalid characters are discarded.
1265 * Note: this function is not intended for full objects with methods and private properties.
1267 * @param mixed $value
1268 * @return mixed with proper utf-8 encoding
1270 function fix_utf8($value) {
1271 if (is_null($value) or $value === '') {
1272 return $value;
1274 } else if (is_string($value)) {
1275 if ((string)(int)$value === $value) {
1276 // Shortcut.
1277 return $value;
1279 // No null bytes expected in our data, so let's remove it.
1280 $value = str_replace("\0", '', $value);
1282 // Note: this duplicates min_fix_utf8() intentionally.
1283 static $buggyiconv = null;
1284 if ($buggyiconv === null) {
1285 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1288 if ($buggyiconv) {
1289 if (function_exists('mb_convert_encoding')) {
1290 $subst = mb_substitute_character();
1291 mb_substitute_character('');
1292 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1293 mb_substitute_character($subst);
1295 } else {
1296 // Warn admins on admin/index.php page.
1297 $result = $value;
1300 } else {
1301 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1304 return $result;
1306 } else if (is_array($value)) {
1307 foreach ($value as $k => $v) {
1308 $value[$k] = fix_utf8($v);
1310 return $value;
1312 } else if (is_object($value)) {
1313 // Do not modify original.
1314 $value = clone($value);
1315 foreach ($value as $k => $v) {
1316 $value->$k = fix_utf8($v);
1318 return $value;
1320 } else {
1321 // This is some other type, no utf-8 here.
1322 return $value;
1327 * Return true if given value is integer or string with integer value
1329 * @param mixed $value String or Int
1330 * @return bool true if number, false if not
1332 function is_number($value) {
1333 if (is_int($value)) {
1334 return true;
1335 } else if (is_string($value)) {
1336 return ((string)(int)$value) === $value;
1337 } else {
1338 return false;
1343 * Returns host part from url.
1345 * @param string $url full url
1346 * @return string host, null if not found
1348 function get_host_from_url($url) {
1349 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1350 if ($matches) {
1351 return $matches[1];
1353 return null;
1357 * Tests whether anything was returned by text editor
1359 * This function is useful for testing whether something you got back from
1360 * the HTML editor actually contains anything. Sometimes the HTML editor
1361 * appear to be empty, but actually you get back a <br> tag or something.
1363 * @param string $string a string containing HTML.
1364 * @return boolean does the string contain any actual content - that is text,
1365 * images, objects, etc.
1367 function html_is_blank($string) {
1368 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1372 * Set a key in global configuration
1374 * Set a key/value pair in both this session's {@link $CFG} global variable
1375 * and in the 'config' database table for future sessions.
1377 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1378 * In that case it doesn't affect $CFG.
1380 * A NULL value will delete the entry.
1382 * NOTE: this function is called from lib/db/upgrade.php
1384 * @param string $name the key to set
1385 * @param string $value the value to set (without magic quotes)
1386 * @param string $plugin (optional) the plugin scope, default null
1387 * @return bool true or exception
1389 function set_config($name, $value, $plugin=null) {
1390 global $CFG, $DB;
1392 if (empty($plugin)) {
1393 if (!array_key_exists($name, $CFG->config_php_settings)) {
1394 // So it's defined for this invocation at least.
1395 if (is_null($value)) {
1396 unset($CFG->$name);
1397 } else {
1398 // Settings from db are always strings.
1399 $CFG->$name = (string)$value;
1403 if ($DB->get_field('config', 'name', array('name' => $name))) {
1404 if ($value === null) {
1405 $DB->delete_records('config', array('name' => $name));
1406 } else {
1407 $DB->set_field('config', 'value', $value, array('name' => $name));
1409 } else {
1410 if ($value !== null) {
1411 $config = new stdClass();
1412 $config->name = $name;
1413 $config->value = $value;
1414 $DB->insert_record('config', $config, false);
1417 if ($name === 'siteidentifier') {
1418 cache_helper::update_site_identifier($value);
1420 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1421 } else {
1422 // Plugin scope.
1423 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1424 if ($value===null) {
1425 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1426 } else {
1427 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1429 } else {
1430 if ($value !== null) {
1431 $config = new stdClass();
1432 $config->plugin = $plugin;
1433 $config->name = $name;
1434 $config->value = $value;
1435 $DB->insert_record('config_plugins', $config, false);
1438 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1441 return true;
1445 * Get configuration values from the global config table
1446 * or the config_plugins table.
1448 * If called with one parameter, it will load all the config
1449 * variables for one plugin, and return them as an object.
1451 * If called with 2 parameters it will return a string single
1452 * value or false if the value is not found.
1454 * NOTE: this function is called from lib/db/upgrade.php
1456 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1457 * that we need only fetch it once per request.
1458 * @param string $plugin full component name
1459 * @param string $name default null
1460 * @return mixed hash-like object or single value, return false no config found
1461 * @throws dml_exception
1463 function get_config($plugin, $name = null) {
1464 global $CFG, $DB;
1466 static $siteidentifier = null;
1468 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1469 $forced =& $CFG->config_php_settings;
1470 $iscore = true;
1471 $plugin = 'core';
1472 } else {
1473 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1474 $forced =& $CFG->forced_plugin_settings[$plugin];
1475 } else {
1476 $forced = array();
1478 $iscore = false;
1481 if ($siteidentifier === null) {
1482 try {
1483 // This may fail during installation.
1484 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1485 // install the database.
1486 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1487 } catch (dml_exception $ex) {
1488 // Set siteidentifier to false. We don't want to trip this continually.
1489 $siteidentifier = false;
1490 throw $ex;
1494 if (!empty($name)) {
1495 if (array_key_exists($name, $forced)) {
1496 return (string)$forced[$name];
1497 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1498 return $siteidentifier;
1502 $cache = cache::make('core', 'config');
1503 $result = $cache->get($plugin);
1504 if ($result === false) {
1505 // The user is after a recordset.
1506 if (!$iscore) {
1507 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1508 } else {
1509 // This part is not really used any more, but anyway...
1510 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1512 $cache->set($plugin, $result);
1515 if (!empty($name)) {
1516 if (array_key_exists($name, $result)) {
1517 return $result[$name];
1519 return false;
1522 if ($plugin === 'core') {
1523 $result['siteidentifier'] = $siteidentifier;
1526 foreach ($forced as $key => $value) {
1527 if (is_null($value) or is_array($value) or is_object($value)) {
1528 // We do not want any extra mess here, just real settings that could be saved in db.
1529 unset($result[$key]);
1530 } else {
1531 // Convert to string as if it went through the DB.
1532 $result[$key] = (string)$value;
1536 return (object)$result;
1540 * Removes a key from global configuration.
1542 * NOTE: this function is called from lib/db/upgrade.php
1544 * @param string $name the key to set
1545 * @param string $plugin (optional) the plugin scope
1546 * @return boolean whether the operation succeeded.
1548 function unset_config($name, $plugin=null) {
1549 global $CFG, $DB;
1551 if (empty($plugin)) {
1552 unset($CFG->$name);
1553 $DB->delete_records('config', array('name' => $name));
1554 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1555 } else {
1556 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1557 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1560 return true;
1564 * Remove all the config variables for a given plugin.
1566 * NOTE: this function is called from lib/db/upgrade.php
1568 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1569 * @return boolean whether the operation succeeded.
1571 function unset_all_config_for_plugin($plugin) {
1572 global $DB;
1573 // Delete from the obvious config_plugins first.
1574 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1575 // Next delete any suspect settings from config.
1576 $like = $DB->sql_like('name', '?', true, true, false, '|');
1577 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1578 $DB->delete_records_select('config', $like, $params);
1579 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1580 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1582 return true;
1586 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1588 * All users are verified if they still have the necessary capability.
1590 * @param string $value the value of the config setting.
1591 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1592 * @param bool $includeadmins include administrators.
1593 * @return array of user objects.
1595 function get_users_from_config($value, $capability, $includeadmins = true) {
1596 if (empty($value) or $value === '$@NONE@$') {
1597 return array();
1600 // We have to make sure that users still have the necessary capability,
1601 // it should be faster to fetch them all first and then test if they are present
1602 // instead of validating them one-by-one.
1603 $users = get_users_by_capability(context_system::instance(), $capability);
1604 if ($includeadmins) {
1605 $admins = get_admins();
1606 foreach ($admins as $admin) {
1607 $users[$admin->id] = $admin;
1611 if ($value === '$@ALL@$') {
1612 return $users;
1615 $result = array(); // Result in correct order.
1616 $allowed = explode(',', $value);
1617 foreach ($allowed as $uid) {
1618 if (isset($users[$uid])) {
1619 $user = $users[$uid];
1620 $result[$user->id] = $user;
1624 return $result;
1629 * Invalidates browser caches and cached data in temp.
1631 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1632 * {@link phpunit_util::reset_dataroot()}
1634 * @return void
1636 function purge_all_caches() {
1637 global $CFG, $DB;
1639 reset_text_filters_cache();
1640 js_reset_all_caches();
1641 theme_reset_all_caches();
1642 get_string_manager()->reset_caches();
1643 core_text::reset_caches();
1644 if (class_exists('core_plugin_manager')) {
1645 core_plugin_manager::reset_caches();
1648 // Bump up cacherev field for all courses.
1649 try {
1650 increment_revision_number('course', 'cacherev', '');
1651 } catch (moodle_exception $e) {
1652 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1655 $DB->reset_caches();
1656 cache_helper::purge_all();
1658 // Purge all other caches: rss, simplepie, etc.
1659 clearstatcache();
1660 remove_dir($CFG->cachedir.'', true);
1662 // Make sure cache dir is writable, throws exception if not.
1663 make_cache_directory('');
1665 // This is the only place where we purge local caches, we are only adding files there.
1666 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1667 remove_dir($CFG->localcachedir, true);
1668 set_config('localcachedirpurged', time());
1669 make_localcache_directory('', true);
1670 \core\task\manager::clear_static_caches();
1674 * Get volatile flags
1676 * @param string $type
1677 * @param int $changedsince default null
1678 * @return array records array
1680 function get_cache_flags($type, $changedsince = null) {
1681 global $DB;
1683 $params = array('type' => $type, 'expiry' => time());
1684 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1685 if ($changedsince !== null) {
1686 $params['changedsince'] = $changedsince;
1687 $sqlwhere .= " AND timemodified > :changedsince";
1689 $cf = array();
1690 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1691 foreach ($flags as $flag) {
1692 $cf[$flag->name] = $flag->value;
1695 return $cf;
1699 * Get volatile flags
1701 * @param string $type
1702 * @param string $name
1703 * @param int $changedsince default null
1704 * @return string|false The cache flag value or false
1706 function get_cache_flag($type, $name, $changedsince=null) {
1707 global $DB;
1709 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1711 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1712 if ($changedsince !== null) {
1713 $params['changedsince'] = $changedsince;
1714 $sqlwhere .= " AND timemodified > :changedsince";
1717 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1721 * Set a volatile flag
1723 * @param string $type the "type" namespace for the key
1724 * @param string $name the key to set
1725 * @param string $value the value to set (without magic quotes) - null will remove the flag
1726 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1727 * @return bool Always returns true
1729 function set_cache_flag($type, $name, $value, $expiry = null) {
1730 global $DB;
1732 $timemodified = time();
1733 if ($expiry === null || $expiry < $timemodified) {
1734 $expiry = $timemodified + 24 * 60 * 60;
1735 } else {
1736 $expiry = (int)$expiry;
1739 if ($value === null) {
1740 unset_cache_flag($type, $name);
1741 return true;
1744 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1745 // This is a potential problem in DEBUG_DEVELOPER.
1746 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1747 return true; // No need to update.
1749 $f->value = $value;
1750 $f->expiry = $expiry;
1751 $f->timemodified = $timemodified;
1752 $DB->update_record('cache_flags', $f);
1753 } else {
1754 $f = new stdClass();
1755 $f->flagtype = $type;
1756 $f->name = $name;
1757 $f->value = $value;
1758 $f->expiry = $expiry;
1759 $f->timemodified = $timemodified;
1760 $DB->insert_record('cache_flags', $f);
1762 return true;
1766 * Removes a single volatile flag
1768 * @param string $type the "type" namespace for the key
1769 * @param string $name the key to set
1770 * @return bool
1772 function unset_cache_flag($type, $name) {
1773 global $DB;
1774 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1775 return true;
1779 * Garbage-collect volatile flags
1781 * @return bool Always returns true
1783 function gc_cache_flags() {
1784 global $DB;
1785 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1786 return true;
1789 // USER PREFERENCE API.
1792 * Refresh user preference cache. This is used most often for $USER
1793 * object that is stored in session, but it also helps with performance in cron script.
1795 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1797 * @package core
1798 * @category preference
1799 * @access public
1800 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1801 * @param int $cachelifetime Cache life time on the current page (in seconds)
1802 * @throws coding_exception
1803 * @return null
1805 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1806 global $DB;
1807 // Static cache, we need to check on each page load, not only every 2 minutes.
1808 static $loadedusers = array();
1810 if (!isset($user->id)) {
1811 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1814 if (empty($user->id) or isguestuser($user->id)) {
1815 // No permanent storage for not-logged-in users and guest.
1816 if (!isset($user->preference)) {
1817 $user->preference = array();
1819 return;
1822 $timenow = time();
1824 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1825 // Already loaded at least once on this page. Are we up to date?
1826 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1827 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1828 return;
1830 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1831 // No change since the lastcheck on this page.
1832 $user->preference['_lastloaded'] = $timenow;
1833 return;
1837 // OK, so we have to reload all preferences.
1838 $loadedusers[$user->id] = true;
1839 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1840 $user->preference['_lastloaded'] = $timenow;
1844 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1846 * NOTE: internal function, do not call from other code.
1848 * @package core
1849 * @access private
1850 * @param integer $userid the user whose prefs were changed.
1852 function mark_user_preferences_changed($userid) {
1853 global $CFG;
1855 if (empty($userid) or isguestuser($userid)) {
1856 // No cache flags for guest and not-logged-in users.
1857 return;
1860 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1864 * Sets a preference for the specified user.
1866 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1868 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1870 * @package core
1871 * @category preference
1872 * @access public
1873 * @param string $name The key to set as preference for the specified user
1874 * @param string $value The value to set for the $name key in the specified user's
1875 * record, null means delete current value.
1876 * @param stdClass|int|null $user A moodle user object or id, null means current user
1877 * @throws coding_exception
1878 * @return bool Always true or exception
1880 function set_user_preference($name, $value, $user = null) {
1881 global $USER, $DB;
1883 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1884 throw new coding_exception('Invalid preference name in set_user_preference() call');
1887 if (is_null($value)) {
1888 // Null means delete current.
1889 return unset_user_preference($name, $user);
1890 } else if (is_object($value)) {
1891 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1892 } else if (is_array($value)) {
1893 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1895 // Value column maximum length is 1333 characters.
1896 $value = (string)$value;
1897 if (core_text::strlen($value) > 1333) {
1898 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1901 if (is_null($user)) {
1902 $user = $USER;
1903 } else if (isset($user->id)) {
1904 // It is a valid object.
1905 } else if (is_numeric($user)) {
1906 $user = (object)array('id' => (int)$user);
1907 } else {
1908 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1911 check_user_preferences_loaded($user);
1913 if (empty($user->id) or isguestuser($user->id)) {
1914 // No permanent storage for not-logged-in users and guest.
1915 $user->preference[$name] = $value;
1916 return true;
1919 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1920 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1921 // Preference already set to this value.
1922 return true;
1924 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1926 } else {
1927 $preference = new stdClass();
1928 $preference->userid = $user->id;
1929 $preference->name = $name;
1930 $preference->value = $value;
1931 $DB->insert_record('user_preferences', $preference);
1934 // Update value in cache.
1935 $user->preference[$name] = $value;
1936 // Update the $USER in case where we've not a direct reference to $USER.
1937 if ($user !== $USER && $user->id == $USER->id) {
1938 $USER->preference[$name] = $value;
1941 // Set reload flag for other sessions.
1942 mark_user_preferences_changed($user->id);
1944 return true;
1948 * Sets a whole array of preferences for the current user
1950 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1952 * @package core
1953 * @category preference
1954 * @access public
1955 * @param array $prefarray An array of key/value pairs to be set
1956 * @param stdClass|int|null $user A moodle user object or id, null means current user
1957 * @return bool Always true or exception
1959 function set_user_preferences(array $prefarray, $user = null) {
1960 foreach ($prefarray as $name => $value) {
1961 set_user_preference($name, $value, $user);
1963 return true;
1967 * Unsets a preference completely by deleting it from the database
1969 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1971 * @package core
1972 * @category preference
1973 * @access public
1974 * @param string $name The key to unset as preference for the specified user
1975 * @param stdClass|int|null $user A moodle user object or id, null means current user
1976 * @throws coding_exception
1977 * @return bool Always true or exception
1979 function unset_user_preference($name, $user = null) {
1980 global $USER, $DB;
1982 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1983 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1986 if (is_null($user)) {
1987 $user = $USER;
1988 } else if (isset($user->id)) {
1989 // It is a valid object.
1990 } else if (is_numeric($user)) {
1991 $user = (object)array('id' => (int)$user);
1992 } else {
1993 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1996 check_user_preferences_loaded($user);
1998 if (empty($user->id) or isguestuser($user->id)) {
1999 // No permanent storage for not-logged-in user and guest.
2000 unset($user->preference[$name]);
2001 return true;
2004 // Delete from DB.
2005 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2007 // Delete the preference from cache.
2008 unset($user->preference[$name]);
2009 // Update the $USER in case where we've not a direct reference to $USER.
2010 if ($user !== $USER && $user->id == $USER->id) {
2011 unset($USER->preference[$name]);
2014 // Set reload flag for other sessions.
2015 mark_user_preferences_changed($user->id);
2017 return true;
2021 * Used to fetch user preference(s)
2023 * If no arguments are supplied this function will return
2024 * all of the current user preferences as an array.
2026 * If a name is specified then this function
2027 * attempts to return that particular preference value. If
2028 * none is found, then the optional value $default is returned,
2029 * otherwise null.
2031 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2033 * @package core
2034 * @category preference
2035 * @access public
2036 * @param string $name Name of the key to use in finding a preference value
2037 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2038 * @param stdClass|int|null $user A moodle user object or id, null means current user
2039 * @throws coding_exception
2040 * @return string|mixed|null A string containing the value of a single preference. An
2041 * array with all of the preferences or null
2043 function get_user_preferences($name = null, $default = null, $user = null) {
2044 global $USER;
2046 if (is_null($name)) {
2047 // All prefs.
2048 } else if (is_numeric($name) or $name === '_lastloaded') {
2049 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2052 if (is_null($user)) {
2053 $user = $USER;
2054 } else if (isset($user->id)) {
2055 // Is a valid object.
2056 } else if (is_numeric($user)) {
2057 $user = (object)array('id' => (int)$user);
2058 } else {
2059 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2062 check_user_preferences_loaded($user);
2064 if (empty($name)) {
2065 // All values.
2066 return $user->preference;
2067 } else if (isset($user->preference[$name])) {
2068 // The single string value.
2069 return $user->preference[$name];
2070 } else {
2071 // Default value (null if not specified).
2072 return $default;
2076 // FUNCTIONS FOR HANDLING TIME.
2079 * Given Gregorian date parts in user time produce a GMT timestamp.
2081 * @package core
2082 * @category time
2083 * @param int $year The year part to create timestamp of
2084 * @param int $month The month part to create timestamp of
2085 * @param int $day The day part to create timestamp of
2086 * @param int $hour The hour part to create timestamp of
2087 * @param int $minute The minute part to create timestamp of
2088 * @param int $second The second part to create timestamp of
2089 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2090 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2091 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2092 * applied only if timezone is 99 or string.
2093 * @return int GMT timestamp
2095 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2096 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2097 $date->setDate((int)$year, (int)$month, (int)$day);
2098 $date->setTime((int)$hour, (int)$minute, (int)$second);
2100 $time = $date->getTimestamp();
2102 if ($time === false) {
2103 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2104 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2107 // Moodle BC DST stuff.
2108 if (!$applydst) {
2109 $time += dst_offset_on($time, $timezone);
2112 return $time;
2117 * Format a date/time (seconds) as weeks, days, hours etc as needed
2119 * Given an amount of time in seconds, returns string
2120 * formatted nicely as weeks, days, hours etc as needed
2122 * @package core
2123 * @category time
2124 * @uses MINSECS
2125 * @uses HOURSECS
2126 * @uses DAYSECS
2127 * @uses YEARSECS
2128 * @param int $totalsecs Time in seconds
2129 * @param stdClass $str Should be a time object
2130 * @return string A nicely formatted date/time string
2132 function format_time($totalsecs, $str = null) {
2134 $totalsecs = abs($totalsecs);
2136 if (!$str) {
2137 // Create the str structure the slow way.
2138 $str = new stdClass();
2139 $str->day = get_string('day');
2140 $str->days = get_string('days');
2141 $str->hour = get_string('hour');
2142 $str->hours = get_string('hours');
2143 $str->min = get_string('min');
2144 $str->mins = get_string('mins');
2145 $str->sec = get_string('sec');
2146 $str->secs = get_string('secs');
2147 $str->year = get_string('year');
2148 $str->years = get_string('years');
2151 $years = floor($totalsecs/YEARSECS);
2152 $remainder = $totalsecs - ($years*YEARSECS);
2153 $days = floor($remainder/DAYSECS);
2154 $remainder = $totalsecs - ($days*DAYSECS);
2155 $hours = floor($remainder/HOURSECS);
2156 $remainder = $remainder - ($hours*HOURSECS);
2157 $mins = floor($remainder/MINSECS);
2158 $secs = $remainder - ($mins*MINSECS);
2160 $ss = ($secs == 1) ? $str->sec : $str->secs;
2161 $sm = ($mins == 1) ? $str->min : $str->mins;
2162 $sh = ($hours == 1) ? $str->hour : $str->hours;
2163 $sd = ($days == 1) ? $str->day : $str->days;
2164 $sy = ($years == 1) ? $str->year : $str->years;
2166 $oyears = '';
2167 $odays = '';
2168 $ohours = '';
2169 $omins = '';
2170 $osecs = '';
2172 if ($years) {
2173 $oyears = $years .' '. $sy;
2175 if ($days) {
2176 $odays = $days .' '. $sd;
2178 if ($hours) {
2179 $ohours = $hours .' '. $sh;
2181 if ($mins) {
2182 $omins = $mins .' '. $sm;
2184 if ($secs) {
2185 $osecs = $secs .' '. $ss;
2188 if ($years) {
2189 return trim($oyears .' '. $odays);
2191 if ($days) {
2192 return trim($odays .' '. $ohours);
2194 if ($hours) {
2195 return trim($ohours .' '. $omins);
2197 if ($mins) {
2198 return trim($omins .' '. $osecs);
2200 if ($secs) {
2201 return $osecs;
2203 return get_string('now');
2207 * Returns a formatted string that represents a date in user time.
2209 * @package core
2210 * @category time
2211 * @param int $date the timestamp in UTC, as obtained from the database.
2212 * @param string $format strftime format. You should probably get this using
2213 * get_string('strftime...', 'langconfig');
2214 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2215 * not 99 then daylight saving will not be added.
2216 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2217 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2218 * If false then the leading zero is maintained.
2219 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2220 * @return string the formatted date/time.
2222 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2223 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2224 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2228 * Returns a formatted date ensuring it is UTF-8.
2230 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2231 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2233 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2234 * @param string $format strftime format.
2235 * @param int|float|string $tz the user timezone
2236 * @return string the formatted date/time.
2237 * @since Moodle 2.3.3
2239 function date_format_string($date, $format, $tz = 99) {
2240 global $CFG;
2242 $localewincharset = null;
2243 // Get the calendar type user is using.
2244 if ($CFG->ostype == 'WINDOWS') {
2245 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2246 $localewincharset = $calendartype->locale_win_charset();
2249 if ($localewincharset) {
2250 $format = core_text::convert($format, 'utf-8', $localewincharset);
2253 date_default_timezone_set(core_date::get_user_timezone($tz));
2254 $datestring = strftime($format, $date);
2255 core_date::set_default_server_timezone();
2257 if ($localewincharset) {
2258 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2261 return $datestring;
2265 * Given a $time timestamp in GMT (seconds since epoch),
2266 * returns an array that represents the Gregorian date in user time
2268 * @package core
2269 * @category time
2270 * @param int $time Timestamp in GMT
2271 * @param float|int|string $timezone user timezone
2272 * @return array An array that represents the date in user time
2274 function usergetdate($time, $timezone=99) {
2275 date_default_timezone_set(core_date::get_user_timezone($timezone));
2276 $result = getdate($time);
2277 core_date::set_default_server_timezone();
2279 return $result;
2283 * Given a GMT timestamp (seconds since epoch), offsets it by
2284 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2286 * NOTE: this function does not include DST properly,
2287 * you should use the PHP date stuff instead!
2289 * @package core
2290 * @category time
2291 * @param int $date Timestamp in GMT
2292 * @param float|int|string $timezone user timezone
2293 * @return int
2295 function usertime($date, $timezone=99) {
2296 $userdate = new DateTime('@' . $date);
2297 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2298 $dst = dst_offset_on($date, $timezone);
2300 return $date - $userdate->getOffset() + $dst;
2304 * Given a time, return the GMT timestamp of the most recent midnight
2305 * for the current user.
2307 * @package core
2308 * @category time
2309 * @param int $date Timestamp in GMT
2310 * @param float|int|string $timezone user timezone
2311 * @return int Returns a GMT timestamp
2313 function usergetmidnight($date, $timezone=99) {
2315 $userdate = usergetdate($date, $timezone);
2317 // Time of midnight of this user's day, in GMT.
2318 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2323 * Returns a string that prints the user's timezone
2325 * @package core
2326 * @category time
2327 * @param float|int|string $timezone user timezone
2328 * @return string
2330 function usertimezone($timezone=99) {
2331 $tz = core_date::get_user_timezone($timezone);
2332 return core_date::get_localised_timezone($tz);
2336 * Returns a float or a string which denotes the user's timezone
2337 * 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)
2338 * means that for this timezone there are also DST rules to be taken into account
2339 * Checks various settings and picks the most dominant of those which have a value
2341 * @package core
2342 * @category time
2343 * @param float|int|string $tz timezone to calculate GMT time offset before
2344 * calculating user timezone, 99 is default user timezone
2345 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2346 * @return float|string
2348 function get_user_timezone($tz = 99) {
2349 global $USER, $CFG;
2351 $timezones = array(
2352 $tz,
2353 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2354 isset($USER->timezone) ? $USER->timezone : 99,
2355 isset($CFG->timezone) ? $CFG->timezone : 99,
2358 $tz = 99;
2360 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2361 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2362 $tz = $next['value'];
2364 return is_numeric($tz) ? (float) $tz : $tz;
2368 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2369 * - Note: Daylight saving only works for string timezones and not for float.
2371 * @package core
2372 * @category time
2373 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2374 * @param int|float|string $strtimezone user timezone
2375 * @return int
2377 function dst_offset_on($time, $strtimezone = null) {
2378 $tz = core_date::get_user_timezone($strtimezone);
2379 $date = new DateTime('@' . $time);
2380 $date->setTimezone(new DateTimeZone($tz));
2381 if ($date->format('I') == '1') {
2382 if ($tz === 'Australia/Lord_Howe') {
2383 return 1800;
2385 return 3600;
2387 return 0;
2391 * Calculates when the day appears in specific month
2393 * @package core
2394 * @category time
2395 * @param int $startday starting day of the month
2396 * @param int $weekday The day when week starts (normally taken from user preferences)
2397 * @param int $month The month whose day is sought
2398 * @param int $year The year of the month whose day is sought
2399 * @return int
2401 function find_day_in_month($startday, $weekday, $month, $year) {
2402 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2404 $daysinmonth = days_in_month($month, $year);
2405 $daysinweek = count($calendartype->get_weekdays());
2407 if ($weekday == -1) {
2408 // Don't care about weekday, so return:
2409 // abs($startday) if $startday != -1
2410 // $daysinmonth otherwise.
2411 return ($startday == -1) ? $daysinmonth : abs($startday);
2414 // From now on we 're looking for a specific weekday.
2415 // Give "end of month" its actual value, since we know it.
2416 if ($startday == -1) {
2417 $startday = -1 * $daysinmonth;
2420 // Starting from day $startday, the sign is the direction.
2421 if ($startday < 1) {
2422 $startday = abs($startday);
2423 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2425 // This is the last such weekday of the month.
2426 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2427 if ($lastinmonth > $daysinmonth) {
2428 $lastinmonth -= $daysinweek;
2431 // Find the first such weekday <= $startday.
2432 while ($lastinmonth > $startday) {
2433 $lastinmonth -= $daysinweek;
2436 return $lastinmonth;
2437 } else {
2438 $indexweekday = dayofweek($startday, $month, $year);
2440 $diff = $weekday - $indexweekday;
2441 if ($diff < 0) {
2442 $diff += $daysinweek;
2445 // This is the first such weekday of the month equal to or after $startday.
2446 $firstfromindex = $startday + $diff;
2448 return $firstfromindex;
2453 * Calculate the number of days in a given month
2455 * @package core
2456 * @category time
2457 * @param int $month The month whose day count is sought
2458 * @param int $year The year of the month whose day count is sought
2459 * @return int
2461 function days_in_month($month, $year) {
2462 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2463 return $calendartype->get_num_days_in_month($year, $month);
2467 * Calculate the position in the week of a specific calendar day
2469 * @package core
2470 * @category time
2471 * @param int $day The day of the date whose position in the week is sought
2472 * @param int $month The month of the date whose position in the week is sought
2473 * @param int $year The year of the date whose position in the week is sought
2474 * @return int
2476 function dayofweek($day, $month, $year) {
2477 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2478 return $calendartype->get_weekday($year, $month, $day);
2481 // USER AUTHENTICATION AND LOGIN.
2484 * Returns full login url.
2486 * @return string login url
2488 function get_login_url() {
2489 global $CFG;
2491 $url = "$CFG->wwwroot/login/index.php";
2493 if (!empty($CFG->loginhttps)) {
2494 $url = str_replace('http:', 'https:', $url);
2497 return $url;
2501 * This function checks that the current user is logged in and has the
2502 * required privileges
2504 * This function checks that the current user is logged in, and optionally
2505 * whether they are allowed to be in a particular course and view a particular
2506 * course module.
2507 * If they are not logged in, then it redirects them to the site login unless
2508 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2509 * case they are automatically logged in as guests.
2510 * If $courseid is given and the user is not enrolled in that course then the
2511 * user is redirected to the course enrolment page.
2512 * If $cm is given and the course module is hidden and the user is not a teacher
2513 * in the course then the user is redirected to the course home page.
2515 * When $cm parameter specified, this function sets page layout to 'module'.
2516 * You need to change it manually later if some other layout needed.
2518 * @package core_access
2519 * @category access
2521 * @param mixed $courseorid id of the course or course object
2522 * @param bool $autologinguest default true
2523 * @param object $cm course module object
2524 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2525 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2526 * in order to keep redirects working properly. MDL-14495
2527 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2528 * @return mixed Void, exit, and die depending on path
2529 * @throws coding_exception
2530 * @throws require_login_exception
2531 * @throws moodle_exception
2533 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2534 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2536 // Must not redirect when byteserving already started.
2537 if (!empty($_SERVER['HTTP_RANGE'])) {
2538 $preventredirect = true;
2541 if (AJAX_SCRIPT) {
2542 // We cannot redirect for AJAX scripts either.
2543 $preventredirect = true;
2546 // Setup global $COURSE, themes, language and locale.
2547 if (!empty($courseorid)) {
2548 if (is_object($courseorid)) {
2549 $course = $courseorid;
2550 } else if ($courseorid == SITEID) {
2551 $course = clone($SITE);
2552 } else {
2553 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2555 if ($cm) {
2556 if ($cm->course != $course->id) {
2557 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2559 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2560 if (!($cm instanceof cm_info)) {
2561 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2562 // db queries so this is not really a performance concern, however it is obviously
2563 // better if you use get_fast_modinfo to get the cm before calling this.
2564 $modinfo = get_fast_modinfo($course);
2565 $cm = $modinfo->get_cm($cm->id);
2568 } else {
2569 // Do not touch global $COURSE via $PAGE->set_course(),
2570 // the reasons is we need to be able to call require_login() at any time!!
2571 $course = $SITE;
2572 if ($cm) {
2573 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2577 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2578 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2579 // risk leading the user back to the AJAX request URL.
2580 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2581 $setwantsurltome = false;
2584 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2585 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2586 if ($preventredirect) {
2587 throw new require_login_session_timeout_exception();
2588 } else {
2589 if ($setwantsurltome) {
2590 $SESSION->wantsurl = qualified_me();
2592 redirect(get_login_url());
2596 // If the user is not even logged in yet then make sure they are.
2597 if (!isloggedin()) {
2598 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2599 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2600 // Misconfigured site guest, just redirect to login page.
2601 redirect(get_login_url());
2602 exit; // Never reached.
2604 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2605 complete_user_login($guest);
2606 $USER->autologinguest = true;
2607 $SESSION->lang = $lang;
2608 } else {
2609 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2610 if ($preventredirect) {
2611 throw new require_login_exception('You are not logged in');
2614 if ($setwantsurltome) {
2615 $SESSION->wantsurl = qualified_me();
2618 $referer = get_local_referer(false);
2619 if (!empty($referer)) {
2620 $SESSION->fromurl = $referer;
2623 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2624 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2625 foreach($authsequence as $authname) {
2626 $authplugin = get_auth_plugin($authname);
2627 $authplugin->pre_loginpage_hook();
2628 if (isloggedin()) {
2629 break;
2633 // If we're still not logged in then go to the login page
2634 if (!isloggedin()) {
2635 redirect(get_login_url());
2636 exit; // Never reached.
2641 // Loginas as redirection if needed.
2642 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2643 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2644 if ($USER->loginascontext->instanceid != $course->id) {
2645 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2650 // Check whether the user should be changing password (but only if it is REALLY them).
2651 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2652 $userauth = get_auth_plugin($USER->auth);
2653 if ($userauth->can_change_password() and !$preventredirect) {
2654 if ($setwantsurltome) {
2655 $SESSION->wantsurl = qualified_me();
2657 if ($changeurl = $userauth->change_password_url()) {
2658 // Use plugin custom url.
2659 redirect($changeurl);
2660 } else {
2661 // Use moodle internal method.
2662 if (empty($CFG->loginhttps)) {
2663 redirect($CFG->wwwroot .'/login/change_password.php');
2664 } else {
2665 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2666 redirect($wwwroot .'/login/change_password.php');
2669 } else if ($userauth->can_change_password()) {
2670 throw new moodle_exception('forcepasswordchangenotice');
2671 } else {
2672 throw new moodle_exception('nopasswordchangeforced', 'auth');
2676 // Check that the user account is properly set up. If we can't redirect to
2677 // edit their profile and this is not a WS request, perform just the lax check.
2678 // It will allow them to use filepicker on the profile edit page.
2680 if ($preventredirect && !WS_SERVER) {
2681 $usernotfullysetup = user_not_fully_set_up($USER, false);
2682 } else {
2683 $usernotfullysetup = user_not_fully_set_up($USER, true);
2686 if ($usernotfullysetup) {
2687 if ($preventredirect) {
2688 throw new moodle_exception('usernotfullysetup');
2690 if ($setwantsurltome) {
2691 $SESSION->wantsurl = qualified_me();
2693 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2696 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2697 sesskey();
2699 // Do not bother admins with any formalities, except for activities pending deletion.
2700 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2701 // Set the global $COURSE.
2702 if ($cm) {
2703 $PAGE->set_cm($cm, $course);
2704 $PAGE->set_pagelayout('incourse');
2705 } else if (!empty($courseorid)) {
2706 $PAGE->set_course($course);
2708 // Set accesstime or the user will appear offline which messes up messaging.
2709 user_accesstime_log($course->id);
2710 return;
2713 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2714 if (!$USER->policyagreed and !is_siteadmin()) {
2715 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2716 if ($preventredirect) {
2717 throw new moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicy);
2719 if ($setwantsurltome) {
2720 $SESSION->wantsurl = qualified_me();
2722 redirect($CFG->wwwroot .'/user/policy.php');
2723 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2724 if ($preventredirect) {
2725 throw new moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicyguest);
2727 if ($setwantsurltome) {
2728 $SESSION->wantsurl = qualified_me();
2730 redirect($CFG->wwwroot .'/user/policy.php');
2734 // Fetch the system context, the course context, and prefetch its child contexts.
2735 $sysctx = context_system::instance();
2736 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2737 if ($cm) {
2738 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2739 } else {
2740 $cmcontext = null;
2743 // If the site is currently under maintenance, then print a message.
2744 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2745 if ($preventredirect) {
2746 throw new require_login_exception('Maintenance in progress');
2748 $PAGE->set_context(null);
2749 print_maintenance_message();
2752 // Make sure the course itself is not hidden.
2753 if ($course->id == SITEID) {
2754 // Frontpage can not be hidden.
2755 } else {
2756 if (is_role_switched($course->id)) {
2757 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2758 } else {
2759 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2760 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2761 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2762 if ($preventredirect) {
2763 throw new require_login_exception('Course is hidden');
2765 $PAGE->set_context(null);
2766 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2767 // the navigation will mess up when trying to find it.
2768 navigation_node::override_active_url(new moodle_url('/'));
2769 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2774 // Is the user enrolled?
2775 if ($course->id == SITEID) {
2776 // Everybody is enrolled on the frontpage.
2777 } else {
2778 if (\core\session\manager::is_loggedinas()) {
2779 // Make sure the REAL person can access this course first.
2780 $realuser = \core\session\manager::get_realuser();
2781 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2782 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2783 if ($preventredirect) {
2784 throw new require_login_exception('Invalid course login-as access');
2786 $PAGE->set_context(null);
2787 echo $OUTPUT->header();
2788 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2792 $access = false;
2794 if (is_role_switched($course->id)) {
2795 // Ok, user had to be inside this course before the switch.
2796 $access = true;
2798 } else if (is_viewing($coursecontext, $USER)) {
2799 // Ok, no need to mess with enrol.
2800 $access = true;
2802 } else {
2803 if (isset($USER->enrol['enrolled'][$course->id])) {
2804 if ($USER->enrol['enrolled'][$course->id] > time()) {
2805 $access = true;
2806 if (isset($USER->enrol['tempguest'][$course->id])) {
2807 unset($USER->enrol['tempguest'][$course->id]);
2808 remove_temp_course_roles($coursecontext);
2810 } else {
2811 // Expired.
2812 unset($USER->enrol['enrolled'][$course->id]);
2815 if (isset($USER->enrol['tempguest'][$course->id])) {
2816 if ($USER->enrol['tempguest'][$course->id] == 0) {
2817 $access = true;
2818 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2819 $access = true;
2820 } else {
2821 // Expired.
2822 unset($USER->enrol['tempguest'][$course->id]);
2823 remove_temp_course_roles($coursecontext);
2827 if (!$access) {
2828 // Cache not ok.
2829 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2830 if ($until !== false) {
2831 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2832 if ($until == 0) {
2833 $until = ENROL_MAX_TIMESTAMP;
2835 $USER->enrol['enrolled'][$course->id] = $until;
2836 $access = true;
2838 } else {
2839 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2840 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2841 $enrols = enrol_get_plugins(true);
2842 // First ask all enabled enrol instances in course if they want to auto enrol user.
2843 foreach ($instances as $instance) {
2844 if (!isset($enrols[$instance->enrol])) {
2845 continue;
2847 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2848 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2849 if ($until !== false) {
2850 if ($until == 0) {
2851 $until = ENROL_MAX_TIMESTAMP;
2853 $USER->enrol['enrolled'][$course->id] = $until;
2854 $access = true;
2855 break;
2858 // If not enrolled yet try to gain temporary guest access.
2859 if (!$access) {
2860 foreach ($instances as $instance) {
2861 if (!isset($enrols[$instance->enrol])) {
2862 continue;
2864 // Get a duration for the guest access, a timestamp in the future or false.
2865 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2866 if ($until !== false and $until > time()) {
2867 $USER->enrol['tempguest'][$course->id] = $until;
2868 $access = true;
2869 break;
2877 if (!$access) {
2878 if ($preventredirect) {
2879 throw new require_login_exception('Not enrolled');
2881 if ($setwantsurltome) {
2882 $SESSION->wantsurl = qualified_me();
2884 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2888 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
2889 if ($cm && $cm->deletioninprogress) {
2890 if ($preventredirect) {
2891 throw new moodle_exception('activityisscheduledfordeletion');
2893 require_once($CFG->dirroot . '/course/lib.php');
2894 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
2897 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2898 if ($cm && !$cm->uservisible) {
2899 if ($preventredirect) {
2900 throw new require_login_exception('Activity is hidden');
2902 // Get the error message that activity is not available and why (if explanation can be shown to the user).
2903 $PAGE->set_course($course);
2904 $renderer = $PAGE->get_renderer('course');
2905 $message = $renderer->course_section_cm_unavailable_error_message($cm);
2906 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
2909 // Set the global $COURSE.
2910 if ($cm) {
2911 $PAGE->set_cm($cm, $course);
2912 $PAGE->set_pagelayout('incourse');
2913 } else if (!empty($courseorid)) {
2914 $PAGE->set_course($course);
2917 // Finally access granted, update lastaccess times.
2918 user_accesstime_log($course->id);
2923 * This function just makes sure a user is logged out.
2925 * @package core_access
2926 * @category access
2928 function require_logout() {
2929 global $USER, $DB;
2931 if (!isloggedin()) {
2932 // This should not happen often, no need for hooks or events here.
2933 \core\session\manager::terminate_current();
2934 return;
2937 // Execute hooks before action.
2938 $authplugins = array();
2939 $authsequence = get_enabled_auth_plugins();
2940 foreach ($authsequence as $authname) {
2941 $authplugins[$authname] = get_auth_plugin($authname);
2942 $authplugins[$authname]->prelogout_hook();
2945 // Store info that gets removed during logout.
2946 $sid = session_id();
2947 $event = \core\event\user_loggedout::create(
2948 array(
2949 'userid' => $USER->id,
2950 'objectid' => $USER->id,
2951 'other' => array('sessionid' => $sid),
2954 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2955 $event->add_record_snapshot('sessions', $session);
2958 // Clone of $USER object to be used by auth plugins.
2959 $user = fullclone($USER);
2961 // Delete session record and drop $_SESSION content.
2962 \core\session\manager::terminate_current();
2964 // Trigger event AFTER action.
2965 $event->trigger();
2967 // Hook to execute auth plugins redirection after event trigger.
2968 foreach ($authplugins as $authplugin) {
2969 $authplugin->postlogout_hook($user);
2974 * Weaker version of require_login()
2976 * This is a weaker version of {@link require_login()} which only requires login
2977 * when called from within a course rather than the site page, unless
2978 * the forcelogin option is turned on.
2979 * @see require_login()
2981 * @package core_access
2982 * @category access
2984 * @param mixed $courseorid The course object or id in question
2985 * @param bool $autologinguest Allow autologin guests if that is wanted
2986 * @param object $cm Course activity module if known
2987 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2988 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2989 * in order to keep redirects working properly. MDL-14495
2990 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2991 * @return void
2992 * @throws coding_exception
2994 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2995 global $CFG, $PAGE, $SITE;
2996 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
2997 or (!is_object($courseorid) and $courseorid == SITEID));
2998 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2999 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3000 // db queries so this is not really a performance concern, however it is obviously
3001 // better if you use get_fast_modinfo to get the cm before calling this.
3002 if (is_object($courseorid)) {
3003 $course = $courseorid;
3004 } else {
3005 $course = clone($SITE);
3007 $modinfo = get_fast_modinfo($course);
3008 $cm = $modinfo->get_cm($cm->id);
3010 if (!empty($CFG->forcelogin)) {
3011 // Login required for both SITE and courses.
3012 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3014 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3015 // Always login for hidden activities.
3016 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3018 } else if ($issite) {
3019 // Login for SITE not required.
3020 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3021 if (!empty($courseorid)) {
3022 if (is_object($courseorid)) {
3023 $course = $courseorid;
3024 } else {
3025 $course = clone $SITE;
3027 if ($cm) {
3028 if ($cm->course != $course->id) {
3029 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3031 $PAGE->set_cm($cm, $course);
3032 $PAGE->set_pagelayout('incourse');
3033 } else {
3034 $PAGE->set_course($course);
3036 } else {
3037 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3038 $PAGE->set_course($PAGE->course);
3040 user_accesstime_log(SITEID);
3041 return;
3043 } else {
3044 // Course login always required.
3045 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3050 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3052 * @param string $keyvalue the key value
3053 * @param string $script unique script identifier
3054 * @param int $instance instance id
3055 * @return stdClass the key entry in the user_private_key table
3056 * @since Moodle 3.2
3057 * @throws moodle_exception
3059 function validate_user_key($keyvalue, $script, $instance) {
3060 global $DB;
3062 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3063 print_error('invalidkey');
3066 if (!empty($key->validuntil) and $key->validuntil < time()) {
3067 print_error('expiredkey');
3070 if ($key->iprestriction) {
3071 $remoteaddr = getremoteaddr(null);
3072 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3073 print_error('ipmismatch');
3076 return $key;
3080 * Require key login. Function terminates with error if key not found or incorrect.
3082 * @uses NO_MOODLE_COOKIES
3083 * @uses PARAM_ALPHANUM
3084 * @param string $script unique script identifier
3085 * @param int $instance optional instance id
3086 * @return int Instance ID
3088 function require_user_key_login($script, $instance=null) {
3089 global $DB;
3091 if (!NO_MOODLE_COOKIES) {
3092 print_error('sessioncookiesdisable');
3095 // Extra safety.
3096 \core\session\manager::write_close();
3098 $keyvalue = required_param('key', PARAM_ALPHANUM);
3100 $key = validate_user_key($keyvalue, $script, $instance);
3102 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3103 print_error('invaliduserid');
3106 // Emulate normal session.
3107 enrol_check_plugins($user);
3108 \core\session\manager::set_user($user);
3110 // Note we are not using normal login.
3111 if (!defined('USER_KEY_LOGIN')) {
3112 define('USER_KEY_LOGIN', true);
3115 // Return instance id - it might be empty.
3116 return $key->instance;
3120 * Creates a new private user access key.
3122 * @param string $script unique target identifier
3123 * @param int $userid
3124 * @param int $instance optional instance id
3125 * @param string $iprestriction optional ip restricted access
3126 * @param int $validuntil key valid only until given data
3127 * @return string access key value
3129 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3130 global $DB;
3132 $key = new stdClass();
3133 $key->script = $script;
3134 $key->userid = $userid;
3135 $key->instance = $instance;
3136 $key->iprestriction = $iprestriction;
3137 $key->validuntil = $validuntil;
3138 $key->timecreated = time();
3140 // Something long and unique.
3141 $key->value = md5($userid.'_'.time().random_string(40));
3142 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3143 // Must be unique.
3144 $key->value = md5($userid.'_'.time().random_string(40));
3146 $DB->insert_record('user_private_key', $key);
3147 return $key->value;
3151 * Delete the user's new private user access keys for a particular script.
3153 * @param string $script unique target identifier
3154 * @param int $userid
3155 * @return void
3157 function delete_user_key($script, $userid) {
3158 global $DB;
3159 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3163 * Gets a private user access key (and creates one if one doesn't exist).
3165 * @param string $script unique target identifier
3166 * @param int $userid
3167 * @param int $instance optional instance id
3168 * @param string $iprestriction optional ip restricted access
3169 * @param int $validuntil key valid only until given date
3170 * @return string access key value
3172 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3173 global $DB;
3175 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3176 'instance' => $instance, 'iprestriction' => $iprestriction,
3177 'validuntil' => $validuntil))) {
3178 return $key->value;
3179 } else {
3180 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3186 * Modify the user table by setting the currently logged in user's last login to now.
3188 * @return bool Always returns true
3190 function update_user_login_times() {
3191 global $USER, $DB;
3193 if (isguestuser()) {
3194 // Do not update guest access times/ips for performance.
3195 return true;
3198 $now = time();
3200 $user = new stdClass();
3201 $user->id = $USER->id;
3203 // Make sure all users that logged in have some firstaccess.
3204 if ($USER->firstaccess == 0) {
3205 $USER->firstaccess = $user->firstaccess = $now;
3208 // Store the previous current as lastlogin.
3209 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3211 $USER->currentlogin = $user->currentlogin = $now;
3213 // Function user_accesstime_log() may not update immediately, better do it here.
3214 $USER->lastaccess = $user->lastaccess = $now;
3215 $USER->lastip = $user->lastip = getremoteaddr();
3217 // Note: do not call user_update_user() here because this is part of the login process,
3218 // the login event means that these fields were updated.
3219 $DB->update_record('user', $user);
3220 return true;
3224 * Determines if a user has completed setting up their account.
3226 * The lax mode (with $strict = false) has been introduced for special cases
3227 * only where we want to skip certain checks intentionally. This is valid in
3228 * certain mnet or ajax scenarios when the user cannot / should not be
3229 * redirected to edit their profile. In most cases, you should perform the
3230 * strict check.
3232 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3233 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3234 * @return bool
3236 function user_not_fully_set_up($user, $strict = true) {
3237 global $CFG;
3238 require_once($CFG->dirroot.'/user/profile/lib.php');
3240 if (isguestuser($user)) {
3241 return false;
3244 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3245 return true;
3248 if ($strict) {
3249 if (empty($user->id)) {
3250 // Strict mode can be used with existing accounts only.
3251 return true;
3253 if (!profile_has_required_custom_fields_set($user->id)) {
3254 return true;
3258 return false;
3262 * Check whether the user has exceeded the bounce threshold
3264 * @param stdClass $user A {@link $USER} object
3265 * @return bool true => User has exceeded bounce threshold
3267 function over_bounce_threshold($user) {
3268 global $CFG, $DB;
3270 if (empty($CFG->handlebounces)) {
3271 return false;
3274 if (empty($user->id)) {
3275 // No real (DB) user, nothing to do here.
3276 return false;
3279 // Set sensible defaults.
3280 if (empty($CFG->minbounces)) {
3281 $CFG->minbounces = 10;
3283 if (empty($CFG->bounceratio)) {
3284 $CFG->bounceratio = .20;
3286 $bouncecount = 0;
3287 $sendcount = 0;
3288 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3289 $bouncecount = $bounce->value;
3291 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3292 $sendcount = $send->value;
3294 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3298 * Used to increment or reset email sent count
3300 * @param stdClass $user object containing an id
3301 * @param bool $reset will reset the count to 0
3302 * @return void
3304 function set_send_count($user, $reset=false) {
3305 global $DB;
3307 if (empty($user->id)) {
3308 // No real (DB) user, nothing to do here.
3309 return;
3312 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3313 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3314 $DB->update_record('user_preferences', $pref);
3315 } else if (!empty($reset)) {
3316 // If it's not there and we're resetting, don't bother. Make a new one.
3317 $pref = new stdClass();
3318 $pref->name = 'email_send_count';
3319 $pref->value = 1;
3320 $pref->userid = $user->id;
3321 $DB->insert_record('user_preferences', $pref, false);
3326 * Increment or reset user's email bounce count
3328 * @param stdClass $user object containing an id
3329 * @param bool $reset will reset the count to 0
3331 function set_bounce_count($user, $reset=false) {
3332 global $DB;
3334 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3335 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3336 $DB->update_record('user_preferences', $pref);
3337 } else if (!empty($reset)) {
3338 // If it's not there and we're resetting, don't bother. Make a new one.
3339 $pref = new stdClass();
3340 $pref->name = 'email_bounce_count';
3341 $pref->value = 1;
3342 $pref->userid = $user->id;
3343 $DB->insert_record('user_preferences', $pref, false);
3348 * Determines if the logged in user is currently moving an activity
3350 * @param int $courseid The id of the course being tested
3351 * @return bool
3353 function ismoving($courseid) {
3354 global $USER;
3356 if (!empty($USER->activitycopy)) {
3357 return ($USER->activitycopycourse == $courseid);
3359 return false;
3363 * Returns a persons full name
3365 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3366 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3367 * specify one.
3369 * @param stdClass $user A {@link $USER} object to get full name of.
3370 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3371 * @return string
3373 function fullname($user, $override=false) {
3374 global $CFG, $SESSION;
3376 if (!isset($user->firstname) and !isset($user->lastname)) {
3377 return '';
3380 // Get all of the name fields.
3381 $allnames = get_all_user_name_fields();
3382 if ($CFG->debugdeveloper) {
3383 foreach ($allnames as $allname) {
3384 if (!property_exists($user, $allname)) {
3385 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3386 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3387 // Message has been sent, no point in sending the message multiple times.
3388 break;
3393 if (!$override) {
3394 if (!empty($CFG->forcefirstname)) {
3395 $user->firstname = $CFG->forcefirstname;
3397 if (!empty($CFG->forcelastname)) {
3398 $user->lastname = $CFG->forcelastname;
3402 if (!empty($SESSION->fullnamedisplay)) {
3403 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3406 $template = null;
3407 // If the fullnamedisplay setting is available, set the template to that.
3408 if (isset($CFG->fullnamedisplay)) {
3409 $template = $CFG->fullnamedisplay;
3411 // If the template is empty, or set to language, return the language string.
3412 if ((empty($template) || $template == 'language') && !$override) {
3413 return get_string('fullnamedisplay', null, $user);
3416 // Check to see if we are displaying according to the alternative full name format.
3417 if ($override) {
3418 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3419 // Default to show just the user names according to the fullnamedisplay string.
3420 return get_string('fullnamedisplay', null, $user);
3421 } else {
3422 // If the override is true, then change the template to use the complete name.
3423 $template = $CFG->alternativefullnameformat;
3427 $requirednames = array();
3428 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3429 foreach ($allnames as $allname) {
3430 if (strpos($template, $allname) !== false) {
3431 $requirednames[] = $allname;
3435 $displayname = $template;
3436 // Switch in the actual data into the template.
3437 foreach ($requirednames as $altname) {
3438 if (isset($user->$altname)) {
3439 // Using empty() on the below if statement causes breakages.
3440 if ((string)$user->$altname == '') {
3441 $displayname = str_replace($altname, 'EMPTY', $displayname);
3442 } else {
3443 $displayname = str_replace($altname, $user->$altname, $displayname);
3445 } else {
3446 $displayname = str_replace($altname, 'EMPTY', $displayname);
3449 // Tidy up any misc. characters (Not perfect, but gets most characters).
3450 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3451 // katakana and parenthesis.
3452 $patterns = array();
3453 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3454 // filled in by a user.
3455 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3456 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3457 // This regular expression is to remove any double spaces in the display name.
3458 $patterns[] = '/\s{2,}/u';
3459 foreach ($patterns as $pattern) {
3460 $displayname = preg_replace($pattern, ' ', $displayname);
3463 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3464 $displayname = trim($displayname);
3465 if (empty($displayname)) {
3466 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3467 // people in general feel is a good setting to fall back on.
3468 $displayname = $user->firstname;
3470 return $displayname;
3474 * A centralised location for the all name fields. Returns an array / sql string snippet.
3476 * @param bool $returnsql True for an sql select field snippet.
3477 * @param string $tableprefix table query prefix to use in front of each field.
3478 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3479 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3480 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3481 * @return array|string All name fields.
3483 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3484 // This array is provided in this order because when called by fullname() (above) if firstname is before
3485 // firstnamephonetic str_replace() will change the wrong placeholder.
3486 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3487 'lastnamephonetic' => 'lastnamephonetic',
3488 'middlename' => 'middlename',
3489 'alternatename' => 'alternatename',
3490 'firstname' => 'firstname',
3491 'lastname' => 'lastname');
3493 // Let's add a prefix to the array of user name fields if provided.
3494 if ($prefix) {
3495 foreach ($alternatenames as $key => $altname) {
3496 $alternatenames[$key] = $prefix . $altname;
3500 // If we want the end result to have firstname and lastname at the front / top of the result.
3501 if ($order) {
3502 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3503 for ($i = 0; $i < 2; $i++) {
3504 // Get the last element.
3505 $lastelement = end($alternatenames);
3506 // Remove it from the array.
3507 unset($alternatenames[$lastelement]);
3508 // Put the element back on the top of the array.
3509 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3513 // Create an sql field snippet if requested.
3514 if ($returnsql) {
3515 if ($tableprefix) {
3516 if ($fieldprefix) {
3517 foreach ($alternatenames as $key => $altname) {
3518 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3520 } else {
3521 foreach ($alternatenames as $key => $altname) {
3522 $alternatenames[$key] = $tableprefix . '.' . $altname;
3526 $alternatenames = implode(',', $alternatenames);
3528 return $alternatenames;
3532 * Reduces lines of duplicated code for getting user name fields.
3534 * See also {@link user_picture::unalias()}
3536 * @param object $addtoobject Object to add user name fields to.
3537 * @param object $secondobject Object that contains user name field information.
3538 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3539 * @param array $additionalfields Additional fields to be matched with data in the second object.
3540 * The key can be set to the user table field name.
3541 * @return object User name fields.
3543 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3544 $fields = get_all_user_name_fields(false, null, $prefix);
3545 if ($additionalfields) {
3546 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3547 // the key is a number and then sets the key to the array value.
3548 foreach ($additionalfields as $key => $value) {
3549 if (is_numeric($key)) {
3550 $additionalfields[$value] = $prefix . $value;
3551 unset($additionalfields[$key]);
3552 } else {
3553 $additionalfields[$key] = $prefix . $value;
3556 $fields = array_merge($fields, $additionalfields);
3558 foreach ($fields as $key => $field) {
3559 // Important that we have all of the user name fields present in the object that we are sending back.
3560 $addtoobject->$key = '';
3561 if (isset($secondobject->$field)) {
3562 $addtoobject->$key = $secondobject->$field;
3565 return $addtoobject;
3569 * Returns an array of values in order of occurance in a provided string.
3570 * The key in the result is the character postion in the string.
3572 * @param array $values Values to be found in the string format
3573 * @param string $stringformat The string which may contain values being searched for.
3574 * @return array An array of values in order according to placement in the string format.
3576 function order_in_string($values, $stringformat) {
3577 $valuearray = array();
3578 foreach ($values as $value) {
3579 $pattern = "/$value\b/";
3580 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3581 if (preg_match($pattern, $stringformat)) {
3582 $replacement = "thing";
3583 // Replace the value with something more unique to ensure we get the right position when using strpos().
3584 $newformat = preg_replace($pattern, $replacement, $stringformat);
3585 $position = strpos($newformat, $replacement);
3586 $valuearray[$position] = $value;
3589 ksort($valuearray);
3590 return $valuearray;
3594 * Checks if current user is shown any extra fields when listing users.
3596 * @param object $context Context
3597 * @param array $already Array of fields that we're going to show anyway
3598 * so don't bother listing them
3599 * @return array Array of field names from user table, not including anything
3600 * listed in $already
3602 function get_extra_user_fields($context, $already = array()) {
3603 global $CFG;
3605 // Only users with permission get the extra fields.
3606 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3607 return array();
3610 // Split showuseridentity on comma.
3611 if (empty($CFG->showuseridentity)) {
3612 // Explode gives wrong result with empty string.
3613 $extra = array();
3614 } else {
3615 $extra = explode(',', $CFG->showuseridentity);
3617 $renumber = false;
3618 foreach ($extra as $key => $field) {
3619 if (in_array($field, $already)) {
3620 unset($extra[$key]);
3621 $renumber = true;
3624 if ($renumber) {
3625 // For consistency, if entries are removed from array, renumber it
3626 // so they are numbered as you would expect.
3627 $extra = array_merge($extra);
3629 return $extra;
3633 * If the current user is to be shown extra user fields when listing or
3634 * selecting users, returns a string suitable for including in an SQL select
3635 * clause to retrieve those fields.
3637 * @param context $context Context
3638 * @param string $alias Alias of user table, e.g. 'u' (default none)
3639 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3640 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3641 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3643 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3644 $fields = get_extra_user_fields($context, $already);
3645 $result = '';
3646 // Add punctuation for alias.
3647 if ($alias !== '') {
3648 $alias .= '.';
3650 foreach ($fields as $field) {
3651 $result .= ', ' . $alias . $field;
3652 if ($prefix) {
3653 $result .= ' AS ' . $prefix . $field;
3656 return $result;
3660 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3661 * @param string $field Field name, e.g. 'phone1'
3662 * @return string Text description taken from language file, e.g. 'Phone number'
3664 function get_user_field_name($field) {
3665 // Some fields have language strings which are not the same as field name.
3666 switch ($field) {
3667 case 'url' : {
3668 return get_string('webpage');
3670 case 'icq' : {
3671 return get_string('icqnumber');
3673 case 'skype' : {
3674 return get_string('skypeid');
3676 case 'aim' : {
3677 return get_string('aimid');
3679 case 'yahoo' : {
3680 return get_string('yahooid');
3682 case 'msn' : {
3683 return get_string('msnid');
3686 // Otherwise just use the same lang string.
3687 return get_string($field);
3691 * Returns whether a given authentication plugin exists.
3693 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3694 * @return boolean Whether the plugin is available.
3696 function exists_auth_plugin($auth) {
3697 global $CFG;
3699 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3700 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3702 return false;
3706 * Checks if a given plugin is in the list of enabled authentication plugins.
3708 * @param string $auth Authentication plugin.
3709 * @return boolean Whether the plugin is enabled.
3711 function is_enabled_auth($auth) {
3712 if (empty($auth)) {
3713 return false;
3716 $enabled = get_enabled_auth_plugins();
3718 return in_array($auth, $enabled);
3722 * Returns an authentication plugin instance.
3724 * @param string $auth name of authentication plugin
3725 * @return auth_plugin_base An instance of the required authentication plugin.
3727 function get_auth_plugin($auth) {
3728 global $CFG;
3730 // Check the plugin exists first.
3731 if (! exists_auth_plugin($auth)) {
3732 print_error('authpluginnotfound', 'debug', '', $auth);
3735 // Return auth plugin instance.
3736 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3737 $class = "auth_plugin_$auth";
3738 return new $class;
3742 * Returns array of active auth plugins.
3744 * @param bool $fix fix $CFG->auth if needed
3745 * @return array
3747 function get_enabled_auth_plugins($fix=false) {
3748 global $CFG;
3750 $default = array('manual', 'nologin');
3752 if (empty($CFG->auth)) {
3753 $auths = array();
3754 } else {
3755 $auths = explode(',', $CFG->auth);
3758 if ($fix) {
3759 $auths = array_unique($auths);
3760 foreach ($auths as $k => $authname) {
3761 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3762 unset($auths[$k]);
3765 $newconfig = implode(',', $auths);
3766 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3767 set_config('auth', $newconfig);
3771 return (array_merge($default, $auths));
3775 * Returns true if an internal authentication method is being used.
3776 * if method not specified then, global default is assumed
3778 * @param string $auth Form of authentication required
3779 * @return bool
3781 function is_internal_auth($auth) {
3782 // Throws error if bad $auth.
3783 $authplugin = get_auth_plugin($auth);
3784 return $authplugin->is_internal();
3788 * Returns true if the user is a 'restored' one.
3790 * Used in the login process to inform the user and allow him/her to reset the password
3792 * @param string $username username to be checked
3793 * @return bool
3795 function is_restored_user($username) {
3796 global $CFG, $DB;
3798 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3802 * Returns an array of user fields
3804 * @return array User field/column names
3806 function get_user_fieldnames() {
3807 global $DB;
3809 $fieldarray = $DB->get_columns('user');
3810 unset($fieldarray['id']);
3811 $fieldarray = array_keys($fieldarray);
3813 return $fieldarray;
3817 * Creates a bare-bones user record
3819 * @todo Outline auth types and provide code example
3821 * @param string $username New user's username to add to record
3822 * @param string $password New user's password to add to record
3823 * @param string $auth Form of authentication required
3824 * @return stdClass A complete user object
3826 function create_user_record($username, $password, $auth = 'manual') {
3827 global $CFG, $DB;
3828 require_once($CFG->dirroot.'/user/profile/lib.php');
3829 require_once($CFG->dirroot.'/user/lib.php');
3831 // Just in case check text case.
3832 $username = trim(core_text::strtolower($username));
3834 $authplugin = get_auth_plugin($auth);
3835 $customfields = $authplugin->get_custom_user_profile_fields();
3836 $newuser = new stdClass();
3837 if ($newinfo = $authplugin->get_userinfo($username)) {
3838 $newinfo = truncate_userinfo($newinfo);
3839 foreach ($newinfo as $key => $value) {
3840 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3841 $newuser->$key = $value;
3846 if (!empty($newuser->email)) {
3847 if (email_is_not_allowed($newuser->email)) {
3848 unset($newuser->email);
3852 if (!isset($newuser->city)) {
3853 $newuser->city = '';
3856 $newuser->auth = $auth;
3857 $newuser->username = $username;
3859 // Fix for MDL-8480
3860 // user CFG lang for user if $newuser->lang is empty
3861 // or $user->lang is not an installed language.
3862 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3863 $newuser->lang = $CFG->lang;
3865 $newuser->confirmed = 1;
3866 $newuser->lastip = getremoteaddr();
3867 $newuser->timecreated = time();
3868 $newuser->timemodified = $newuser->timecreated;
3869 $newuser->mnethostid = $CFG->mnet_localhost_id;
3871 $newuser->id = user_create_user($newuser, false, false);
3873 // Save user profile data.
3874 profile_save_data($newuser);
3876 $user = get_complete_user_data('id', $newuser->id);
3877 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3878 set_user_preference('auth_forcepasswordchange', 1, $user);
3880 // Set the password.
3881 update_internal_user_password($user, $password);
3883 // Trigger event.
3884 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3886 return $user;
3890 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3892 * @param string $username user's username to update the record
3893 * @return stdClass A complete user object
3895 function update_user_record($username) {
3896 global $DB, $CFG;
3897 // Just in case check text case.
3898 $username = trim(core_text::strtolower($username));
3900 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3901 return update_user_record_by_id($oldinfo->id);
3905 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3907 * @param int $id user id
3908 * @return stdClass A complete user object
3910 function update_user_record_by_id($id) {
3911 global $DB, $CFG;
3912 require_once($CFG->dirroot."/user/profile/lib.php");
3913 require_once($CFG->dirroot.'/user/lib.php');
3915 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3916 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3918 $newuser = array();
3919 $userauth = get_auth_plugin($oldinfo->auth);
3921 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3922 $newinfo = truncate_userinfo($newinfo);
3923 $customfields = $userauth->get_custom_user_profile_fields();
3925 foreach ($newinfo as $key => $value) {
3926 $iscustom = in_array($key, $customfields);
3927 if (!$iscustom) {
3928 $key = strtolower($key);
3930 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3931 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3932 // Unknown or must not be changed.
3933 continue;
3935 $confval = $userauth->config->{'field_updatelocal_' . $key};
3936 $lockval = $userauth->config->{'field_lock_' . $key};
3937 if (empty($confval) || empty($lockval)) {
3938 continue;
3940 if ($confval === 'onlogin') {
3941 // MDL-4207 Don't overwrite modified user profile values with
3942 // empty LDAP values when 'unlocked if empty' is set. The purpose
3943 // of the setting 'unlocked if empty' is to allow the user to fill
3944 // in a value for the selected field _if LDAP is giving
3945 // nothing_ for this field. Thus it makes sense to let this value
3946 // stand in until LDAP is giving a value for this field.
3947 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3948 if ($iscustom || (in_array($key, $userauth->userfields) &&
3949 ((string)$oldinfo->$key !== (string)$value))) {
3950 $newuser[$key] = (string)$value;
3955 if ($newuser) {
3956 $newuser['id'] = $oldinfo->id;
3957 $newuser['timemodified'] = time();
3958 user_update_user((object) $newuser, false, false);
3960 // Save user profile data.
3961 profile_save_data((object) $newuser);
3963 // Trigger event.
3964 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
3968 return get_complete_user_data('id', $oldinfo->id);
3972 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
3974 * @param array $info Array of user properties to truncate if needed
3975 * @return array The now truncated information that was passed in
3977 function truncate_userinfo(array $info) {
3978 // Define the limits.
3979 $limit = array(
3980 'username' => 100,
3981 'idnumber' => 255,
3982 'firstname' => 100,
3983 'lastname' => 100,
3984 'email' => 100,
3985 'icq' => 15,
3986 'phone1' => 20,
3987 'phone2' => 20,
3988 'institution' => 255,
3989 'department' => 255,
3990 'address' => 255,
3991 'city' => 120,
3992 'country' => 2,
3993 'url' => 255,
3996 // Apply where needed.
3997 foreach (array_keys($info) as $key) {
3998 if (!empty($limit[$key])) {
3999 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4003 return $info;
4007 * Marks user deleted in internal user database and notifies the auth plugin.
4008 * Also unenrols user from all roles and does other cleanup.
4010 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4012 * @param stdClass $user full user object before delete
4013 * @return boolean success
4014 * @throws coding_exception if invalid $user parameter detected
4016 function delete_user(stdClass $user) {
4017 global $CFG, $DB;
4018 require_once($CFG->libdir.'/grouplib.php');
4019 require_once($CFG->libdir.'/gradelib.php');
4020 require_once($CFG->dirroot.'/message/lib.php');
4021 require_once($CFG->dirroot.'/user/lib.php');
4023 // Make sure nobody sends bogus record type as parameter.
4024 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4025 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4028 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4029 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4030 debugging('Attempt to delete unknown user account.');
4031 return false;
4034 // There must be always exactly one guest record, originally the guest account was identified by username only,
4035 // now we use $CFG->siteguest for performance reasons.
4036 if ($user->username === 'guest' or isguestuser($user)) {
4037 debugging('Guest user account can not be deleted.');
4038 return false;
4041 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4042 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4043 if ($user->auth === 'manual' and is_siteadmin($user)) {
4044 debugging('Local administrator accounts can not be deleted.');
4045 return false;
4048 // Allow plugins to use this user object before we completely delete it.
4049 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4050 foreach ($pluginsfunction as $plugintype => $plugins) {
4051 foreach ($plugins as $pluginfunction) {
4052 $pluginfunction($user);
4057 // Keep user record before updating it, as we have to pass this to user_deleted event.
4058 $olduser = clone $user;
4060 // Keep a copy of user context, we need it for event.
4061 $usercontext = context_user::instance($user->id);
4063 // Delete all grades - backup is kept in grade_grades_history table.
4064 grade_user_delete($user->id);
4066 // Move unread messages from this user to read.
4067 message_move_userfrom_unread2read($user->id);
4069 // TODO: remove from cohorts using standard API here.
4071 // Remove user tags.
4072 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4074 // Unconditionally unenrol from all courses.
4075 enrol_user_delete($user);
4077 // Unenrol from all roles in all contexts.
4078 // This might be slow but it is really needed - modules might do some extra cleanup!
4079 role_unassign_all(array('userid' => $user->id));
4081 // Now do a brute force cleanup.
4083 // Remove from all cohorts.
4084 $DB->delete_records('cohort_members', array('userid' => $user->id));
4086 // Remove from all groups.
4087 $DB->delete_records('groups_members', array('userid' => $user->id));
4089 // Brute force unenrol from all courses.
4090 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4092 // Purge user preferences.
4093 $DB->delete_records('user_preferences', array('userid' => $user->id));
4095 // Purge user extra profile info.
4096 $DB->delete_records('user_info_data', array('userid' => $user->id));
4098 // Purge log of previous password hashes.
4099 $DB->delete_records('user_password_history', array('userid' => $user->id));
4101 // Last course access not necessary either.
4102 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4103 // Remove all user tokens.
4104 $DB->delete_records('external_tokens', array('userid' => $user->id));
4106 // Unauthorise the user for all services.
4107 $DB->delete_records('external_services_users', array('userid' => $user->id));
4109 // Remove users private keys.
4110 $DB->delete_records('user_private_key', array('userid' => $user->id));
4112 // Remove users customised pages.
4113 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4115 // Force logout - may fail if file based sessions used, sorry.
4116 \core\session\manager::kill_user_sessions($user->id);
4118 // Generate username from email address, or a fake email.
4119 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4120 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
4122 // Workaround for bulk deletes of users with the same email address.
4123 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4124 $delname++;
4127 // Mark internal user record as "deleted".
4128 $updateuser = new stdClass();
4129 $updateuser->id = $user->id;
4130 $updateuser->deleted = 1;
4131 $updateuser->username = $delname; // Remember it just in case.
4132 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4133 $updateuser->idnumber = ''; // Clear this field to free it up.
4134 $updateuser->picture = 0;
4135 $updateuser->timemodified = time();
4137 // Don't trigger update event, as user is being deleted.
4138 user_update_user($updateuser, false, false);
4140 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4141 context_helper::delete_instance(CONTEXT_USER, $user->id);
4143 // Any plugin that needs to cleanup should register this event.
4144 // Trigger event.
4145 $event = \core\event\user_deleted::create(
4146 array(
4147 'objectid' => $user->id,
4148 'relateduserid' => $user->id,
4149 'context' => $usercontext,
4150 'other' => array(
4151 'username' => $user->username,
4152 'email' => $user->email,
4153 'idnumber' => $user->idnumber,
4154 'picture' => $user->picture,
4155 'mnethostid' => $user->mnethostid
4159 $event->add_record_snapshot('user', $olduser);
4160 $event->trigger();
4162 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4163 // should know about this updated property persisted to the user's table.
4164 $user->timemodified = $updateuser->timemodified;
4166 // Notify auth plugin - do not block the delete even when plugin fails.
4167 $authplugin = get_auth_plugin($user->auth);
4168 $authplugin->user_delete($user);
4170 return true;
4174 * Retrieve the guest user object.
4176 * @return stdClass A {@link $USER} object
4178 function guest_user() {
4179 global $CFG, $DB;
4181 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4182 $newuser->confirmed = 1;
4183 $newuser->lang = $CFG->lang;
4184 $newuser->lastip = getremoteaddr();
4187 return $newuser;
4191 * Authenticates a user against the chosen authentication mechanism
4193 * Given a username and password, this function looks them
4194 * up using the currently selected authentication mechanism,
4195 * and if the authentication is successful, it returns a
4196 * valid $user object from the 'user' table.
4198 * Uses auth_ functions from the currently active auth module
4200 * After authenticate_user_login() returns success, you will need to
4201 * log that the user has logged in, and call complete_user_login() to set
4202 * the session up.
4204 * Note: this function works only with non-mnet accounts!
4206 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4207 * @param string $password User's password
4208 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4209 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4210 * @return stdClass|false A {@link $USER} object or false if error
4212 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4213 global $CFG, $DB;
4214 require_once("$CFG->libdir/authlib.php");
4216 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4217 // we have found the user
4219 } else if (!empty($CFG->authloginviaemail)) {
4220 if ($email = clean_param($username, PARAM_EMAIL)) {
4221 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4222 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4223 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4224 if (count($users) === 1) {
4225 // Use email for login only if unique.
4226 $user = reset($users);
4227 $user = get_complete_user_data('id', $user->id);
4228 $username = $user->username;
4230 unset($users);
4234 $authsenabled = get_enabled_auth_plugins();
4236 if ($user) {
4237 // Use manual if auth not set.
4238 $auth = empty($user->auth) ? 'manual' : $user->auth;
4240 if (in_array($user->auth, $authsenabled)) {
4241 $authplugin = get_auth_plugin($user->auth);
4242 $authplugin->pre_user_login_hook($user);
4245 if (!empty($user->suspended)) {
4246 $failurereason = AUTH_LOGIN_SUSPENDED;
4248 // Trigger login failed event.
4249 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4250 'other' => array('username' => $username, 'reason' => $failurereason)));
4251 $event->trigger();
4252 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4253 return false;
4255 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4256 // Legacy way to suspend user.
4257 $failurereason = AUTH_LOGIN_SUSPENDED;
4259 // Trigger login failed event.
4260 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4261 'other' => array('username' => $username, 'reason' => $failurereason)));
4262 $event->trigger();
4263 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4264 return false;
4266 $auths = array($auth);
4268 } else {
4269 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4270 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4271 $failurereason = AUTH_LOGIN_NOUSER;
4273 // Trigger login failed event.
4274 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4275 'reason' => $failurereason)));
4276 $event->trigger();
4277 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4278 return false;
4281 // User does not exist.
4282 $auths = $authsenabled;
4283 $user = new stdClass();
4284 $user->id = 0;
4287 if ($ignorelockout) {
4288 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4289 // or this function is called from a SSO script.
4290 } else if ($user->id) {
4291 // Verify login lockout after other ways that may prevent user login.
4292 if (login_is_lockedout($user)) {
4293 $failurereason = AUTH_LOGIN_LOCKOUT;
4295 // Trigger login failed event.
4296 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4297 'other' => array('username' => $username, 'reason' => $failurereason)));
4298 $event->trigger();
4300 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4301 return false;
4303 } else {
4304 // We can not lockout non-existing accounts.
4307 foreach ($auths as $auth) {
4308 $authplugin = get_auth_plugin($auth);
4310 // On auth fail fall through to the next plugin.
4311 if (!$authplugin->user_login($username, $password)) {
4312 continue;
4315 // Successful authentication.
4316 if ($user->id) {
4317 // User already exists in database.
4318 if (empty($user->auth)) {
4319 // For some reason auth isn't set yet.
4320 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4321 $user->auth = $auth;
4324 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4325 // the current hash algorithm while we have access to the user's password.
4326 update_internal_user_password($user, $password);
4328 if ($authplugin->is_synchronised_with_external()) {
4329 // Update user record from external DB.
4330 $user = update_user_record_by_id($user->id);
4332 } else {
4333 // The user is authenticated but user creation may be disabled.
4334 if (!empty($CFG->authpreventaccountcreation)) {
4335 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4337 // Trigger login failed event.
4338 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4339 'reason' => $failurereason)));
4340 $event->trigger();
4342 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4343 $_SERVER['HTTP_USER_AGENT']);
4344 return false;
4345 } else {
4346 $user = create_user_record($username, $password, $auth);
4350 $authplugin->sync_roles($user);
4352 foreach ($authsenabled as $hau) {
4353 $hauth = get_auth_plugin($hau);
4354 $hauth->user_authenticated_hook($user, $username, $password);
4357 if (empty($user->id)) {
4358 $failurereason = AUTH_LOGIN_NOUSER;
4359 // Trigger login failed event.
4360 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4361 'reason' => $failurereason)));
4362 $event->trigger();
4363 return false;
4366 if (!empty($user->suspended)) {
4367 // Just in case some auth plugin suspended account.
4368 $failurereason = AUTH_LOGIN_SUSPENDED;
4369 // Trigger login failed event.
4370 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4371 'other' => array('username' => $username, 'reason' => $failurereason)));
4372 $event->trigger();
4373 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4374 return false;
4377 login_attempt_valid($user);
4378 $failurereason = AUTH_LOGIN_OK;
4379 return $user;
4382 // Failed if all the plugins have failed.
4383 if (debugging('', DEBUG_ALL)) {
4384 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4387 if ($user->id) {
4388 login_attempt_failed($user);
4389 $failurereason = AUTH_LOGIN_FAILED;
4390 // Trigger login failed event.
4391 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4392 'other' => array('username' => $username, 'reason' => $failurereason)));
4393 $event->trigger();
4394 } else {
4395 $failurereason = AUTH_LOGIN_NOUSER;
4396 // Trigger login failed event.
4397 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4398 'reason' => $failurereason)));
4399 $event->trigger();
4402 return false;
4406 * Call to complete the user login process after authenticate_user_login()
4407 * has succeeded. It will setup the $USER variable and other required bits
4408 * and pieces.
4410 * NOTE:
4411 * - It will NOT log anything -- up to the caller to decide what to log.
4412 * - this function does not set any cookies any more!
4414 * @param stdClass $user
4415 * @return stdClass A {@link $USER} object - BC only, do not use
4417 function complete_user_login($user) {
4418 global $CFG, $USER, $SESSION;
4420 \core\session\manager::login_user($user);
4422 // Reload preferences from DB.
4423 unset($USER->preference);
4424 check_user_preferences_loaded($USER);
4426 // Update login times.
4427 update_user_login_times();
4429 // Extra session prefs init.
4430 set_login_session_preferences();
4432 // Trigger login event.
4433 $event = \core\event\user_loggedin::create(
4434 array(
4435 'userid' => $USER->id,
4436 'objectid' => $USER->id,
4437 'other' => array('username' => $USER->username),
4440 $event->trigger();
4442 if (isguestuser()) {
4443 // No need to continue when user is THE guest.
4444 return $USER;
4447 if (CLI_SCRIPT) {
4448 // We can redirect to password change URL only in browser.
4449 return $USER;
4452 // Select password change url.
4453 $userauth = get_auth_plugin($USER->auth);
4455 // Check whether the user should be changing password.
4456 if (get_user_preferences('auth_forcepasswordchange', false)) {
4457 if ($userauth->can_change_password()) {
4458 if ($changeurl = $userauth->change_password_url()) {
4459 redirect($changeurl);
4460 } else {
4461 require_once($CFG->dirroot . '/login/lib.php');
4462 $SESSION->wantsurl = core_login_get_return_url();
4463 redirect($CFG->httpswwwroot.'/login/change_password.php');
4465 } else {
4466 print_error('nopasswordchangeforced', 'auth');
4469 return $USER;
4473 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4475 * @param string $password String to check.
4476 * @return boolean True if the $password matches the format of an md5 sum.
4478 function password_is_legacy_hash($password) {
4479 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4483 * Compare password against hash stored in user object to determine if it is valid.
4485 * If necessary it also updates the stored hash to the current format.
4487 * @param stdClass $user (Password property may be updated).
4488 * @param string $password Plain text password.
4489 * @return bool True if password is valid.
4491 function validate_internal_user_password($user, $password) {
4492 global $CFG;
4494 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4495 // Internal password is not used at all, it can not validate.
4496 return false;
4499 // If hash isn't a legacy (md5) hash, validate using the library function.
4500 if (!password_is_legacy_hash($user->password)) {
4501 return password_verify($password, $user->password);
4504 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4505 // is valid we can then update it to the new algorithm.
4507 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4508 $validated = false;
4510 if ($user->password === md5($password.$sitesalt)
4511 or $user->password === md5($password)
4512 or $user->password === md5(addslashes($password).$sitesalt)
4513 or $user->password === md5(addslashes($password))) {
4514 // Note: we are intentionally using the addslashes() here because we
4515 // need to accept old password hashes of passwords with magic quotes.
4516 $validated = true;
4518 } else {
4519 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4520 $alt = 'passwordsaltalt'.$i;
4521 if (!empty($CFG->$alt)) {
4522 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4523 $validated = true;
4524 break;
4530 if ($validated) {
4531 // If the password matches the existing md5 hash, update to the
4532 // current hash algorithm while we have access to the user's password.
4533 update_internal_user_password($user, $password);
4536 return $validated;
4540 * Calculate hash for a plain text password.
4542 * @param string $password Plain text password to be hashed.
4543 * @param bool $fasthash If true, use a low cost factor when generating the hash
4544 * This is much faster to generate but makes the hash
4545 * less secure. It is used when lots of hashes need to
4546 * be generated quickly.
4547 * @return string The hashed password.
4549 * @throws moodle_exception If a problem occurs while generating the hash.
4551 function hash_internal_user_password($password, $fasthash = false) {
4552 global $CFG;
4554 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4555 $options = ($fasthash) ? array('cost' => 4) : array();
4557 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4559 if ($generatedhash === false || $generatedhash === null) {
4560 throw new moodle_exception('Failed to generate password hash.');
4563 return $generatedhash;
4567 * Update password hash in user object (if necessary).
4569 * The password is updated if:
4570 * 1. The password has changed (the hash of $user->password is different
4571 * to the hash of $password).
4572 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4573 * md5 algorithm).
4575 * Updating the password will modify the $user object and the database
4576 * record to use the current hashing algorithm.
4577 * It will remove Web Services user tokens too.
4579 * @param stdClass $user User object (password property may be updated).
4580 * @param string $password Plain text password.
4581 * @param bool $fasthash If true, use a low cost factor when generating the hash
4582 * This is much faster to generate but makes the hash
4583 * less secure. It is used when lots of hashes need to
4584 * be generated quickly.
4585 * @return bool Always returns true.
4587 function update_internal_user_password($user, $password, $fasthash = false) {
4588 global $CFG, $DB;
4590 // Figure out what the hashed password should be.
4591 if (!isset($user->auth)) {
4592 debugging('User record in update_internal_user_password() must include field auth',
4593 DEBUG_DEVELOPER);
4594 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4596 $authplugin = get_auth_plugin($user->auth);
4597 if ($authplugin->prevent_local_passwords()) {
4598 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4599 } else {
4600 $hashedpassword = hash_internal_user_password($password, $fasthash);
4603 $algorithmchanged = false;
4605 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4606 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4607 $passwordchanged = ($user->password !== $hashedpassword);
4609 } else if (isset($user->password)) {
4610 // If verification fails then it means the password has changed.
4611 $passwordchanged = !password_verify($password, $user->password);
4612 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4613 } else {
4614 // While creating new user, password in unset in $user object, to avoid
4615 // saving it with user_create()
4616 $passwordchanged = true;
4619 if ($passwordchanged || $algorithmchanged) {
4620 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4621 $user->password = $hashedpassword;
4623 // Trigger event.
4624 $user = $DB->get_record('user', array('id' => $user->id));
4625 \core\event\user_password_updated::create_from_user($user)->trigger();
4627 // Remove WS user tokens.
4628 if (!empty($CFG->passwordchangetokendeletion)) {
4629 require_once($CFG->dirroot.'/webservice/lib.php');
4630 webservice::delete_user_ws_tokens($user->id);
4634 return true;
4638 * Get a complete user record, which includes all the info in the user record.
4640 * Intended for setting as $USER session variable
4642 * @param string $field The user field to be checked for a given value.
4643 * @param string $value The value to match for $field.
4644 * @param int $mnethostid
4645 * @return mixed False, or A {@link $USER} object.
4647 function get_complete_user_data($field, $value, $mnethostid = null) {
4648 global $CFG, $DB;
4650 if (!$field || !$value) {
4651 return false;
4654 // Build the WHERE clause for an SQL query.
4655 $params = array('fieldval' => $value);
4656 $constraints = "$field = :fieldval AND deleted <> 1";
4658 // If we are loading user data based on anything other than id,
4659 // we must also restrict our search based on mnet host.
4660 if ($field != 'id') {
4661 if (empty($mnethostid)) {
4662 // If empty, we restrict to local users.
4663 $mnethostid = $CFG->mnet_localhost_id;
4666 if (!empty($mnethostid)) {
4667 $params['mnethostid'] = $mnethostid;
4668 $constraints .= " AND mnethostid = :mnethostid";
4671 // Get all the basic user data.
4672 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4673 return false;
4676 // Get various settings and preferences.
4678 // Preload preference cache.
4679 check_user_preferences_loaded($user);
4681 // Load course enrolment related stuff.
4682 $user->lastcourseaccess = array(); // During last session.
4683 $user->currentcourseaccess = array(); // During current session.
4684 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4685 foreach ($lastaccesses as $lastaccess) {
4686 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4690 $sql = "SELECT g.id, g.courseid
4691 FROM {groups} g, {groups_members} gm
4692 WHERE gm.groupid=g.id AND gm.userid=?";
4694 // This is a special hack to speedup calendar display.
4695 $user->groupmember = array();
4696 if (!isguestuser($user)) {
4697 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4698 foreach ($groups as $group) {
4699 if (!array_key_exists($group->courseid, $user->groupmember)) {
4700 $user->groupmember[$group->courseid] = array();
4702 $user->groupmember[$group->courseid][$group->id] = $group->id;
4707 // Add the custom profile fields to the user record.
4708 $user->profile = array();
4709 if (!isguestuser($user)) {
4710 require_once($CFG->dirroot.'/user/profile/lib.php');
4711 profile_load_custom_fields($user);
4714 // Rewrite some variables if necessary.
4715 if (!empty($user->description)) {
4716 // No need to cart all of it around.
4717 $user->description = true;
4719 if (isguestuser($user)) {
4720 // Guest language always same as site.
4721 $user->lang = $CFG->lang;
4722 // Name always in current language.
4723 $user->firstname = get_string('guestuser');
4724 $user->lastname = ' ';
4727 return $user;
4731 * Validate a password against the configured password policy
4733 * @param string $password the password to be checked against the password policy
4734 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4735 * @return bool true if the password is valid according to the policy. false otherwise.
4737 function check_password_policy($password, &$errmsg) {
4738 global $CFG;
4740 if (empty($CFG->passwordpolicy)) {
4741 return true;
4744 $errmsg = '';
4745 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4746 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4749 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4750 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4753 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4754 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4757 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4758 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4761 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4762 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4764 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4765 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4768 if ($errmsg == '') {
4769 return true;
4770 } else {
4771 return false;
4777 * When logging in, this function is run to set certain preferences for the current SESSION.
4779 function set_login_session_preferences() {
4780 global $SESSION;
4782 $SESSION->justloggedin = true;
4784 unset($SESSION->lang);
4785 unset($SESSION->forcelang);
4786 unset($SESSION->load_navigation_admin);
4791 * Delete a course, including all related data from the database, and any associated files.
4793 * @param mixed $courseorid The id of the course or course object to delete.
4794 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4795 * @return bool true if all the removals succeeded. false if there were any failures. If this
4796 * method returns false, some of the removals will probably have succeeded, and others
4797 * failed, but you have no way of knowing which.
4799 function delete_course($courseorid, $showfeedback = true) {
4800 global $DB;
4802 if (is_object($courseorid)) {
4803 $courseid = $courseorid->id;
4804 $course = $courseorid;
4805 } else {
4806 $courseid = $courseorid;
4807 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4808 return false;
4811 $context = context_course::instance($courseid);
4813 // Frontpage course can not be deleted!!
4814 if ($courseid == SITEID) {
4815 return false;
4818 // Allow plugins to use this course before we completely delete it.
4819 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
4820 foreach ($pluginsfunction as $plugintype => $plugins) {
4821 foreach ($plugins as $pluginfunction) {
4822 $pluginfunction($course);
4827 // Make the course completely empty.
4828 remove_course_contents($courseid, $showfeedback);
4830 // Delete the course and related context instance.
4831 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4833 $DB->delete_records("course", array("id" => $courseid));
4834 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4836 // Reset all course related caches here.
4837 if (class_exists('format_base', false)) {
4838 format_base::reset_course_cache($courseid);
4841 // Trigger a course deleted event.
4842 $event = \core\event\course_deleted::create(array(
4843 'objectid' => $course->id,
4844 'context' => $context,
4845 'other' => array(
4846 'shortname' => $course->shortname,
4847 'fullname' => $course->fullname,
4848 'idnumber' => $course->idnumber
4851 $event->add_record_snapshot('course', $course);
4852 $event->trigger();
4854 return true;
4858 * Clear a course out completely, deleting all content but don't delete the course itself.
4860 * This function does not verify any permissions.
4862 * Please note this function also deletes all user enrolments,
4863 * enrolment instances and role assignments by default.
4865 * $options:
4866 * - 'keep_roles_and_enrolments' - false by default
4867 * - 'keep_groups_and_groupings' - false by default
4869 * @param int $courseid The id of the course that is being deleted
4870 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4871 * @param array $options extra options
4872 * @return bool true if all the removals succeeded. false if there were any failures. If this
4873 * method returns false, some of the removals will probably have succeeded, and others
4874 * failed, but you have no way of knowing which.
4876 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4877 global $CFG, $DB, $OUTPUT;
4879 require_once($CFG->libdir.'/badgeslib.php');
4880 require_once($CFG->libdir.'/completionlib.php');
4881 require_once($CFG->libdir.'/questionlib.php');
4882 require_once($CFG->libdir.'/gradelib.php');
4883 require_once($CFG->dirroot.'/group/lib.php');
4884 require_once($CFG->dirroot.'/comment/lib.php');
4885 require_once($CFG->dirroot.'/rating/lib.php');
4886 require_once($CFG->dirroot.'/notes/lib.php');
4888 // Handle course badges.
4889 badges_handle_course_deletion($courseid);
4891 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4892 $strdeleted = get_string('deleted').' - ';
4894 // Some crazy wishlist of stuff we should skip during purging of course content.
4895 $options = (array)$options;
4897 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
4898 $coursecontext = context_course::instance($courseid);
4899 $fs = get_file_storage();
4901 // Delete course completion information, this has to be done before grades and enrols.
4902 $cc = new completion_info($course);
4903 $cc->clear_criteria();
4904 if ($showfeedback) {
4905 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4908 // Remove all data from gradebook - this needs to be done before course modules
4909 // because while deleting this information, the system may need to reference
4910 // the course modules that own the grades.
4911 remove_course_grades($courseid, $showfeedback);
4912 remove_grade_letters($coursecontext, $showfeedback);
4914 // Delete course blocks in any all child contexts,
4915 // they may depend on modules so delete them first.
4916 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4917 foreach ($childcontexts as $childcontext) {
4918 blocks_delete_all_for_context($childcontext->id);
4920 unset($childcontexts);
4921 blocks_delete_all_for_context($coursecontext->id);
4922 if ($showfeedback) {
4923 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4926 // Get the list of all modules that are properly installed.
4927 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
4929 // Delete every instance of every module,
4930 // this has to be done before deleting of course level stuff.
4931 $locations = core_component::get_plugin_list('mod');
4932 foreach ($locations as $modname => $moddir) {
4933 if ($modname === 'NEWMODULE') {
4934 continue;
4936 if (array_key_exists($modname, $allmodules)) {
4937 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
4938 FROM {".$modname."} m
4939 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
4940 WHERE m.course = :courseid";
4941 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
4942 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
4944 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
4945 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
4946 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
4948 if ($instances) {
4949 foreach ($instances as $cm) {
4950 if ($cm->id) {
4951 // Delete activity context questions and question categories.
4952 question_delete_activity($cm, $showfeedback);
4953 // Notify the competency subsystem.
4954 \core_competency\api::hook_course_module_deleted($cm);
4956 if (function_exists($moddelete)) {
4957 // This purges all module data in related tables, extra user prefs, settings, etc.
4958 $moddelete($cm->modinstance);
4959 } else {
4960 // NOTE: we should not allow installation of modules with missing delete support!
4961 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
4962 $DB->delete_records($modname, array('id' => $cm->modinstance));
4965 if ($cm->id) {
4966 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
4967 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4968 $DB->delete_records('course_modules', array('id' => $cm->id));
4972 if (function_exists($moddeletecourse)) {
4973 // Execute optional course cleanup callback. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
4974 debugging("Callback delete_course is deprecated. Function $moddeletecourse should be converted " .
4975 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER);
4976 $moddeletecourse($course, $showfeedback);
4978 if ($instances and $showfeedback) {
4979 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
4981 } else {
4982 // Ooops, this module is not properly installed, force-delete it in the next block.
4986 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
4988 // Delete completion defaults.
4989 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
4991 // Remove all data from availability and completion tables that is associated
4992 // with course-modules belonging to this course. Note this is done even if the
4993 // features are not enabled now, in case they were enabled previously.
4994 $DB->delete_records_select('course_modules_completion',
4995 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4996 array($courseid));
4998 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
4999 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5000 $allmodulesbyid = array_flip($allmodules);
5001 foreach ($cms as $cm) {
5002 if (array_key_exists($cm->module, $allmodulesbyid)) {
5003 try {
5004 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5005 } catch (Exception $e) {
5006 // Ignore weird or missing table problems.
5009 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5010 $DB->delete_records('course_modules', array('id' => $cm->id));
5013 if ($showfeedback) {
5014 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5017 // Cleanup the rest of plugins. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
5018 $cleanuplugintypes = array('report', 'coursereport', 'format');
5019 $callbacks = get_plugins_with_function('delete_course', 'lib.php');
5020 foreach ($cleanuplugintypes as $type) {
5021 if (!empty($callbacks[$type])) {
5022 foreach ($callbacks[$type] as $pluginfunction) {
5023 debugging("Callback delete_course is deprecated. Function $pluginfunction should be converted " .
5024 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER);
5025 $pluginfunction($course->id, $showfeedback);
5027 if ($showfeedback) {
5028 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5033 // Delete questions and question categories.
5034 question_delete_course($course, $showfeedback);
5035 if ($showfeedback) {
5036 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5039 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5040 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5041 foreach ($childcontexts as $childcontext) {
5042 $childcontext->delete();
5044 unset($childcontexts);
5046 // Remove all roles and enrolments by default.
5047 if (empty($options['keep_roles_and_enrolments'])) {
5048 // This hack is used in restore when deleting contents of existing course.
5049 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5050 enrol_course_delete($course);
5051 if ($showfeedback) {
5052 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5056 // Delete any groups, removing members and grouping/course links first.
5057 if (empty($options['keep_groups_and_groupings'])) {
5058 groups_delete_groupings($course->id, $showfeedback);
5059 groups_delete_groups($course->id, $showfeedback);
5062 // Filters be gone!
5063 filter_delete_all_for_context($coursecontext->id);
5065 // Notes, you shall not pass!
5066 note_delete_all($course->id);
5068 // Die comments!
5069 comment::delete_comments($coursecontext->id);
5071 // Ratings are history too.
5072 $delopt = new stdclass();
5073 $delopt->contextid = $coursecontext->id;
5074 $rm = new rating_manager();
5075 $rm->delete_ratings($delopt);
5077 // Delete course tags.
5078 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5080 // Notify the competency subsystem.
5081 \core_competency\api::hook_course_deleted($course);
5083 // Delete calendar events.
5084 $DB->delete_records('event', array('courseid' => $course->id));
5085 $fs->delete_area_files($coursecontext->id, 'calendar');
5087 // Delete all related records in other core tables that may have a courseid
5088 // This array stores the tables that need to be cleared, as
5089 // table_name => column_name that contains the course id.
5090 $tablestoclear = array(
5091 'backup_courses' => 'courseid', // Scheduled backup stuff.
5092 'user_lastaccess' => 'courseid', // User access info.
5094 foreach ($tablestoclear as $table => $col) {
5095 $DB->delete_records($table, array($col => $course->id));
5098 // Delete all course backup files.
5099 $fs->delete_area_files($coursecontext->id, 'backup');
5101 // Cleanup course record - remove links to deleted stuff.
5102 $oldcourse = new stdClass();
5103 $oldcourse->id = $course->id;
5104 $oldcourse->summary = '';
5105 $oldcourse->cacherev = 0;
5106 $oldcourse->legacyfiles = 0;
5107 if (!empty($options['keep_groups_and_groupings'])) {
5108 $oldcourse->defaultgroupingid = 0;
5110 $DB->update_record('course', $oldcourse);
5112 // Delete course sections.
5113 $DB->delete_records('course_sections', array('course' => $course->id));
5115 // Delete legacy, section and any other course files.
5116 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5118 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5119 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5120 // Easy, do not delete the context itself...
5121 $coursecontext->delete_content();
5122 } else {
5123 // Hack alert!!!!
5124 // We can not drop all context stuff because it would bork enrolments and roles,
5125 // there might be also files used by enrol plugins...
5128 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5129 // also some non-standard unsupported plugins may try to store something there.
5130 fulldelete($CFG->dataroot.'/'.$course->id);
5132 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5133 $cachemodinfo = cache::make('core', 'coursemodinfo');
5134 $cachemodinfo->delete($courseid);
5136 // Trigger a course content deleted event.
5137 $event = \core\event\course_content_deleted::create(array(
5138 'objectid' => $course->id,
5139 'context' => $coursecontext,
5140 'other' => array('shortname' => $course->shortname,
5141 'fullname' => $course->fullname,
5142 'options' => $options) // Passing this for legacy reasons.
5144 $event->add_record_snapshot('course', $course);
5145 $event->trigger();
5147 return true;
5151 * Change dates in module - used from course reset.
5153 * @param string $modname forum, assignment, etc
5154 * @param array $fields array of date fields from mod table
5155 * @param int $timeshift time difference
5156 * @param int $courseid
5157 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5158 * @return bool success
5160 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5161 global $CFG, $DB;
5162 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5164 $return = true;
5165 $params = array($timeshift, $courseid);
5166 foreach ($fields as $field) {
5167 $updatesql = "UPDATE {".$modname."}
5168 SET $field = $field + ?
5169 WHERE course=? AND $field<>0";
5170 if ($modid) {
5171 $updatesql .= ' AND id=?';
5172 $params[] = $modid;
5174 $return = $DB->execute($updatesql, $params) && $return;
5177 return $return;
5181 * This function will empty a course of user data.
5182 * It will retain the activities and the structure of the course.
5184 * @param object $data an object containing all the settings including courseid (without magic quotes)
5185 * @return array status array of array component, item, error
5187 function reset_course_userdata($data) {
5188 global $CFG, $DB;
5189 require_once($CFG->libdir.'/gradelib.php');
5190 require_once($CFG->libdir.'/completionlib.php');
5191 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5192 require_once($CFG->dirroot.'/group/lib.php');
5194 $data->courseid = $data->id;
5195 $context = context_course::instance($data->courseid);
5197 $eventparams = array(
5198 'context' => $context,
5199 'courseid' => $data->id,
5200 'other' => array(
5201 'reset_options' => (array) $data
5204 $event = \core\event\course_reset_started::create($eventparams);
5205 $event->trigger();
5207 // Calculate the time shift of dates.
5208 if (!empty($data->reset_start_date)) {
5209 // Time part of course startdate should be zero.
5210 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5211 } else {
5212 $data->timeshift = 0;
5215 // Result array: component, item, error.
5216 $status = array();
5218 // Start the resetting.
5219 $componentstr = get_string('general');
5221 // Move the course start time.
5222 if (!empty($data->reset_start_date) and $data->timeshift) {
5223 // Change course start data.
5224 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5225 // Update all course and group events - do not move activity events.
5226 $updatesql = "UPDATE {event}
5227 SET timestart = timestart + ?
5228 WHERE courseid=? AND instance=0";
5229 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5231 // Update any date activity restrictions.
5232 if ($CFG->enableavailability) {
5233 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5236 // Update completion expected dates.
5237 if ($CFG->enablecompletion) {
5238 $modinfo = get_fast_modinfo($data->courseid);
5239 $changed = false;
5240 foreach ($modinfo->get_cms() as $cm) {
5241 if ($cm->completion && !empty($cm->completionexpected)) {
5242 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5243 array('id' => $cm->id));
5244 $changed = true;
5248 // Clear course cache if changes made.
5249 if ($changed) {
5250 rebuild_course_cache($data->courseid, true);
5253 // Update course date completion criteria.
5254 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5257 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5260 if (!empty($data->reset_end_date)) {
5261 // If the user set a end date value respect it.
5262 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5263 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5264 // If there is a time shift apply it to the end date as well.
5265 $enddate = $data->reset_end_date_old + $data->timeshift;
5266 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5269 if (!empty($data->reset_events)) {
5270 $DB->delete_records('event', array('courseid' => $data->courseid));
5271 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5274 if (!empty($data->reset_notes)) {
5275 require_once($CFG->dirroot.'/notes/lib.php');
5276 note_delete_all($data->courseid);
5277 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5280 if (!empty($data->delete_blog_associations)) {
5281 require_once($CFG->dirroot.'/blog/lib.php');
5282 blog_remove_associations_for_course($data->courseid);
5283 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5286 if (!empty($data->reset_completion)) {
5287 // Delete course and activity completion information.
5288 $course = $DB->get_record('course', array('id' => $data->courseid));
5289 $cc = new completion_info($course);
5290 $cc->delete_all_completion_data();
5291 $status[] = array('component' => $componentstr,
5292 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5295 if (!empty($data->reset_competency_ratings)) {
5296 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5297 $status[] = array('component' => $componentstr,
5298 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5301 $componentstr = get_string('roles');
5303 if (!empty($data->reset_roles_overrides)) {
5304 $children = $context->get_child_contexts();
5305 foreach ($children as $child) {
5306 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5308 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5309 // Force refresh for logged in users.
5310 $context->mark_dirty();
5311 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5314 if (!empty($data->reset_roles_local)) {
5315 $children = $context->get_child_contexts();
5316 foreach ($children as $child) {
5317 role_unassign_all(array('contextid' => $child->id));
5319 // Force refresh for logged in users.
5320 $context->mark_dirty();
5321 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5324 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5325 $data->unenrolled = array();
5326 if (!empty($data->unenrol_users)) {
5327 $plugins = enrol_get_plugins(true);
5328 $instances = enrol_get_instances($data->courseid, true);
5329 foreach ($instances as $key => $instance) {
5330 if (!isset($plugins[$instance->enrol])) {
5331 unset($instances[$key]);
5332 continue;
5336 foreach ($data->unenrol_users as $withroleid) {
5337 if ($withroleid) {
5338 $sql = "SELECT ue.*
5339 FROM {user_enrolments} ue
5340 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5341 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5342 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5343 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5345 } else {
5346 // Without any role assigned at course context.
5347 $sql = "SELECT ue.*
5348 FROM {user_enrolments} ue
5349 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5350 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5351 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5352 WHERE ra.id IS null";
5353 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5356 $rs = $DB->get_recordset_sql($sql, $params);
5357 foreach ($rs as $ue) {
5358 if (!isset($instances[$ue->enrolid])) {
5359 continue;
5361 $instance = $instances[$ue->enrolid];
5362 $plugin = $plugins[$instance->enrol];
5363 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5364 continue;
5367 $plugin->unenrol_user($instance, $ue->userid);
5368 $data->unenrolled[$ue->userid] = $ue->userid;
5370 $rs->close();
5373 if (!empty($data->unenrolled)) {
5374 $status[] = array(
5375 'component' => $componentstr,
5376 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5377 'error' => false
5381 $componentstr = get_string('groups');
5383 // Remove all group members.
5384 if (!empty($data->reset_groups_members)) {
5385 groups_delete_group_members($data->courseid);
5386 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5389 // Remove all groups.
5390 if (!empty($data->reset_groups_remove)) {
5391 groups_delete_groups($data->courseid, false);
5392 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5395 // Remove all grouping members.
5396 if (!empty($data->reset_groupings_members)) {
5397 groups_delete_groupings_groups($data->courseid, false);
5398 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5401 // Remove all groupings.
5402 if (!empty($data->reset_groupings_remove)) {
5403 groups_delete_groupings($data->courseid, false);
5404 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5407 // Look in every instance of every module for data to delete.
5408 $unsupportedmods = array();
5409 if ($allmods = $DB->get_records('modules') ) {
5410 foreach ($allmods as $mod) {
5411 $modname = $mod->name;
5412 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5413 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5414 if (file_exists($modfile)) {
5415 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5416 continue; // Skip mods with no instances.
5418 include_once($modfile);
5419 if (function_exists($moddeleteuserdata)) {
5420 $modstatus = $moddeleteuserdata($data);
5421 if (is_array($modstatus)) {
5422 $status = array_merge($status, $modstatus);
5423 } else {
5424 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5426 } else {
5427 $unsupportedmods[] = $mod;
5429 } else {
5430 debugging('Missing lib.php in '.$modname.' module!');
5432 // Update calendar events for all modules.
5433 course_module_bulk_update_calendar_events($modname, $data->courseid);
5437 // Mention unsupported mods.
5438 if (!empty($unsupportedmods)) {
5439 foreach ($unsupportedmods as $mod) {
5440 $status[] = array(
5441 'component' => get_string('modulenameplural', $mod->name),
5442 'item' => '',
5443 'error' => get_string('resetnotimplemented')
5448 $componentstr = get_string('gradebook', 'grades');
5449 // Reset gradebook,.
5450 if (!empty($data->reset_gradebook_items)) {
5451 remove_course_grades($data->courseid, false);
5452 grade_grab_course_grades($data->courseid);
5453 grade_regrade_final_grades($data->courseid);
5454 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5456 } else if (!empty($data->reset_gradebook_grades)) {
5457 grade_course_reset($data->courseid);
5458 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5460 // Reset comments.
5461 if (!empty($data->reset_comments)) {
5462 require_once($CFG->dirroot.'/comment/lib.php');
5463 comment::reset_course_page_comments($context);
5466 $event = \core\event\course_reset_ended::create($eventparams);
5467 $event->trigger();
5469 return $status;
5473 * Generate an email processing address.
5475 * @param int $modid
5476 * @param string $modargs
5477 * @return string Returns email processing address
5479 function generate_email_processing_address($modid, $modargs) {
5480 global $CFG;
5482 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5483 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5489 * @todo Finish documenting this function
5491 * @param string $modargs
5492 * @param string $body Currently unused
5494 function moodle_process_email($modargs, $body) {
5495 global $DB;
5497 // The first char should be an unencoded letter. We'll take this as an action.
5498 switch ($modargs{0}) {
5499 case 'B': { // Bounce.
5500 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5501 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5502 // Check the half md5 of their email.
5503 $md5check = substr(md5($user->email), 0, 16);
5504 if ($md5check == substr($modargs, -16)) {
5505 set_bounce_count($user);
5507 // Else maybe they've already changed it?
5510 break;
5511 // Maybe more later?
5515 // CORRESPONDENCE.
5518 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5520 * @param string $action 'get', 'buffer', 'close' or 'flush'
5521 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5523 function get_mailer($action='get') {
5524 global $CFG;
5526 /** @var moodle_phpmailer $mailer */
5527 static $mailer = null;
5528 static $counter = 0;
5530 if (!isset($CFG->smtpmaxbulk)) {
5531 $CFG->smtpmaxbulk = 1;
5534 if ($action == 'get') {
5535 $prevkeepalive = false;
5537 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5538 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5539 $counter++;
5540 // Reset the mailer.
5541 $mailer->Priority = 3;
5542 $mailer->CharSet = 'UTF-8'; // Our default.
5543 $mailer->ContentType = "text/plain";
5544 $mailer->Encoding = "8bit";
5545 $mailer->From = "root@localhost";
5546 $mailer->FromName = "Root User";
5547 $mailer->Sender = "";
5548 $mailer->Subject = "";
5549 $mailer->Body = "";
5550 $mailer->AltBody = "";
5551 $mailer->ConfirmReadingTo = "";
5553 $mailer->clearAllRecipients();
5554 $mailer->clearReplyTos();
5555 $mailer->clearAttachments();
5556 $mailer->clearCustomHeaders();
5557 return $mailer;
5560 $prevkeepalive = $mailer->SMTPKeepAlive;
5561 get_mailer('flush');
5564 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5565 $mailer = new moodle_phpmailer();
5567 $counter = 1;
5569 if ($CFG->smtphosts == 'qmail') {
5570 // Use Qmail system.
5571 $mailer->isQmail();
5573 } else if (empty($CFG->smtphosts)) {
5574 // Use PHP mail() = sendmail.
5575 $mailer->isMail();
5577 } else {
5578 // Use SMTP directly.
5579 $mailer->isSMTP();
5580 if (!empty($CFG->debugsmtp)) {
5581 $mailer->SMTPDebug = true;
5583 // Specify main and backup servers.
5584 $mailer->Host = $CFG->smtphosts;
5585 // Specify secure connection protocol.
5586 $mailer->SMTPSecure = $CFG->smtpsecure;
5587 // Use previous keepalive.
5588 $mailer->SMTPKeepAlive = $prevkeepalive;
5590 if ($CFG->smtpuser) {
5591 // Use SMTP authentication.
5592 $mailer->SMTPAuth = true;
5593 $mailer->Username = $CFG->smtpuser;
5594 $mailer->Password = $CFG->smtppass;
5598 return $mailer;
5601 $nothing = null;
5603 // Keep smtp session open after sending.
5604 if ($action == 'buffer') {
5605 if (!empty($CFG->smtpmaxbulk)) {
5606 get_mailer('flush');
5607 $m = get_mailer();
5608 if ($m->Mailer == 'smtp') {
5609 $m->SMTPKeepAlive = true;
5612 return $nothing;
5615 // Close smtp session, but continue buffering.
5616 if ($action == 'flush') {
5617 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5618 if (!empty($mailer->SMTPDebug)) {
5619 echo '<pre>'."\n";
5621 $mailer->SmtpClose();
5622 if (!empty($mailer->SMTPDebug)) {
5623 echo '</pre>';
5626 return $nothing;
5629 // Close smtp session, do not buffer anymore.
5630 if ($action == 'close') {
5631 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5632 get_mailer('flush');
5633 $mailer->SMTPKeepAlive = false;
5635 $mailer = null; // Better force new instance.
5636 return $nothing;
5641 * A helper function to test for email diversion
5643 * @param string $email
5644 * @return bool Returns true if the email should be diverted
5646 function email_should_be_diverted($email) {
5647 global $CFG;
5649 if (empty($CFG->divertallemailsto)) {
5650 return false;
5653 if (empty($CFG->divertallemailsexcept)) {
5654 return true;
5657 $patterns = array_map('trim', explode(',', $CFG->divertallemailsexcept));
5658 foreach ($patterns as $pattern) {
5659 if (preg_match("/$pattern/", $email)) {
5660 return false;
5664 return true;
5668 * Generate a unique email Message-ID using the moodle domain and install path
5670 * @param string $localpart An optional unique message id prefix.
5671 * @return string The formatted ID ready for appending to the email headers.
5673 function generate_email_messageid($localpart = null) {
5674 global $CFG;
5676 $urlinfo = parse_url($CFG->wwwroot);
5677 $base = '@' . $urlinfo['host'];
5679 // If multiple moodles are on the same domain we want to tell them
5680 // apart so we add the install path to the local part. This means
5681 // that the id local part should never contain a / character so
5682 // we can correctly parse the id to reassemble the wwwroot.
5683 if (isset($urlinfo['path'])) {
5684 $base = $urlinfo['path'] . $base;
5687 if (empty($localpart)) {
5688 $localpart = uniqid('', true);
5691 // Because we may have an option /installpath suffix to the local part
5692 // of the id we need to escape any / chars which are in the $localpart.
5693 $localpart = str_replace('/', '%2F', $localpart);
5695 return '<' . $localpart . $base . '>';
5699 * Send an email to a specified user
5701 * @param stdClass $user A {@link $USER} object
5702 * @param stdClass $from A {@link $USER} object
5703 * @param string $subject plain text subject line of the email
5704 * @param string $messagetext plain text version of the message
5705 * @param string $messagehtml complete html version of the message (optional)
5706 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5707 * @param string $attachname the name of the file (extension indicates MIME)
5708 * @param bool $usetrueaddress determines whether $from email address should
5709 * be sent out. Will be overruled by user profile setting for maildisplay
5710 * @param string $replyto Email address to reply to
5711 * @param string $replytoname Name of reply to recipient
5712 * @param int $wordwrapwidth custom word wrap width, default 79
5713 * @return bool Returns true if mail was sent OK and false if there was an error.
5715 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5716 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5718 global $CFG, $PAGE, $SITE;
5720 if (empty($user) or empty($user->id)) {
5721 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5722 return false;
5725 if (empty($user->email)) {
5726 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5727 return false;
5730 if (!empty($user->deleted)) {
5731 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5732 return false;
5735 if (defined('BEHAT_SITE_RUNNING')) {
5736 // Fake email sending in behat.
5737 return true;
5740 if (!empty($CFG->noemailever)) {
5741 // Hidden setting for development sites, set in config.php if needed.
5742 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5743 return true;
5746 if (email_should_be_diverted($user->email)) {
5747 $subject = "[DIVERTED {$user->email}] $subject";
5748 $user = clone($user);
5749 $user->email = $CFG->divertallemailsto;
5752 // Skip mail to suspended users.
5753 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5754 return true;
5757 if (!validate_email($user->email)) {
5758 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5759 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5760 return false;
5763 if (over_bounce_threshold($user)) {
5764 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5765 return false;
5768 // TLD .invalid is specifically reserved for invalid domain names.
5769 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5770 if (substr($user->email, -8) == '.invalid') {
5771 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5772 return true; // This is not an error.
5775 // If the user is a remote mnet user, parse the email text for URL to the
5776 // wwwroot and modify the url to direct the user's browser to login at their
5777 // home site (identity provider - idp) before hitting the link itself.
5778 if (is_mnet_remote_user($user)) {
5779 require_once($CFG->dirroot.'/mnet/lib.php');
5781 $jumpurl = mnet_get_idp_jump_url($user);
5782 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5784 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5785 $callback,
5786 $messagetext);
5787 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5788 $callback,
5789 $messagehtml);
5791 $mail = get_mailer();
5793 if (!empty($mail->SMTPDebug)) {
5794 echo '<pre>' . "\n";
5797 $temprecipients = array();
5798 $tempreplyto = array();
5800 // Make sure that we fall back onto some reasonable no-reply address.
5801 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
5802 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
5804 if (!validate_email($noreplyaddress)) {
5805 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
5806 $noreplyaddress = $noreplyaddressdefault;
5809 // Make up an email address for handling bounces.
5810 if (!empty($CFG->handlebounces)) {
5811 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5812 $mail->Sender = generate_email_processing_address(0, $modargs);
5813 } else {
5814 $mail->Sender = $noreplyaddress;
5817 // Make sure that the explicit replyto is valid, fall back to the implicit one.
5818 if (!empty($replyto) && !validate_email($replyto)) {
5819 debugging('email_to_user: Invalid replyto-email '.s($replyto));
5820 $replyto = $noreplyaddress;
5823 if (is_string($from)) { // So we can pass whatever we want if there is need.
5824 $mail->From = $noreplyaddress;
5825 $mail->FromName = $from;
5826 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
5827 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
5828 // in a course with the sender.
5829 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
5830 if (!validate_email($from->email)) {
5831 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
5832 // Better not to use $noreplyaddress in this case.
5833 return false;
5835 $mail->From = $from->email;
5836 $fromdetails = new stdClass();
5837 $fromdetails->name = fullname($from);
5838 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5839 $fromdetails->siteshortname = format_string($SITE->shortname);
5840 $fromstring = $fromdetails->name;
5841 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
5842 $fromstring = get_string('emailvia', 'core', $fromdetails);
5844 $mail->FromName = $fromstring;
5845 if (empty($replyto)) {
5846 $tempreplyto[] = array($from->email, fullname($from));
5848 } else {
5849 $mail->From = $noreplyaddress;
5850 $fromdetails = new stdClass();
5851 $fromdetails->name = fullname($from);
5852 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5853 $fromdetails->siteshortname = format_string($SITE->shortname);
5854 $fromstring = $fromdetails->name;
5855 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
5856 $fromstring = get_string('emailvia', 'core', $fromdetails);
5858 $mail->FromName = $fromstring;
5859 if (empty($replyto)) {
5860 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
5864 if (!empty($replyto)) {
5865 $tempreplyto[] = array($replyto, $replytoname);
5868 $temprecipients[] = array($user->email, fullname($user));
5870 // Set word wrap.
5871 $mail->WordWrap = $wordwrapwidth;
5873 if (!empty($from->customheaders)) {
5874 // Add custom headers.
5875 if (is_array($from->customheaders)) {
5876 foreach ($from->customheaders as $customheader) {
5877 $mail->addCustomHeader($customheader);
5879 } else {
5880 $mail->addCustomHeader($from->customheaders);
5884 // If the X-PHP-Originating-Script email header is on then also add an additional
5885 // header with details of where exactly in moodle the email was triggered from,
5886 // either a call to message_send() or to email_to_user().
5887 if (ini_get('mail.add_x_header')) {
5889 $stack = debug_backtrace(false);
5890 $origin = $stack[0];
5892 foreach ($stack as $depth => $call) {
5893 if ($call['function'] == 'message_send') {
5894 $origin = $call;
5898 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
5899 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
5900 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
5903 if (!empty($from->priority)) {
5904 $mail->Priority = $from->priority;
5907 $renderer = $PAGE->get_renderer('core');
5908 $context = array(
5909 'sitefullname' => $SITE->fullname,
5910 'siteshortname' => $SITE->shortname,
5911 'sitewwwroot' => $CFG->wwwroot,
5912 'subject' => $subject,
5913 'to' => $user->email,
5914 'toname' => fullname($user),
5915 'from' => $mail->From,
5916 'fromname' => $mail->FromName,
5918 if (!empty($tempreplyto[0])) {
5919 $context['replyto'] = $tempreplyto[0][0];
5920 $context['replytoname'] = $tempreplyto[0][1];
5922 if ($user->id > 0) {
5923 $context['touserid'] = $user->id;
5924 $context['tousername'] = $user->username;
5927 if (!empty($user->mailformat) && $user->mailformat == 1) {
5928 // Only process html templates if the user preferences allow html email.
5930 if ($messagehtml) {
5931 // If html has been given then pass it through the template.
5932 $context['body'] = $messagehtml;
5933 $messagehtml = $renderer->render_from_template('core/email_html', $context);
5935 } else {
5936 // If no html has been given, BUT there is an html wrapping template then
5937 // auto convert the text to html and then wrap it.
5938 $autohtml = trim(text_to_html($messagetext));
5939 $context['body'] = $autohtml;
5940 $temphtml = $renderer->render_from_template('core/email_html', $context);
5941 if ($autohtml != $temphtml) {
5942 $messagehtml = $temphtml;
5947 $context['body'] = $messagetext;
5948 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
5949 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
5950 $messagetext = $renderer->render_from_template('core/email_text', $context);
5952 // Autogenerate a MessageID if it's missing.
5953 if (empty($mail->MessageID)) {
5954 $mail->MessageID = generate_email_messageid();
5957 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5958 // Don't ever send HTML to users who don't want it.
5959 $mail->isHTML(true);
5960 $mail->Encoding = 'quoted-printable';
5961 $mail->Body = $messagehtml;
5962 $mail->AltBody = "\n$messagetext\n";
5963 } else {
5964 $mail->IsHTML(false);
5965 $mail->Body = "\n$messagetext\n";
5968 if ($attachment && $attachname) {
5969 if (preg_match( "~\\.\\.~" , $attachment )) {
5970 // Security check for ".." in dir path.
5971 $supportuser = core_user::get_support_user();
5972 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5973 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5974 } else {
5975 require_once($CFG->libdir.'/filelib.php');
5976 $mimetype = mimeinfo('type', $attachname);
5978 $attachmentpath = $attachment;
5980 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5981 $attachpath = str_replace('\\', '/', $attachmentpath);
5982 // Make sure both variables are normalised before comparing.
5983 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
5985 // If the attachment is a full path to a file in the tempdir, use it as is,
5986 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5987 if (strpos($attachpath, $temppath) !== 0) {
5988 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
5991 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5995 // Check if the email should be sent in an other charset then the default UTF-8.
5996 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5998 // Use the defined site mail charset or eventually the one preferred by the recipient.
5999 $charset = $CFG->sitemailcharset;
6000 if (!empty($CFG->allowusermailcharset)) {
6001 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6002 $charset = $useremailcharset;
6006 // Convert all the necessary strings if the charset is supported.
6007 $charsets = get_list_of_charsets();
6008 unset($charsets['UTF-8']);
6009 if (in_array($charset, $charsets)) {
6010 $mail->CharSet = $charset;
6011 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6012 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6013 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6014 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6016 foreach ($temprecipients as $key => $values) {
6017 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6019 foreach ($tempreplyto as $key => $values) {
6020 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6025 foreach ($temprecipients as $values) {
6026 $mail->addAddress($values[0], $values[1]);
6028 foreach ($tempreplyto as $values) {
6029 $mail->addReplyTo($values[0], $values[1]);
6032 if ($mail->send()) {
6033 set_send_count($user);
6034 if (!empty($mail->SMTPDebug)) {
6035 echo '</pre>';
6037 return true;
6038 } else {
6039 // Trigger event for failing to send email.
6040 $event = \core\event\email_failed::create(array(
6041 'context' => context_system::instance(),
6042 'userid' => $from->id,
6043 'relateduserid' => $user->id,
6044 'other' => array(
6045 'subject' => $subject,
6046 'message' => $messagetext,
6047 'errorinfo' => $mail->ErrorInfo
6050 $event->trigger();
6051 if (CLI_SCRIPT) {
6052 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6054 if (!empty($mail->SMTPDebug)) {
6055 echo '</pre>';
6057 return false;
6062 * Check to see if a user's real email address should be used for the "From" field.
6064 * @param object $from The user object for the user we are sending the email from.
6065 * @param object $user The user object that we are sending the email to.
6066 * @param array $unused No longer used.
6067 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6069 function can_send_from_real_email_address($from, $user, $unused = null) {
6070 global $CFG;
6071 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6072 return false;
6074 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6075 // Email is in the list of allowed domains for sending email,
6076 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6077 // in a course with the sender.
6078 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6079 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6080 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6081 && enrol_get_shared_courses($user, $from, false, true)))) {
6082 return true;
6084 return false;
6088 * Generate a signoff for emails based on support settings
6090 * @return string
6092 function generate_email_signoff() {
6093 global $CFG;
6095 $signoff = "\n";
6096 if (!empty($CFG->supportname)) {
6097 $signoff .= $CFG->supportname."\n";
6099 if (!empty($CFG->supportemail)) {
6100 $signoff .= $CFG->supportemail."\n";
6102 if (!empty($CFG->supportpage)) {
6103 $signoff .= $CFG->supportpage."\n";
6105 return $signoff;
6109 * Sets specified user's password and send the new password to the user via email.
6111 * @param stdClass $user A {@link $USER} object
6112 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6113 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6115 function setnew_password_and_mail($user, $fasthash = false) {
6116 global $CFG, $DB;
6118 // We try to send the mail in language the user understands,
6119 // unfortunately the filter_string() does not support alternative langs yet
6120 // so multilang will not work properly for site->fullname.
6121 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6123 $site = get_site();
6125 $supportuser = core_user::get_support_user();
6127 $newpassword = generate_password();
6129 update_internal_user_password($user, $newpassword, $fasthash);
6131 $a = new stdClass();
6132 $a->firstname = fullname($user, true);
6133 $a->sitename = format_string($site->fullname);
6134 $a->username = $user->username;
6135 $a->newpassword = $newpassword;
6136 $a->link = $CFG->wwwroot .'/login/';
6137 $a->signoff = generate_email_signoff();
6139 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6141 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6143 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6144 return email_to_user($user, $supportuser, $subject, $message);
6149 * Resets specified user's password and send the new password to the user via email.
6151 * @param stdClass $user A {@link $USER} object
6152 * @return bool Returns true if mail was sent OK and false if there was an error.
6154 function reset_password_and_mail($user) {
6155 global $CFG;
6157 $site = get_site();
6158 $supportuser = core_user::get_support_user();
6160 $userauth = get_auth_plugin($user->auth);
6161 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6162 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6163 return false;
6166 $newpassword = generate_password();
6168 if (!$userauth->user_update_password($user, $newpassword)) {
6169 print_error("cannotsetpassword");
6172 $a = new stdClass();
6173 $a->firstname = $user->firstname;
6174 $a->lastname = $user->lastname;
6175 $a->sitename = format_string($site->fullname);
6176 $a->username = $user->username;
6177 $a->newpassword = $newpassword;
6178 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
6179 $a->signoff = generate_email_signoff();
6181 $message = get_string('newpasswordtext', '', $a);
6183 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6185 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6187 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6188 return email_to_user($user, $supportuser, $subject, $message);
6192 * Send email to specified user with confirmation text and activation link.
6194 * @param stdClass $user A {@link $USER} object
6195 * @param string $confirmationurl user confirmation URL
6196 * @return bool Returns true if mail was sent OK and false if there was an error.
6198 function send_confirmation_email($user, $confirmationurl = null) {
6199 global $CFG;
6201 $site = get_site();
6202 $supportuser = core_user::get_support_user();
6204 $data = new stdClass();
6205 $data->firstname = fullname($user);
6206 $data->sitename = format_string($site->fullname);
6207 $data->admin = generate_email_signoff();
6209 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6211 if (empty($confirmationurl)) {
6212 $confirmationurl = '/login/confirm.php';
6215 $confirmationurl = new moodle_url($confirmationurl);
6216 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6217 $confirmationurl->remove_params('data');
6218 $confirmationpath = $confirmationurl->out(false);
6220 // We need to custom encode the username to include trailing dots in the link.
6221 // Because of this custom encoding we can't use moodle_url directly.
6222 // Determine if a query string is present in the confirmation url.
6223 $hasquerystring = strpos($confirmationpath, '?') !== false;
6224 // Perform normal url encoding of the username first.
6225 $username = urlencode($user->username);
6226 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6227 $username = str_replace('.', '%2E', $username);
6229 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6231 $message = get_string('emailconfirmation', '', $data);
6232 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6234 $user->mailformat = 1; // Always send HTML version as well.
6236 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6237 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6241 * Sends a password change confirmation email.
6243 * @param stdClass $user A {@link $USER} object
6244 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6245 * @return bool Returns true if mail was sent OK and false if there was an error.
6247 function send_password_change_confirmation_email($user, $resetrecord) {
6248 global $CFG;
6250 $site = get_site();
6251 $supportuser = core_user::get_support_user();
6252 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6254 $data = new stdClass();
6255 $data->firstname = $user->firstname;
6256 $data->lastname = $user->lastname;
6257 $data->username = $user->username;
6258 $data->sitename = format_string($site->fullname);
6259 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6260 $data->admin = generate_email_signoff();
6261 $data->resetminutes = $pwresetmins;
6263 $message = get_string('emailresetconfirmation', '', $data);
6264 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6266 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6267 return email_to_user($user, $supportuser, $subject, $message);
6272 * Sends an email containinginformation on how to change your password.
6274 * @param stdClass $user A {@link $USER} object
6275 * @return bool Returns true if mail was sent OK and false if there was an error.
6277 function send_password_change_info($user) {
6278 global $CFG;
6280 $site = get_site();
6281 $supportuser = core_user::get_support_user();
6282 $systemcontext = context_system::instance();
6284 $data = new stdClass();
6285 $data->firstname = $user->firstname;
6286 $data->lastname = $user->lastname;
6287 $data->sitename = format_string($site->fullname);
6288 $data->admin = generate_email_signoff();
6290 $userauth = get_auth_plugin($user->auth);
6292 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6293 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6294 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6295 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6296 return email_to_user($user, $supportuser, $subject, $message);
6299 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6300 // We have some external url for password changing.
6301 $data->link .= $userauth->change_password_url();
6303 } else {
6304 // No way to change password, sorry.
6305 $data->link = '';
6308 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6309 $message = get_string('emailpasswordchangeinfo', '', $data);
6310 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6311 } else {
6312 $message = get_string('emailpasswordchangeinfofail', '', $data);
6313 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6316 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6317 return email_to_user($user, $supportuser, $subject, $message);
6322 * Check that an email is allowed. It returns an error message if there was a problem.
6324 * @param string $email Content of email
6325 * @return string|false
6327 function email_is_not_allowed($email) {
6328 global $CFG;
6330 if (!empty($CFG->allowemailaddresses)) {
6331 $allowed = explode(' ', $CFG->allowemailaddresses);
6332 foreach ($allowed as $allowedpattern) {
6333 $allowedpattern = trim($allowedpattern);
6334 if (!$allowedpattern) {
6335 continue;
6337 if (strpos($allowedpattern, '.') === 0) {
6338 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6339 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6340 return false;
6343 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6344 return false;
6347 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6349 } else if (!empty($CFG->denyemailaddresses)) {
6350 $denied = explode(' ', $CFG->denyemailaddresses);
6351 foreach ($denied as $deniedpattern) {
6352 $deniedpattern = trim($deniedpattern);
6353 if (!$deniedpattern) {
6354 continue;
6356 if (strpos($deniedpattern, '.') === 0) {
6357 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6358 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6359 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6362 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6363 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6368 return false;
6371 // FILE HANDLING.
6374 * Returns local file storage instance
6376 * @return file_storage
6378 function get_file_storage($reset = false) {
6379 global $CFG;
6381 static $fs = null;
6383 if ($reset) {
6384 $fs = null;
6385 return;
6388 if ($fs) {
6389 return $fs;
6392 require_once("$CFG->libdir/filelib.php");
6394 $fs = new file_storage();
6396 return $fs;
6400 * Returns local file storage instance
6402 * @return file_browser
6404 function get_file_browser() {
6405 global $CFG;
6407 static $fb = null;
6409 if ($fb) {
6410 return $fb;
6413 require_once("$CFG->libdir/filelib.php");
6415 $fb = new file_browser();
6417 return $fb;
6421 * Returns file packer
6423 * @param string $mimetype default application/zip
6424 * @return file_packer
6426 function get_file_packer($mimetype='application/zip') {
6427 global $CFG;
6429 static $fp = array();
6431 if (isset($fp[$mimetype])) {
6432 return $fp[$mimetype];
6435 switch ($mimetype) {
6436 case 'application/zip':
6437 case 'application/vnd.moodle.profiling':
6438 $classname = 'zip_packer';
6439 break;
6441 case 'application/x-gzip' :
6442 $classname = 'tgz_packer';
6443 break;
6445 case 'application/vnd.moodle.backup':
6446 $classname = 'mbz_packer';
6447 break;
6449 default:
6450 return false;
6453 require_once("$CFG->libdir/filestorage/$classname.php");
6454 $fp[$mimetype] = new $classname();
6456 return $fp[$mimetype];
6460 * Returns current name of file on disk if it exists.
6462 * @param string $newfile File to be verified
6463 * @return string Current name of file on disk if true
6465 function valid_uploaded_file($newfile) {
6466 if (empty($newfile)) {
6467 return '';
6469 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6470 return $newfile['tmp_name'];
6471 } else {
6472 return '';
6477 * Returns the maximum size for uploading files.
6479 * There are seven possible upload limits:
6480 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6481 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6482 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6483 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6484 * 5. by the Moodle admin in $CFG->maxbytes
6485 * 6. by the teacher in the current course $course->maxbytes
6486 * 7. by the teacher for the current module, eg $assignment->maxbytes
6488 * These last two are passed to this function as arguments (in bytes).
6489 * Anything defined as 0 is ignored.
6490 * The smallest of all the non-zero numbers is returned.
6492 * @todo Finish documenting this function
6494 * @param int $sitebytes Set maximum size
6495 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6496 * @param int $modulebytes Current module ->maxbytes (in bytes)
6497 * @param bool $unused This parameter has been deprecated and is not used any more.
6498 * @return int The maximum size for uploading files.
6500 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6502 if (! $filesize = ini_get('upload_max_filesize')) {
6503 $filesize = '5M';
6505 $minimumsize = get_real_size($filesize);
6507 if ($postsize = ini_get('post_max_size')) {
6508 $postsize = get_real_size($postsize);
6509 if ($postsize < $minimumsize) {
6510 $minimumsize = $postsize;
6514 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6515 $minimumsize = $sitebytes;
6518 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6519 $minimumsize = $coursebytes;
6522 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6523 $minimumsize = $modulebytes;
6526 return $minimumsize;
6530 * Returns the maximum size for uploading files for the current user
6532 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6534 * @param context $context The context in which to check user capabilities
6535 * @param int $sitebytes Set maximum size
6536 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6537 * @param int $modulebytes Current module ->maxbytes (in bytes)
6538 * @param stdClass $user The user
6539 * @param bool $unused This parameter has been deprecated and is not used any more.
6540 * @return int The maximum size for uploading files.
6542 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6543 $unused = false) {
6544 global $USER;
6546 if (empty($user)) {
6547 $user = $USER;
6550 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6551 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6554 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6558 * Returns an array of possible sizes in local language
6560 * Related to {@link get_max_upload_file_size()} - this function returns an
6561 * array of possible sizes in an array, translated to the
6562 * local language.
6564 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6566 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6567 * with the value set to 0. This option will be the first in the list.
6569 * @uses SORT_NUMERIC
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 int|array $custombytes custom upload size/s which will be added to list,
6574 * Only value/s smaller then maxsize will be added to list.
6575 * @return array
6577 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6578 global $CFG;
6580 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6581 return array();
6584 if ($sitebytes == 0) {
6585 // Will get the minimum of upload_max_filesize or post_max_size.
6586 $sitebytes = get_max_upload_file_size();
6589 $filesize = array();
6590 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6591 5242880, 10485760, 20971520, 52428800, 104857600,
6592 262144000, 524288000, 786432000, 1073741824,
6593 2147483648, 4294967296, 8589934592);
6595 // If custombytes is given and is valid then add it to the list.
6596 if (is_number($custombytes) and $custombytes > 0) {
6597 $custombytes = (int)$custombytes;
6598 if (!in_array($custombytes, $sizelist)) {
6599 $sizelist[] = $custombytes;
6601 } else if (is_array($custombytes)) {
6602 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6605 // Allow maxbytes to be selected if it falls outside the above boundaries.
6606 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6607 // Note: get_real_size() is used in order to prevent problems with invalid values.
6608 $sizelist[] = get_real_size($CFG->maxbytes);
6611 foreach ($sizelist as $sizebytes) {
6612 if ($sizebytes < $maxsize && $sizebytes > 0) {
6613 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6617 $limitlevel = '';
6618 $displaysize = '';
6619 if ($modulebytes &&
6620 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6621 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6622 $limitlevel = get_string('activity', 'core');
6623 $displaysize = display_size($modulebytes);
6624 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6626 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6627 $limitlevel = get_string('course', 'core');
6628 $displaysize = display_size($coursebytes);
6629 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6631 } else if ($sitebytes) {
6632 $limitlevel = get_string('site', 'core');
6633 $displaysize = display_size($sitebytes);
6634 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6637 krsort($filesize, SORT_NUMERIC);
6638 if ($limitlevel) {
6639 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6640 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6643 return $filesize;
6647 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6649 * If excludefiles is defined, then that file/directory is ignored
6650 * If getdirs is true, then (sub)directories are included in the output
6651 * If getfiles is true, then files are included in the output
6652 * (at least one of these must be true!)
6654 * @todo Finish documenting this function. Add examples of $excludefile usage.
6656 * @param string $rootdir A given root directory to start from
6657 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6658 * @param bool $descend If true then subdirectories are recursed as well
6659 * @param bool $getdirs If true then (sub)directories are included in the output
6660 * @param bool $getfiles If true then files are included in the output
6661 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6663 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6665 $dirs = array();
6667 if (!$getdirs and !$getfiles) { // Nothing to show.
6668 return $dirs;
6671 if (!is_dir($rootdir)) { // Must be a directory.
6672 return $dirs;
6675 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6676 return $dirs;
6679 if (!is_array($excludefiles)) {
6680 $excludefiles = array($excludefiles);
6683 while (false !== ($file = readdir($dir))) {
6684 $firstchar = substr($file, 0, 1);
6685 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6686 continue;
6688 $fullfile = $rootdir .'/'. $file;
6689 if (filetype($fullfile) == 'dir') {
6690 if ($getdirs) {
6691 $dirs[] = $file;
6693 if ($descend) {
6694 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6695 foreach ($subdirs as $subdir) {
6696 $dirs[] = $file .'/'. $subdir;
6699 } else if ($getfiles) {
6700 $dirs[] = $file;
6703 closedir($dir);
6705 asort($dirs);
6707 return $dirs;
6712 * Adds up all the files in a directory and works out the size.
6714 * @param string $rootdir The directory to start from
6715 * @param string $excludefile A file to exclude when summing directory size
6716 * @return int The summed size of all files and subfiles within the root directory
6718 function get_directory_size($rootdir, $excludefile='') {
6719 global $CFG;
6721 // Do it this way if we can, it's much faster.
6722 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6723 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6724 $output = null;
6725 $return = null;
6726 exec($command, $output, $return);
6727 if (is_array($output)) {
6728 // We told it to return k.
6729 return get_real_size(intval($output[0]).'k');
6733 if (!is_dir($rootdir)) {
6734 // Must be a directory.
6735 return 0;
6738 if (!$dir = @opendir($rootdir)) {
6739 // Can't open it for some reason.
6740 return 0;
6743 $size = 0;
6745 while (false !== ($file = readdir($dir))) {
6746 $firstchar = substr($file, 0, 1);
6747 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6748 continue;
6750 $fullfile = $rootdir .'/'. $file;
6751 if (filetype($fullfile) == 'dir') {
6752 $size += get_directory_size($fullfile, $excludefile);
6753 } else {
6754 $size += filesize($fullfile);
6757 closedir($dir);
6759 return $size;
6763 * Converts bytes into display form
6765 * @static string $gb Localized string for size in gigabytes
6766 * @static string $mb Localized string for size in megabytes
6767 * @static string $kb Localized string for size in kilobytes
6768 * @static string $b Localized string for size in bytes
6769 * @param int $size The size to convert to human readable form
6770 * @return string
6772 function display_size($size) {
6774 static $gb, $mb, $kb, $b;
6776 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6777 return get_string('unlimited');
6780 if (empty($gb)) {
6781 $gb = get_string('sizegb');
6782 $mb = get_string('sizemb');
6783 $kb = get_string('sizekb');
6784 $b = get_string('sizeb');
6787 if ($size >= 1073741824) {
6788 $size = round($size / 1073741824 * 10) / 10 . $gb;
6789 } else if ($size >= 1048576) {
6790 $size = round($size / 1048576 * 10) / 10 . $mb;
6791 } else if ($size >= 1024) {
6792 $size = round($size / 1024 * 10) / 10 . $kb;
6793 } else {
6794 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6796 return $size;
6800 * Cleans a given filename by removing suspicious or troublesome characters
6802 * @see clean_param()
6803 * @param string $string file name
6804 * @return string cleaned file name
6806 function clean_filename($string) {
6807 return clean_param($string, PARAM_FILE);
6811 // STRING TRANSLATION.
6814 * Returns the code for the current language
6816 * @category string
6817 * @return string
6819 function current_language() {
6820 global $CFG, $USER, $SESSION, $COURSE;
6822 if (!empty($SESSION->forcelang)) {
6823 // Allows overriding course-forced language (useful for admins to check
6824 // issues in courses whose language they don't understand).
6825 // Also used by some code to temporarily get language-related information in a
6826 // specific language (see force_current_language()).
6827 $return = $SESSION->forcelang;
6829 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6830 // Course language can override all other settings for this page.
6831 $return = $COURSE->lang;
6833 } else if (!empty($SESSION->lang)) {
6834 // Session language can override other settings.
6835 $return = $SESSION->lang;
6837 } else if (!empty($USER->lang)) {
6838 $return = $USER->lang;
6840 } else if (isset($CFG->lang)) {
6841 $return = $CFG->lang;
6843 } else {
6844 $return = 'en';
6847 // Just in case this slipped in from somewhere by accident.
6848 $return = str_replace('_utf8', '', $return);
6850 return $return;
6854 * Returns parent language of current active language if defined
6856 * @category string
6857 * @param string $lang null means current language
6858 * @return string
6860 function get_parent_language($lang=null) {
6862 // Let's hack around the current language.
6863 if (!empty($lang)) {
6864 $oldforcelang = force_current_language($lang);
6867 $parentlang = get_string('parentlanguage', 'langconfig');
6868 if ($parentlang === 'en') {
6869 $parentlang = '';
6872 // Let's hack around the current language.
6873 if (!empty($lang)) {
6874 force_current_language($oldforcelang);
6877 return $parentlang;
6881 * Force the current language to get strings and dates localised in the given language.
6883 * After calling this function, all strings will be provided in the given language
6884 * until this function is called again, or equivalent code is run.
6886 * @param string $language
6887 * @return string previous $SESSION->forcelang value
6889 function force_current_language($language) {
6890 global $SESSION;
6891 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6892 if ($language !== $sessionforcelang) {
6893 // Seting forcelang to null or an empty string disables it's effect.
6894 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6895 $SESSION->forcelang = $language;
6896 moodle_setlocale();
6899 return $sessionforcelang;
6903 * Returns current string_manager instance.
6905 * The param $forcereload is needed for CLI installer only where the string_manager instance
6906 * must be replaced during the install.php script life time.
6908 * @category string
6909 * @param bool $forcereload shall the singleton be released and new instance created instead?
6910 * @return core_string_manager
6912 function get_string_manager($forcereload=false) {
6913 global $CFG;
6915 static $singleton = null;
6917 if ($forcereload) {
6918 $singleton = null;
6920 if ($singleton === null) {
6921 if (empty($CFG->early_install_lang)) {
6923 if (empty($CFG->langlist)) {
6924 $translist = array();
6925 } else {
6926 $translist = explode(',', $CFG->langlist);
6929 if (!empty($CFG->config_php_settings['customstringmanager'])) {
6930 $classname = $CFG->config_php_settings['customstringmanager'];
6932 if (class_exists($classname)) {
6933 $implements = class_implements($classname);
6935 if (isset($implements['core_string_manager'])) {
6936 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist);
6937 return $singleton;
6939 } else {
6940 debugging('Unable to instantiate custom string manager: class '.$classname.
6941 ' does not implement the core_string_manager interface.');
6944 } else {
6945 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
6949 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6951 } else {
6952 $singleton = new core_string_manager_install();
6956 return $singleton;
6960 * Returns a localized string.
6962 * Returns the translated string specified by $identifier as
6963 * for $module. Uses the same format files as STphp.
6964 * $a is an object, string or number that can be used
6965 * within translation strings
6967 * eg 'hello {$a->firstname} {$a->lastname}'
6968 * or 'hello {$a}'
6970 * If you would like to directly echo the localized string use
6971 * the function {@link print_string()}
6973 * Example usage of this function involves finding the string you would
6974 * like a local equivalent of and using its identifier and module information
6975 * to retrieve it.<br/>
6976 * If you open moodle/lang/en/moodle.php and look near line 278
6977 * you will find a string to prompt a user for their word for 'course'
6978 * <code>
6979 * $string['course'] = 'Course';
6980 * </code>
6981 * So if you want to display the string 'Course'
6982 * in any language that supports it on your site
6983 * you just need to use the identifier 'course'
6984 * <code>
6985 * $mystring = '<strong>'. get_string('course') .'</strong>';
6986 * or
6987 * </code>
6988 * If the string you want is in another file you'd take a slightly
6989 * different approach. Looking in moodle/lang/en/calendar.php you find
6990 * around line 75:
6991 * <code>
6992 * $string['typecourse'] = 'Course event';
6993 * </code>
6994 * If you want to display the string "Course event" in any language
6995 * supported you would use the identifier 'typecourse' and the module 'calendar'
6996 * (because it is in the file calendar.php):
6997 * <code>
6998 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6999 * </code>
7001 * As a last resort, should the identifier fail to map to a string
7002 * the returned string will be [[ $identifier ]]
7004 * In Moodle 2.3 there is a new argument to this function $lazyload.
7005 * Setting $lazyload to true causes get_string to return a lang_string object
7006 * rather than the string itself. The fetching of the string is then put off until
7007 * the string object is first used. The object can be used by calling it's out
7008 * method or by casting the object to a string, either directly e.g.
7009 * (string)$stringobject
7010 * or indirectly by using the string within another string or echoing it out e.g.
7011 * echo $stringobject
7012 * return "<p>{$stringobject}</p>";
7013 * It is worth noting that using $lazyload and attempting to use the string as an
7014 * array key will cause a fatal error as objects cannot be used as array keys.
7015 * But you should never do that anyway!
7016 * For more information {@link lang_string}
7018 * @category string
7019 * @param string $identifier The key identifier for the localized string
7020 * @param string $component The module where the key identifier is stored,
7021 * usually expressed as the filename in the language pack without the
7022 * .php on the end but can also be written as mod/forum or grade/export/xls.
7023 * If none is specified then moodle.php is used.
7024 * @param string|object|array $a An object, string or number that can be used
7025 * within translation strings
7026 * @param bool $lazyload If set to true a string object is returned instead of
7027 * the string itself. The string then isn't calculated until it is first used.
7028 * @return string The localized string.
7029 * @throws coding_exception
7031 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7032 global $CFG;
7034 // If the lazy load argument has been supplied return a lang_string object
7035 // instead.
7036 // We need to make sure it is true (and a bool) as you will see below there
7037 // used to be a forth argument at one point.
7038 if ($lazyload === true) {
7039 return new lang_string($identifier, $component, $a);
7042 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7043 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7046 // There is now a forth argument again, this time it is a boolean however so
7047 // we can still check for the old extralocations parameter.
7048 if (!is_bool($lazyload) && !empty($lazyload)) {
7049 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7052 if (strpos($component, '/') !== false) {
7053 debugging('The module name you passed to get_string is the deprecated format ' .
7054 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7055 $componentpath = explode('/', $component);
7057 switch ($componentpath[0]) {
7058 case 'mod':
7059 $component = $componentpath[1];
7060 break;
7061 case 'blocks':
7062 case 'block':
7063 $component = 'block_'.$componentpath[1];
7064 break;
7065 case 'enrol':
7066 $component = 'enrol_'.$componentpath[1];
7067 break;
7068 case 'format':
7069 $component = 'format_'.$componentpath[1];
7070 break;
7071 case 'grade':
7072 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7073 break;
7077 $result = get_string_manager()->get_string($identifier, $component, $a);
7079 // Debugging feature lets you display string identifier and component.
7080 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7081 $result .= ' {' . $identifier . '/' . $component . '}';
7083 return $result;
7087 * Converts an array of strings to their localized value.
7089 * @param array $array An array of strings
7090 * @param string $component The language module that these strings can be found in.
7091 * @return stdClass translated strings.
7093 function get_strings($array, $component = '') {
7094 $string = new stdClass;
7095 foreach ($array as $item) {
7096 $string->$item = get_string($item, $component);
7098 return $string;
7102 * Prints out a translated string.
7104 * Prints out a translated string using the return value from the {@link get_string()} function.
7106 * Example usage of this function when the string is in the moodle.php file:<br/>
7107 * <code>
7108 * echo '<strong>';
7109 * print_string('course');
7110 * echo '</strong>';
7111 * </code>
7113 * Example usage of this function when the string is not in the moodle.php file:<br/>
7114 * <code>
7115 * echo '<h1>';
7116 * print_string('typecourse', 'calendar');
7117 * echo '</h1>';
7118 * </code>
7120 * @category string
7121 * @param string $identifier The key identifier for the localized string
7122 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7123 * @param string|object|array $a An object, string or number that can be used within translation strings
7125 function print_string($identifier, $component = '', $a = null) {
7126 echo get_string($identifier, $component, $a);
7130 * Returns a list of charset codes
7132 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7133 * (checking that such charset is supported by the texlib library!)
7135 * @return array And associative array with contents in the form of charset => charset
7137 function get_list_of_charsets() {
7139 $charsets = array(
7140 'EUC-JP' => 'EUC-JP',
7141 'ISO-2022-JP'=> 'ISO-2022-JP',
7142 'ISO-8859-1' => 'ISO-8859-1',
7143 'SHIFT-JIS' => 'SHIFT-JIS',
7144 'GB2312' => 'GB2312',
7145 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7146 'UTF-8' => 'UTF-8');
7148 asort($charsets);
7150 return $charsets;
7154 * Returns a list of valid and compatible themes
7156 * @return array
7158 function get_list_of_themes() {
7159 global $CFG;
7161 $themes = array();
7163 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7164 $themelist = explode(',', $CFG->themelist);
7165 } else {
7166 $themelist = array_keys(core_component::get_plugin_list("theme"));
7169 foreach ($themelist as $key => $themename) {
7170 $theme = theme_config::load($themename);
7171 $themes[$themename] = $theme;
7174 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7176 return $themes;
7180 * Factory function for emoticon_manager
7182 * @return emoticon_manager singleton
7184 function get_emoticon_manager() {
7185 static $singleton = null;
7187 if (is_null($singleton)) {
7188 $singleton = new emoticon_manager();
7191 return $singleton;
7195 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7197 * Whenever this manager mentiones 'emoticon object', the following data
7198 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7199 * altidentifier and altcomponent
7201 * @see admin_setting_emoticons
7203 * @copyright 2010 David Mudrak
7204 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7206 class emoticon_manager {
7209 * Returns the currently enabled emoticons
7211 * @return array of emoticon objects
7213 public function get_emoticons() {
7214 global $CFG;
7216 if (empty($CFG->emoticons)) {
7217 return array();
7220 $emoticons = $this->decode_stored_config($CFG->emoticons);
7222 if (!is_array($emoticons)) {
7223 // Something is wrong with the format of stored setting.
7224 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7225 return array();
7228 return $emoticons;
7232 * Converts emoticon object into renderable pix_emoticon object
7234 * @param stdClass $emoticon emoticon object
7235 * @param array $attributes explicit HTML attributes to set
7236 * @return pix_emoticon
7238 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7239 $stringmanager = get_string_manager();
7240 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7241 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7242 } else {
7243 $alt = s($emoticon->text);
7245 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7249 * Encodes the array of emoticon objects into a string storable in config table
7251 * @see self::decode_stored_config()
7252 * @param array $emoticons array of emtocion objects
7253 * @return string
7255 public function encode_stored_config(array $emoticons) {
7256 return json_encode($emoticons);
7260 * Decodes the string into an array of emoticon objects
7262 * @see self::encode_stored_config()
7263 * @param string $encoded
7264 * @return string|null
7266 public function decode_stored_config($encoded) {
7267 $decoded = json_decode($encoded);
7268 if (!is_array($decoded)) {
7269 return null;
7271 return $decoded;
7275 * Returns default set of emoticons supported by Moodle
7277 * @return array of sdtClasses
7279 public function default_emoticons() {
7280 return array(
7281 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7282 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7283 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7284 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7285 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7286 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7287 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7288 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7289 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7290 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7291 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7292 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7293 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7294 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7295 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7296 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7297 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7298 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7299 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7300 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7301 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7302 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7303 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7304 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7305 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7306 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7307 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7308 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7309 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7310 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7315 * Helper method preparing the stdClass with the emoticon properties
7317 * @param string|array $text or array of strings
7318 * @param string $imagename to be used by {@link pix_emoticon}
7319 * @param string $altidentifier alternative string identifier, null for no alt
7320 * @param string $altcomponent where the alternative string is defined
7321 * @param string $imagecomponent to be used by {@link pix_emoticon}
7322 * @return stdClass
7324 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7325 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7326 return (object)array(
7327 'text' => $text,
7328 'imagename' => $imagename,
7329 'imagecomponent' => $imagecomponent,
7330 'altidentifier' => $altidentifier,
7331 'altcomponent' => $altcomponent,
7336 // ENCRYPTION.
7339 * rc4encrypt
7341 * @param string $data Data to encrypt.
7342 * @return string The now encrypted data.
7344 function rc4encrypt($data) {
7345 return endecrypt(get_site_identifier(), $data, '');
7349 * rc4decrypt
7351 * @param string $data Data to decrypt.
7352 * @return string The now decrypted data.
7354 function rc4decrypt($data) {
7355 return endecrypt(get_site_identifier(), $data, 'de');
7359 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7361 * @todo Finish documenting this function
7363 * @param string $pwd The password to use when encrypting or decrypting
7364 * @param string $data The data to be decrypted/encrypted
7365 * @param string $case Either 'de' for decrypt or '' for encrypt
7366 * @return string
7368 function endecrypt ($pwd, $data, $case) {
7370 if ($case == 'de') {
7371 $data = urldecode($data);
7374 $key[] = '';
7375 $box[] = '';
7376 $pwdlength = strlen($pwd);
7378 for ($i = 0; $i <= 255; $i++) {
7379 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7380 $box[$i] = $i;
7383 $x = 0;
7385 for ($i = 0; $i <= 255; $i++) {
7386 $x = ($x + $box[$i] + $key[$i]) % 256;
7387 $tempswap = $box[$i];
7388 $box[$i] = $box[$x];
7389 $box[$x] = $tempswap;
7392 $cipher = '';
7394 $a = 0;
7395 $j = 0;
7397 for ($i = 0; $i < strlen($data); $i++) {
7398 $a = ($a + 1) % 256;
7399 $j = ($j + $box[$a]) % 256;
7400 $temp = $box[$a];
7401 $box[$a] = $box[$j];
7402 $box[$j] = $temp;
7403 $k = $box[(($box[$a] + $box[$j]) % 256)];
7404 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7405 $cipher .= chr($cipherby);
7408 if ($case == 'de') {
7409 $cipher = urldecode(urlencode($cipher));
7410 } else {
7411 $cipher = urlencode($cipher);
7414 return $cipher;
7417 // ENVIRONMENT CHECKING.
7420 * This method validates a plug name. It is much faster than calling clean_param.
7422 * @param string $name a string that might be a plugin name.
7423 * @return bool if this string is a valid plugin name.
7425 function is_valid_plugin_name($name) {
7426 // This does not work for 'mod', bad luck, use any other type.
7427 return core_component::is_valid_plugin_name('tool', $name);
7431 * Get a list of all the plugins of a given type that define a certain API function
7432 * in a certain file. The plugin component names and function names are returned.
7434 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7435 * @param string $function the part of the name of the function after the
7436 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7437 * names like report_courselist_hook.
7438 * @param string $file the name of file within the plugin that defines the
7439 * function. Defaults to lib.php.
7440 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7441 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7443 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7444 global $CFG;
7446 // We don't include here as all plugin types files would be included.
7447 $plugins = get_plugins_with_function($function, $file, false);
7449 if (empty($plugins[$plugintype])) {
7450 return array();
7453 $allplugins = core_component::get_plugin_list($plugintype);
7455 // Reformat the array and include the files.
7456 $pluginfunctions = array();
7457 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7459 // Check that it has not been removed and the file is still available.
7460 if (!empty($allplugins[$pluginname])) {
7462 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7463 if (file_exists($filepath)) {
7464 include_once($filepath);
7465 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7470 return $pluginfunctions;
7474 * Get a list of all the plugins that define a certain API function in a certain file.
7476 * @param string $function the part of the name of the function after the
7477 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7478 * names like report_courselist_hook.
7479 * @param string $file the name of file within the plugin that defines the
7480 * function. Defaults to lib.php.
7481 * @param bool $include Whether to include the files that contain the functions or not.
7482 * @return array with [plugintype][plugin] = functionname
7484 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7485 global $CFG;
7487 if (during_initial_install() || isset($CFG->upgraderunning)) {
7488 // API functions _must not_ be called during an installation or upgrade.
7489 return [];
7492 $cache = \cache::make('core', 'plugin_functions');
7494 // Including both although I doubt that we will find two functions definitions with the same name.
7495 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7496 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7497 $pluginfunctions = $cache->get($key);
7499 if ($pluginfunctions !== false) {
7501 // Checking that the files are still available.
7502 foreach ($pluginfunctions as $plugintype => $plugins) {
7504 $allplugins = \core_component::get_plugin_list($plugintype);
7505 foreach ($plugins as $plugin => $fullpath) {
7507 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7508 if (empty($allplugins[$plugin])) {
7509 unset($pluginfunctions[$plugintype][$plugin]);
7510 continue;
7513 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7514 if ($include && $fileexists) {
7515 // Include the files if it was requested.
7516 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7517 } else if (!$fileexists) {
7518 // If the file is not available any more it should not be returned.
7519 unset($pluginfunctions[$plugintype][$plugin]);
7523 return $pluginfunctions;
7526 $pluginfunctions = array();
7528 // To fill the cached. Also, everything should continue working with cache disabled.
7529 $plugintypes = \core_component::get_plugin_types();
7530 foreach ($plugintypes as $plugintype => $unused) {
7532 // We need to include files here.
7533 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7534 foreach ($pluginswithfile as $plugin => $notused) {
7536 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7538 $pluginfunction = false;
7539 if (function_exists($fullfunction)) {
7540 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7541 $pluginfunction = $fullfunction;
7543 } else if ($plugintype === 'mod') {
7544 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7545 $shortfunction = $plugin . '_' . $function;
7546 if (function_exists($shortfunction)) {
7547 $pluginfunction = $shortfunction;
7551 if ($pluginfunction) {
7552 if (empty($pluginfunctions[$plugintype])) {
7553 $pluginfunctions[$plugintype] = array();
7555 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7560 $cache->set($key, $pluginfunctions);
7562 return $pluginfunctions;
7567 * Lists plugin-like directories within specified directory
7569 * This function was originally used for standard Moodle plugins, please use
7570 * new core_component::get_plugin_list() now.
7572 * This function is used for general directory listing and backwards compatility.
7574 * @param string $directory relative directory from root
7575 * @param string $exclude dir name to exclude from the list (defaults to none)
7576 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7577 * @return array Sorted array of directory names found under the requested parameters
7579 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7580 global $CFG;
7582 $plugins = array();
7584 if (empty($basedir)) {
7585 $basedir = $CFG->dirroot .'/'. $directory;
7587 } else {
7588 $basedir = $basedir .'/'. $directory;
7591 if ($CFG->debugdeveloper and empty($exclude)) {
7592 // Make sure devs do not use this to list normal plugins,
7593 // this is intended for general directories that are not plugins!
7595 $subtypes = core_component::get_plugin_types();
7596 if (in_array($basedir, $subtypes)) {
7597 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7599 unset($subtypes);
7602 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7603 if (!$dirhandle = opendir($basedir)) {
7604 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7605 return array();
7607 while (false !== ($dir = readdir($dirhandle))) {
7608 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7609 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7610 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7611 continue;
7613 if (filetype($basedir .'/'. $dir) != 'dir') {
7614 continue;
7616 $plugins[] = $dir;
7618 closedir($dirhandle);
7620 if ($plugins) {
7621 asort($plugins);
7623 return $plugins;
7627 * Invoke plugin's callback functions
7629 * @param string $type plugin type e.g. 'mod'
7630 * @param string $name plugin name
7631 * @param string $feature feature name
7632 * @param string $action feature's action
7633 * @param array $params parameters of callback function, should be an array
7634 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7635 * @return mixed
7637 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7639 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7640 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7644 * Invoke component's callback functions
7646 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7647 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7648 * @param array $params parameters of callback function
7649 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7650 * @return mixed
7652 function component_callback($component, $function, array $params = array(), $default = null) {
7654 $functionname = component_callback_exists($component, $function);
7656 if ($functionname) {
7657 // Function exists, so just return function result.
7658 $ret = call_user_func_array($functionname, $params);
7659 if (is_null($ret)) {
7660 return $default;
7661 } else {
7662 return $ret;
7665 return $default;
7669 * Determine if a component callback exists and return the function name to call. Note that this
7670 * function will include the required library files so that the functioname returned can be
7671 * called directly.
7673 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7674 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7675 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7676 * @throws coding_exception if invalid component specfied
7678 function component_callback_exists($component, $function) {
7679 global $CFG; // This is needed for the inclusions.
7681 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7682 if (empty($cleancomponent)) {
7683 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7685 $component = $cleancomponent;
7687 list($type, $name) = core_component::normalize_component($component);
7688 $component = $type . '_' . $name;
7690 $oldfunction = $name.'_'.$function;
7691 $function = $component.'_'.$function;
7693 $dir = core_component::get_component_directory($component);
7694 if (empty($dir)) {
7695 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7698 // Load library and look for function.
7699 if (file_exists($dir.'/lib.php')) {
7700 require_once($dir.'/lib.php');
7703 if (!function_exists($function) and function_exists($oldfunction)) {
7704 if ($type !== 'mod' and $type !== 'core') {
7705 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7707 $function = $oldfunction;
7710 if (function_exists($function)) {
7711 return $function;
7713 return false;
7717 * Checks whether a plugin supports a specified feature.
7719 * @param string $type Plugin type e.g. 'mod'
7720 * @param string $name Plugin name e.g. 'forum'
7721 * @param string $feature Feature code (FEATURE_xx constant)
7722 * @param mixed $default default value if feature support unknown
7723 * @return mixed Feature result (false if not supported, null if feature is unknown,
7724 * otherwise usually true but may have other feature-specific value such as array)
7725 * @throws coding_exception
7727 function plugin_supports($type, $name, $feature, $default = null) {
7728 global $CFG;
7730 if ($type === 'mod' and $name === 'NEWMODULE') {
7731 // Somebody forgot to rename the module template.
7732 return false;
7735 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7736 if (empty($component)) {
7737 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7740 $function = null;
7742 if ($type === 'mod') {
7743 // We need this special case because we support subplugins in modules,
7744 // otherwise it would end up in infinite loop.
7745 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7746 include_once("$CFG->dirroot/mod/$name/lib.php");
7747 $function = $component.'_supports';
7748 if (!function_exists($function)) {
7749 // Legacy non-frankenstyle function name.
7750 $function = $name.'_supports';
7754 } else {
7755 if (!$path = core_component::get_plugin_directory($type, $name)) {
7756 // Non existent plugin type.
7757 return false;
7759 if (file_exists("$path/lib.php")) {
7760 include_once("$path/lib.php");
7761 $function = $component.'_supports';
7765 if ($function and function_exists($function)) {
7766 $supports = $function($feature);
7767 if (is_null($supports)) {
7768 // Plugin does not know - use default.
7769 return $default;
7770 } else {
7771 return $supports;
7775 // Plugin does not care, so use default.
7776 return $default;
7780 * Returns true if the current version of PHP is greater that the specified one.
7782 * @todo Check PHP version being required here is it too low?
7784 * @param string $version The version of php being tested.
7785 * @return bool
7787 function check_php_version($version='5.2.4') {
7788 return (version_compare(phpversion(), $version) >= 0);
7792 * Determine if moodle installation requires update.
7794 * Checks version numbers of main code and all plugins to see
7795 * if there are any mismatches.
7797 * @return bool
7799 function moodle_needs_upgrading() {
7800 global $CFG;
7802 if (empty($CFG->version)) {
7803 return true;
7806 // There is no need to purge plugininfo caches here because
7807 // these caches are not used during upgrade and they are purged after
7808 // every upgrade.
7810 if (empty($CFG->allversionshash)) {
7811 return true;
7814 $hash = core_component::get_all_versions_hash();
7816 return ($hash !== $CFG->allversionshash);
7820 * Returns the major version of this site
7822 * Moodle version numbers consist of three numbers separated by a dot, for
7823 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7824 * called major version. This function extracts the major version from either
7825 * $CFG->release (default) or eventually from the $release variable defined in
7826 * the main version.php.
7828 * @param bool $fromdisk should the version if source code files be used
7829 * @return string|false the major version like '2.3', false if could not be determined
7831 function moodle_major_version($fromdisk = false) {
7832 global $CFG;
7834 if ($fromdisk) {
7835 $release = null;
7836 require($CFG->dirroot.'/version.php');
7837 if (empty($release)) {
7838 return false;
7841 } else {
7842 if (empty($CFG->release)) {
7843 return false;
7845 $release = $CFG->release;
7848 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7849 return $matches[0];
7850 } else {
7851 return false;
7855 // MISCELLANEOUS.
7858 * Sets the system locale
7860 * @category string
7861 * @param string $locale Can be used to force a locale
7863 function moodle_setlocale($locale='') {
7864 global $CFG;
7866 static $currentlocale = ''; // Last locale caching.
7868 $oldlocale = $currentlocale;
7870 // Fetch the correct locale based on ostype.
7871 if ($CFG->ostype == 'WINDOWS') {
7872 $stringtofetch = 'localewin';
7873 } else {
7874 $stringtofetch = 'locale';
7877 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7878 if (!empty($locale)) {
7879 $currentlocale = $locale;
7880 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7881 $currentlocale = $CFG->locale;
7882 } else {
7883 $currentlocale = get_string($stringtofetch, 'langconfig');
7886 // Do nothing if locale already set up.
7887 if ($oldlocale == $currentlocale) {
7888 return;
7891 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7892 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7893 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7895 // Get current values.
7896 $monetary= setlocale (LC_MONETARY, 0);
7897 $numeric = setlocale (LC_NUMERIC, 0);
7898 $ctype = setlocale (LC_CTYPE, 0);
7899 if ($CFG->ostype != 'WINDOWS') {
7900 $messages= setlocale (LC_MESSAGES, 0);
7902 // Set locale to all.
7903 $result = setlocale (LC_ALL, $currentlocale);
7904 // If setting of locale fails try the other utf8 or utf-8 variant,
7905 // some operating systems support both (Debian), others just one (OSX).
7906 if ($result === false) {
7907 if (stripos($currentlocale, '.UTF-8') !== false) {
7908 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7909 setlocale (LC_ALL, $newlocale);
7910 } else if (stripos($currentlocale, '.UTF8') !== false) {
7911 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7912 setlocale (LC_ALL, $newlocale);
7915 // Set old values.
7916 setlocale (LC_MONETARY, $monetary);
7917 setlocale (LC_NUMERIC, $numeric);
7918 if ($CFG->ostype != 'WINDOWS') {
7919 setlocale (LC_MESSAGES, $messages);
7921 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7922 // To workaround a well-known PHP problem with Turkish letter Ii.
7923 setlocale (LC_CTYPE, $ctype);
7928 * Count words in a string.
7930 * Words are defined as things between whitespace.
7932 * @category string
7933 * @param string $string The text to be searched for words.
7934 * @return int The count of words in the specified string
7936 function count_words($string) {
7937 $string = strip_tags($string);
7938 // Decode HTML entities.
7939 $string = html_entity_decode($string);
7940 // Replace underscores (which are classed as word characters) with spaces.
7941 $string = preg_replace('/_/u', ' ', $string);
7942 // Remove any characters that shouldn't be treated as word boundaries.
7943 $string = preg_replace('/[\'"’-]/u', '', $string);
7944 // Remove dots and commas from within numbers only.
7945 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7947 return count(preg_split('/\w\b/u', $string)) - 1;
7951 * Count letters in a string.
7953 * Letters are defined as chars not in tags and different from whitespace.
7955 * @category string
7956 * @param string $string The text to be searched for letters.
7957 * @return int The count of letters in the specified text.
7959 function count_letters($string) {
7960 $string = strip_tags($string); // Tags are out now.
7961 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7963 return core_text::strlen($string);
7967 * Generate and return a random string of the specified length.
7969 * @param int $length The length of the string to be created.
7970 * @return string
7972 function random_string($length=15) {
7973 $randombytes = random_bytes_emulate($length);
7974 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7975 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7976 $pool .= '0123456789';
7977 $poollen = strlen($pool);
7978 $string = '';
7979 for ($i = 0; $i < $length; $i++) {
7980 $rand = ord($randombytes[$i]);
7981 $string .= substr($pool, ($rand%($poollen)), 1);
7983 return $string;
7987 * Generate a complex random string (useful for md5 salts)
7989 * This function is based on the above {@link random_string()} however it uses a
7990 * larger pool of characters and generates a string between 24 and 32 characters
7992 * @param int $length Optional if set generates a string to exactly this length
7993 * @return string
7995 function complex_random_string($length=null) {
7996 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7997 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7998 $poollen = strlen($pool);
7999 if ($length===null) {
8000 $length = floor(rand(24, 32));
8002 $randombytes = random_bytes_emulate($length);
8003 $string = '';
8004 for ($i = 0; $i < $length; $i++) {
8005 $rand = ord($randombytes[$i]);
8006 $string .= $pool[($rand%$poollen)];
8008 return $string;
8012 * Try to generates cryptographically secure pseudo-random bytes.
8014 * Note this is achieved by fallbacking between:
8015 * - PHP 7 random_bytes().
8016 * - OpenSSL openssl_random_pseudo_bytes().
8017 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8019 * @param int $length requested length in bytes
8020 * @return string binary data
8022 function random_bytes_emulate($length) {
8023 global $CFG;
8024 if ($length <= 0) {
8025 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8026 return '';
8028 if (function_exists('random_bytes')) {
8029 // Use PHP 7 goodness.
8030 $hash = @random_bytes($length);
8031 if ($hash !== false) {
8032 return $hash;
8035 if (function_exists('openssl_random_pseudo_bytes')) {
8036 // If you have the openssl extension enabled.
8037 $hash = openssl_random_pseudo_bytes($length);
8038 if ($hash !== false) {
8039 return $hash;
8043 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8044 $staticdata = serialize($CFG) . serialize($_SERVER);
8045 $hash = '';
8046 do {
8047 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8048 } while (strlen($hash) < $length);
8050 return substr($hash, 0, $length);
8054 * Given some text (which may contain HTML) and an ideal length,
8055 * this function truncates the text neatly on a word boundary if possible
8057 * @category string
8058 * @param string $text text to be shortened
8059 * @param int $ideal ideal string length
8060 * @param boolean $exact if false, $text will not be cut mid-word
8061 * @param string $ending The string to append if the passed string is truncated
8062 * @return string $truncate shortened string
8064 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8065 // If the plain text is shorter than the maximum length, return the whole text.
8066 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8067 return $text;
8070 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8071 // and only tag in its 'line'.
8072 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8074 $totallength = core_text::strlen($ending);
8075 $truncate = '';
8077 // This array stores information about open and close tags and their position
8078 // in the truncated string. Each item in the array is an object with fields
8079 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8080 // (byte position in truncated text).
8081 $tagdetails = array();
8083 foreach ($lines as $linematchings) {
8084 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8085 if (!empty($linematchings[1])) {
8086 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8087 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8088 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8089 // Record closing tag.
8090 $tagdetails[] = (object) array(
8091 'open' => false,
8092 'tag' => core_text::strtolower($tagmatchings[1]),
8093 'pos' => core_text::strlen($truncate),
8096 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8097 // Record opening tag.
8098 $tagdetails[] = (object) array(
8099 'open' => true,
8100 'tag' => core_text::strtolower($tagmatchings[1]),
8101 'pos' => core_text::strlen($truncate),
8103 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8104 $tagdetails[] = (object) array(
8105 'open' => true,
8106 'tag' => core_text::strtolower('if'),
8107 'pos' => core_text::strlen($truncate),
8109 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8110 $tagdetails[] = (object) array(
8111 'open' => false,
8112 'tag' => core_text::strtolower('if'),
8113 'pos' => core_text::strlen($truncate),
8117 // Add html-tag to $truncate'd text.
8118 $truncate .= $linematchings[1];
8121 // Calculate the length of the plain text part of the line; handle entities as one character.
8122 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8123 if ($totallength + $contentlength > $ideal) {
8124 // The number of characters which are left.
8125 $left = $ideal - $totallength;
8126 $entitieslength = 0;
8127 // Search for html entities.
8128 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)) {
8129 // Calculate the real length of all entities in the legal range.
8130 foreach ($entities[0] as $entity) {
8131 if ($entity[1]+1-$entitieslength <= $left) {
8132 $left--;
8133 $entitieslength += core_text::strlen($entity[0]);
8134 } else {
8135 // No more characters left.
8136 break;
8140 $breakpos = $left + $entitieslength;
8142 // If the words shouldn't be cut in the middle...
8143 if (!$exact) {
8144 // Search the last occurence of a space.
8145 for (; $breakpos > 0; $breakpos--) {
8146 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8147 if ($char === '.' or $char === ' ') {
8148 $breakpos += 1;
8149 break;
8150 } else if (strlen($char) > 2) {
8151 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8152 $breakpos += 1;
8153 break;
8158 if ($breakpos == 0) {
8159 // This deals with the test_shorten_text_no_spaces case.
8160 $breakpos = $left + $entitieslength;
8161 } else if ($breakpos > $left + $entitieslength) {
8162 // This deals with the previous for loop breaking on the first char.
8163 $breakpos = $left + $entitieslength;
8166 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8167 // Maximum length is reached, so get off the loop.
8168 break;
8169 } else {
8170 $truncate .= $linematchings[2];
8171 $totallength += $contentlength;
8174 // If the maximum length is reached, get off the loop.
8175 if ($totallength >= $ideal) {
8176 break;
8180 // Add the defined ending to the text.
8181 $truncate .= $ending;
8183 // Now calculate the list of open html tags based on the truncate position.
8184 $opentags = array();
8185 foreach ($tagdetails as $taginfo) {
8186 if ($taginfo->open) {
8187 // Add tag to the beginning of $opentags list.
8188 array_unshift($opentags, $taginfo->tag);
8189 } else {
8190 // Can have multiple exact same open tags, close the last one.
8191 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8192 if ($pos !== false) {
8193 unset($opentags[$pos]);
8198 // Close all unclosed html-tags.
8199 foreach ($opentags as $tag) {
8200 if ($tag === 'if') {
8201 $truncate .= '<!--<![endif]-->';
8202 } else {
8203 $truncate .= '</' . $tag . '>';
8207 return $truncate;
8212 * Given dates in seconds, how many weeks is the date from startdate
8213 * The first week is 1, the second 2 etc ...
8215 * @param int $startdate Timestamp for the start date
8216 * @param int $thedate Timestamp for the end date
8217 * @return string
8219 function getweek ($startdate, $thedate) {
8220 if ($thedate < $startdate) {
8221 return 0;
8224 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8228 * Returns a randomly generated password of length $maxlen. inspired by
8230 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8231 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8233 * @param int $maxlen The maximum size of the password being generated.
8234 * @return string
8236 function generate_password($maxlen=10) {
8237 global $CFG;
8239 if (empty($CFG->passwordpolicy)) {
8240 $fillers = PASSWORD_DIGITS;
8241 $wordlist = file($CFG->wordlist);
8242 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8243 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8244 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8245 $password = $word1 . $filler1 . $word2;
8246 } else {
8247 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8248 $digits = $CFG->minpassworddigits;
8249 $lower = $CFG->minpasswordlower;
8250 $upper = $CFG->minpasswordupper;
8251 $nonalphanum = $CFG->minpasswordnonalphanum;
8252 $total = $lower + $upper + $digits + $nonalphanum;
8253 // Var minlength should be the greater one of the two ( $minlen and $total ).
8254 $minlen = $minlen < $total ? $total : $minlen;
8255 // Var maxlen can never be smaller than minlen.
8256 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8257 $additional = $maxlen - $total;
8259 // Make sure we have enough characters to fulfill
8260 // complexity requirements.
8261 $passworddigits = PASSWORD_DIGITS;
8262 while ($digits > strlen($passworddigits)) {
8263 $passworddigits .= PASSWORD_DIGITS;
8265 $passwordlower = PASSWORD_LOWER;
8266 while ($lower > strlen($passwordlower)) {
8267 $passwordlower .= PASSWORD_LOWER;
8269 $passwordupper = PASSWORD_UPPER;
8270 while ($upper > strlen($passwordupper)) {
8271 $passwordupper .= PASSWORD_UPPER;
8273 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8274 while ($nonalphanum > strlen($passwordnonalphanum)) {
8275 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8278 // Now mix and shuffle it all.
8279 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8280 substr(str_shuffle ($passwordupper), 0, $upper) .
8281 substr(str_shuffle ($passworddigits), 0, $digits) .
8282 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8283 substr(str_shuffle ($passwordlower .
8284 $passwordupper .
8285 $passworddigits .
8286 $passwordnonalphanum), 0 , $additional));
8289 return substr ($password, 0, $maxlen);
8293 * Given a float, prints it nicely.
8294 * Localized floats must not be used in calculations!
8296 * The stripzeros feature is intended for making numbers look nicer in small
8297 * areas where it is not necessary to indicate the degree of accuracy by showing
8298 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8299 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8301 * @param float $float The float to print
8302 * @param int $decimalpoints The number of decimal places to print.
8303 * @param bool $localized use localized decimal separator
8304 * @param bool $stripzeros If true, removes final zeros after decimal point
8305 * @return string locale float
8307 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8308 if (is_null($float)) {
8309 return '';
8311 if ($localized) {
8312 $separator = get_string('decsep', 'langconfig');
8313 } else {
8314 $separator = '.';
8316 $result = number_format($float, $decimalpoints, $separator, '');
8317 if ($stripzeros) {
8318 // Remove zeros and final dot if not needed.
8319 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8321 return $result;
8325 * Converts locale specific floating point/comma number back to standard PHP float value
8326 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8328 * @param string $localefloat locale aware float representation
8329 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8330 * @return mixed float|bool - false or the parsed float.
8332 function unformat_float($localefloat, $strict = false) {
8333 $localefloat = trim($localefloat);
8335 if ($localefloat == '') {
8336 return null;
8339 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8340 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8342 if ($strict && !is_numeric($localefloat)) {
8343 return false;
8346 return (float)$localefloat;
8350 * Given a simple array, this shuffles it up just like shuffle()
8351 * Unlike PHP's shuffle() this function works on any machine.
8353 * @param array $array The array to be rearranged
8354 * @return array
8356 function swapshuffle($array) {
8358 $last = count($array) - 1;
8359 for ($i = 0; $i <= $last; $i++) {
8360 $from = rand(0, $last);
8361 $curr = $array[$i];
8362 $array[$i] = $array[$from];
8363 $array[$from] = $curr;
8365 return $array;
8369 * Like {@link swapshuffle()}, but works on associative arrays
8371 * @param array $array The associative array to be rearranged
8372 * @return array
8374 function swapshuffle_assoc($array) {
8376 $newarray = array();
8377 $newkeys = swapshuffle(array_keys($array));
8379 foreach ($newkeys as $newkey) {
8380 $newarray[$newkey] = $array[$newkey];
8382 return $newarray;
8386 * Given an arbitrary array, and a number of draws,
8387 * this function returns an array with that amount
8388 * of items. The indexes are retained.
8390 * @todo Finish documenting this function
8392 * @param array $array
8393 * @param int $draws
8394 * @return array
8396 function draw_rand_array($array, $draws) {
8398 $return = array();
8400 $last = count($array);
8402 if ($draws > $last) {
8403 $draws = $last;
8406 while ($draws > 0) {
8407 $last--;
8409 $keys = array_keys($array);
8410 $rand = rand(0, $last);
8412 $return[$keys[$rand]] = $array[$keys[$rand]];
8413 unset($array[$keys[$rand]]);
8415 $draws--;
8418 return $return;
8422 * Calculate the difference between two microtimes
8424 * @param string $a The first Microtime
8425 * @param string $b The second Microtime
8426 * @return string
8428 function microtime_diff($a, $b) {
8429 list($adec, $asec) = explode(' ', $a);
8430 list($bdec, $bsec) = explode(' ', $b);
8431 return $bsec - $asec + $bdec - $adec;
8435 * Given a list (eg a,b,c,d,e) this function returns
8436 * an array of 1->a, 2->b, 3->c etc
8438 * @param string $list The string to explode into array bits
8439 * @param string $separator The separator used within the list string
8440 * @return array The now assembled array
8442 function make_menu_from_list($list, $separator=',') {
8444 $array = array_reverse(explode($separator, $list), true);
8445 foreach ($array as $key => $item) {
8446 $outarray[$key+1] = trim($item);
8448 return $outarray;
8452 * Creates an array that represents all the current grades that
8453 * can be chosen using the given grading type.
8455 * Negative numbers
8456 * are scales, zero is no grade, and positive numbers are maximum
8457 * grades.
8459 * @todo Finish documenting this function or better deprecated this completely!
8461 * @param int $gradingtype
8462 * @return array
8464 function make_grades_menu($gradingtype) {
8465 global $DB;
8467 $grades = array();
8468 if ($gradingtype < 0) {
8469 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8470 return make_menu_from_list($scale->scale);
8472 } else if ($gradingtype > 0) {
8473 for ($i=$gradingtype; $i>=0; $i--) {
8474 $grades[$i] = $i .' / '. $gradingtype;
8476 return $grades;
8478 return $grades;
8482 * make_unique_id_code
8484 * @todo Finish documenting this function
8486 * @uses $_SERVER
8487 * @param string $extra Extra string to append to the end of the code
8488 * @return string
8490 function make_unique_id_code($extra = '') {
8492 $hostname = 'unknownhost';
8493 if (!empty($_SERVER['HTTP_HOST'])) {
8494 $hostname = $_SERVER['HTTP_HOST'];
8495 } else if (!empty($_ENV['HTTP_HOST'])) {
8496 $hostname = $_ENV['HTTP_HOST'];
8497 } else if (!empty($_SERVER['SERVER_NAME'])) {
8498 $hostname = $_SERVER['SERVER_NAME'];
8499 } else if (!empty($_ENV['SERVER_NAME'])) {
8500 $hostname = $_ENV['SERVER_NAME'];
8503 $date = gmdate("ymdHis");
8505 $random = random_string(6);
8507 if ($extra) {
8508 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8509 } else {
8510 return $hostname .'+'. $date .'+'. $random;
8516 * Function to check the passed address is within the passed subnet
8518 * The parameter is a comma separated string of subnet definitions.
8519 * Subnet strings can be in one of three formats:
8520 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8521 * 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)
8522 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8523 * Code for type 1 modified from user posted comments by mediator at
8524 * {@link http://au.php.net/manual/en/function.ip2long.php}
8526 * @param string $addr The address you are checking
8527 * @param string $subnetstr The string of subnet addresses
8528 * @return bool
8530 function address_in_subnet($addr, $subnetstr) {
8532 if ($addr == '0.0.0.0') {
8533 return false;
8535 $subnets = explode(',', $subnetstr);
8536 $found = false;
8537 $addr = trim($addr);
8538 $addr = cleanremoteaddr($addr, false); // Normalise.
8539 if ($addr === null) {
8540 return false;
8542 $addrparts = explode(':', $addr);
8544 $ipv6 = strpos($addr, ':');
8546 foreach ($subnets as $subnet) {
8547 $subnet = trim($subnet);
8548 if ($subnet === '') {
8549 continue;
8552 if (strpos($subnet, '/') !== false) {
8553 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8554 list($ip, $mask) = explode('/', $subnet);
8555 $mask = trim($mask);
8556 if (!is_number($mask)) {
8557 continue; // Incorect mask number, eh?
8559 $ip = cleanremoteaddr($ip, false); // Normalise.
8560 if ($ip === null) {
8561 continue;
8563 if (strpos($ip, ':') !== false) {
8564 // IPv6.
8565 if (!$ipv6) {
8566 continue;
8568 if ($mask > 128 or $mask < 0) {
8569 continue; // Nonsense.
8571 if ($mask == 0) {
8572 return true; // Any address.
8574 if ($mask == 128) {
8575 if ($ip === $addr) {
8576 return true;
8578 continue;
8580 $ipparts = explode(':', $ip);
8581 $modulo = $mask % 16;
8582 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8583 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8584 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8585 if ($modulo == 0) {
8586 return true;
8588 $pos = ($mask-$modulo)/16;
8589 $ipnet = hexdec($ipparts[$pos]);
8590 $addrnet = hexdec($addrparts[$pos]);
8591 $mask = 0xffff << (16 - $modulo);
8592 if (($addrnet & $mask) == ($ipnet & $mask)) {
8593 return true;
8597 } else {
8598 // IPv4.
8599 if ($ipv6) {
8600 continue;
8602 if ($mask > 32 or $mask < 0) {
8603 continue; // Nonsense.
8605 if ($mask == 0) {
8606 return true;
8608 if ($mask == 32) {
8609 if ($ip === $addr) {
8610 return true;
8612 continue;
8614 $mask = 0xffffffff << (32 - $mask);
8615 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8616 return true;
8620 } else if (strpos($subnet, '-') !== false) {
8621 // 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.
8622 $parts = explode('-', $subnet);
8623 if (count($parts) != 2) {
8624 continue;
8627 if (strpos($subnet, ':') !== false) {
8628 // IPv6.
8629 if (!$ipv6) {
8630 continue;
8632 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8633 if ($ipstart === null) {
8634 continue;
8636 $ipparts = explode(':', $ipstart);
8637 $start = hexdec(array_pop($ipparts));
8638 $ipparts[] = trim($parts[1]);
8639 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8640 if ($ipend === null) {
8641 continue;
8643 $ipparts[7] = '';
8644 $ipnet = implode(':', $ipparts);
8645 if (strpos($addr, $ipnet) !== 0) {
8646 continue;
8648 $ipparts = explode(':', $ipend);
8649 $end = hexdec($ipparts[7]);
8651 $addrend = hexdec($addrparts[7]);
8653 if (($addrend >= $start) and ($addrend <= $end)) {
8654 return true;
8657 } else {
8658 // IPv4.
8659 if ($ipv6) {
8660 continue;
8662 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8663 if ($ipstart === null) {
8664 continue;
8666 $ipparts = explode('.', $ipstart);
8667 $ipparts[3] = trim($parts[1]);
8668 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8669 if ($ipend === null) {
8670 continue;
8673 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8674 return true;
8678 } else {
8679 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8680 if (strpos($subnet, ':') !== false) {
8681 // IPv6.
8682 if (!$ipv6) {
8683 continue;
8685 $parts = explode(':', $subnet);
8686 $count = count($parts);
8687 if ($parts[$count-1] === '') {
8688 unset($parts[$count-1]); // Trim trailing :'s.
8689 $count--;
8690 $subnet = implode('.', $parts);
8692 $isip = cleanremoteaddr($subnet, false); // Normalise.
8693 if ($isip !== null) {
8694 if ($isip === $addr) {
8695 return true;
8697 continue;
8698 } else if ($count > 8) {
8699 continue;
8701 $zeros = array_fill(0, 8-$count, '0');
8702 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8703 if (address_in_subnet($addr, $subnet)) {
8704 return true;
8707 } else {
8708 // IPv4.
8709 if ($ipv6) {
8710 continue;
8712 $parts = explode('.', $subnet);
8713 $count = count($parts);
8714 if ($parts[$count-1] === '') {
8715 unset($parts[$count-1]); // Trim trailing .
8716 $count--;
8717 $subnet = implode('.', $parts);
8719 if ($count == 4) {
8720 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8721 if ($subnet === $addr) {
8722 return true;
8724 continue;
8725 } else if ($count > 4) {
8726 continue;
8728 $zeros = array_fill(0, 4-$count, '0');
8729 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8730 if (address_in_subnet($addr, $subnet)) {
8731 return true;
8737 return false;
8741 * For outputting debugging info
8743 * @param string $string The string to write
8744 * @param string $eol The end of line char(s) to use
8745 * @param string $sleep Period to make the application sleep
8746 * This ensures any messages have time to display before redirect
8748 function mtrace($string, $eol="\n", $sleep=0) {
8749 global $CFG;
8751 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
8752 $fn = $CFG->mtrace_wrapper;
8753 $fn($string, $eol);
8754 return;
8755 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
8756 fwrite(STDOUT, $string.$eol);
8757 } else {
8758 echo $string . $eol;
8761 flush();
8763 // Delay to keep message on user's screen in case of subsequent redirect.
8764 if ($sleep) {
8765 sleep($sleep);
8770 * Replace 1 or more slashes or backslashes to 1 slash
8772 * @param string $path The path to strip
8773 * @return string the path with double slashes removed
8775 function cleardoubleslashes ($path) {
8776 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8780 * Is current ip in give list?
8782 * @param string $list
8783 * @return bool
8785 function remoteip_in_list($list) {
8786 $inlist = false;
8787 $clientip = getremoteaddr(null);
8789 if (!$clientip) {
8790 // Ensure access on cli.
8791 return true;
8794 $list = explode("\n", $list);
8795 foreach ($list as $subnet) {
8796 $subnet = trim($subnet);
8797 if (address_in_subnet($clientip, $subnet)) {
8798 $inlist = true;
8799 break;
8802 return $inlist;
8806 * Returns most reliable client address
8808 * @param string $default If an address can't be determined, then return this
8809 * @return string The remote IP address
8811 function getremoteaddr($default='0.0.0.0') {
8812 global $CFG;
8814 if (empty($CFG->getremoteaddrconf)) {
8815 // This will happen, for example, before just after the upgrade, as the
8816 // user is redirected to the admin screen.
8817 $variablestoskip = 0;
8818 } else {
8819 $variablestoskip = $CFG->getremoteaddrconf;
8821 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8822 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8823 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8824 return $address ? $address : $default;
8827 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8828 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8829 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8830 $address = $forwardedaddresses[0];
8832 if (substr_count($address, ":") > 1) {
8833 // Remove port and brackets from IPv6.
8834 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8835 $address = $matches[1];
8837 } else {
8838 // Remove port from IPv4.
8839 if (substr_count($address, ":") == 1) {
8840 $parts = explode(":", $address);
8841 $address = $parts[0];
8845 $address = cleanremoteaddr($address);
8846 return $address ? $address : $default;
8849 if (!empty($_SERVER['REMOTE_ADDR'])) {
8850 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8851 return $address ? $address : $default;
8852 } else {
8853 return $default;
8858 * Cleans an ip address. Internal addresses are now allowed.
8859 * (Originally local addresses were not allowed.)
8861 * @param string $addr IPv4 or IPv6 address
8862 * @param bool $compress use IPv6 address compression
8863 * @return string normalised ip address string, null if error
8865 function cleanremoteaddr($addr, $compress=false) {
8866 $addr = trim($addr);
8868 if (strpos($addr, ':') !== false) {
8869 // Can be only IPv6.
8870 $parts = explode(':', $addr);
8871 $count = count($parts);
8873 if (strpos($parts[$count-1], '.') !== false) {
8874 // Legacy ipv4 notation.
8875 $last = array_pop($parts);
8876 $ipv4 = cleanremoteaddr($last, true);
8877 if ($ipv4 === null) {
8878 return null;
8880 $bits = explode('.', $ipv4);
8881 $parts[] = dechex($bits[0]).dechex($bits[1]);
8882 $parts[] = dechex($bits[2]).dechex($bits[3]);
8883 $count = count($parts);
8884 $addr = implode(':', $parts);
8887 if ($count < 3 or $count > 8) {
8888 return null; // Severly malformed.
8891 if ($count != 8) {
8892 if (strpos($addr, '::') === false) {
8893 return null; // Malformed.
8895 // Uncompress.
8896 $insertat = array_search('', $parts, true);
8897 $missing = array_fill(0, 1 + 8 - $count, '0');
8898 array_splice($parts, $insertat, 1, $missing);
8899 foreach ($parts as $key => $part) {
8900 if ($part === '') {
8901 $parts[$key] = '0';
8906 $adr = implode(':', $parts);
8907 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8908 return null; // Incorrect format - sorry.
8911 // Normalise 0s and case.
8912 $parts = array_map('hexdec', $parts);
8913 $parts = array_map('dechex', $parts);
8915 $result = implode(':', $parts);
8917 if (!$compress) {
8918 return $result;
8921 if ($result === '0:0:0:0:0:0:0:0') {
8922 return '::'; // All addresses.
8925 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8926 if ($compressed !== $result) {
8927 return $compressed;
8930 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8931 if ($compressed !== $result) {
8932 return $compressed;
8935 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8936 if ($compressed !== $result) {
8937 return $compressed;
8940 return $result;
8943 // First get all things that look like IPv4 addresses.
8944 $parts = array();
8945 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8946 return null;
8948 unset($parts[0]);
8950 foreach ($parts as $key => $match) {
8951 if ($match > 255) {
8952 return null;
8954 $parts[$key] = (int)$match; // Normalise 0s.
8957 return implode('.', $parts);
8962 * Is IP address a public address?
8964 * @param string $ip The ip to check
8965 * @return bool true if the ip is public
8967 function ip_is_public($ip) {
8968 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
8972 * This function will make a complete copy of anything it's given,
8973 * regardless of whether it's an object or not.
8975 * @param mixed $thing Something you want cloned
8976 * @return mixed What ever it is you passed it
8978 function fullclone($thing) {
8979 return unserialize(serialize($thing));
8983 * Used to make sure that $min <= $value <= $max
8985 * Make sure that value is between min, and max
8987 * @param int $min The minimum value
8988 * @param int $value The value to check
8989 * @param int $max The maximum value
8990 * @return int
8992 function bounded_number($min, $value, $max) {
8993 if ($value < $min) {
8994 return $min;
8996 if ($value > $max) {
8997 return $max;
8999 return $value;
9003 * Check if there is a nested array within the passed array
9005 * @param array $array
9006 * @return bool true if there is a nested array false otherwise
9008 function array_is_nested($array) {
9009 foreach ($array as $value) {
9010 if (is_array($value)) {
9011 return true;
9014 return false;
9018 * get_performance_info() pairs up with init_performance_info()
9019 * loaded in setup.php. Returns an array with 'html' and 'txt'
9020 * values ready for use, and each of the individual stats provided
9021 * separately as well.
9023 * @return array
9025 function get_performance_info() {
9026 global $CFG, $PERF, $DB, $PAGE;
9028 $info = array();
9029 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9031 $info['html'] = '';
9032 if (!empty($CFG->themedesignermode)) {
9033 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9034 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9036 $info['html'] .= '<ul class="list-unstyled m-l-1 row">'; // Holds userfriendly HTML representation.
9038 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9040 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9041 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9043 if (function_exists('memory_get_usage')) {
9044 $info['memory_total'] = memory_get_usage();
9045 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9046 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9047 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9048 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9051 if (function_exists('memory_get_peak_usage')) {
9052 $info['memory_peak'] = memory_get_peak_usage();
9053 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9054 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9057 $info['html'] .= '</ul><ul class="list-unstyled m-l-1 row">';
9058 $inc = get_included_files();
9059 $info['includecount'] = count($inc);
9060 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9061 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9063 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9064 // We can not track more performance before installation or before PAGE init, sorry.
9065 return $info;
9068 $filtermanager = filter_manager::instance();
9069 if (method_exists($filtermanager, 'get_performance_summary')) {
9070 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9071 $info = array_merge($filterinfo, $info);
9072 foreach ($filterinfo as $key => $value) {
9073 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9074 $info['txt'] .= "$key: $value ";
9078 $stringmanager = get_string_manager();
9079 if (method_exists($stringmanager, 'get_performance_summary')) {
9080 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9081 $info = array_merge($filterinfo, $info);
9082 foreach ($filterinfo as $key => $value) {
9083 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9084 $info['txt'] .= "$key: $value ";
9088 if (!empty($PERF->logwrites)) {
9089 $info['logwrites'] = $PERF->logwrites;
9090 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9091 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9094 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9095 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9096 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9098 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9099 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9100 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9102 if (function_exists('posix_times')) {
9103 $ptimes = posix_times();
9104 if (is_array($ptimes)) {
9105 foreach ($ptimes as $key => $val) {
9106 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9108 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9109 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9110 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9114 // Grab the load average for the last minute.
9115 // /proc will only work under some linux configurations
9116 // while uptime is there under MacOSX/Darwin and other unices.
9117 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9118 list($serverload) = explode(' ', $loadavg[0]);
9119 unset($loadavg);
9120 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9121 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9122 $serverload = $matches[1];
9123 } else {
9124 trigger_error('Could not parse uptime output!');
9127 if (!empty($serverload)) {
9128 $info['serverload'] = $serverload;
9129 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9130 $info['txt'] .= "serverload: {$info['serverload']} ";
9133 // Display size of session if session started.
9134 if ($si = \core\session\manager::get_performance_info()) {
9135 $info['sessionsize'] = $si['size'];
9136 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9137 $info['txt'] .= $si['txt'];
9140 $info['html'] .= '</ul>';
9141 if ($stats = cache_helper::get_stats()) {
9142 $html = '<ul class="cachesused list-unstyled m-l-1 row">';
9143 $html .= '<li class="cache-stats-heading font-weight-bold">Caches used (hits/misses/sets)</li>';
9144 $html .= '</ul><ul class="cachesused list-unstyled m-l-1">';
9145 $text = 'Caches used (hits/misses/sets): ';
9146 $hits = 0;
9147 $misses = 0;
9148 $sets = 0;
9149 foreach ($stats as $definition => $details) {
9150 switch ($details['mode']) {
9151 case cache_store::MODE_APPLICATION:
9152 $modeclass = 'application';
9153 $mode = ' <span title="application cache">[a]</span>';
9154 break;
9155 case cache_store::MODE_SESSION:
9156 $modeclass = 'session';
9157 $mode = ' <span title="session cache">[s]</span>';
9158 break;
9159 case cache_store::MODE_REQUEST:
9160 $modeclass = 'request';
9161 $mode = ' <span title="request cache">[r]</span>';
9162 break;
9164 $html .= '<ul class="cache-definition-stats list-unstyled m-l-1 cache-mode-'.$modeclass.' card d-inline-block">';
9165 $html .= '<li class="cache-definition-stats-heading p-t-1 card-header bg-inverse font-weight-bold">' .
9166 $definition . $mode.'</li>';
9167 $text .= "$definition {";
9168 foreach ($details['stores'] as $store => $data) {
9169 $hits += $data['hits'];
9170 $misses += $data['misses'];
9171 $sets += $data['sets'];
9172 if ($data['hits'] == 0 and $data['misses'] > 0) {
9173 $cachestoreclass = 'nohits text-danger';
9174 } else if ($data['hits'] < $data['misses']) {
9175 $cachestoreclass = 'lowhits text-warning';
9176 } else {
9177 $cachestoreclass = 'hihits text-success';
9179 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9180 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">" .
9181 "$store: $data[hits] / $data[misses] / $data[sets]</li>";
9182 // This makes boxes of same sizes.
9183 if (count($details['stores']) == 1) {
9184 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">&nbsp;</li>";
9187 $html .= '</ul>';
9188 $text .= '} ';
9190 $html .= '</ul> ';
9191 $html .= "<div class='cache-total-stats row'>Total: $hits / $misses / $sets</div>";
9192 $info['cachesused'] = "$hits / $misses / $sets";
9193 $info['html'] .= $html;
9194 $info['txt'] .= $text.'. ';
9195 } else {
9196 $info['cachesused'] = '0 / 0 / 0';
9197 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9198 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9201 $info['html'] = '<div class="performanceinfo siteinfo container-fluid">'.$info['html'].'</div>';
9202 return $info;
9206 * Delete directory or only its content
9208 * @param string $dir directory path
9209 * @param bool $contentonly
9210 * @return bool success, true also if dir does not exist
9212 function remove_dir($dir, $contentonly=false) {
9213 if (!file_exists($dir)) {
9214 // Nothing to do.
9215 return true;
9217 if (!$handle = opendir($dir)) {
9218 return false;
9220 $result = true;
9221 while (false!==($item = readdir($handle))) {
9222 if ($item != '.' && $item != '..') {
9223 if (is_dir($dir.'/'.$item)) {
9224 $result = remove_dir($dir.'/'.$item) && $result;
9225 } else {
9226 $result = unlink($dir.'/'.$item) && $result;
9230 closedir($handle);
9231 if ($contentonly) {
9232 clearstatcache(); // Make sure file stat cache is properly invalidated.
9233 return $result;
9235 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9236 clearstatcache(); // Make sure file stat cache is properly invalidated.
9237 return $result;
9241 * Detect if an object or a class contains a given property
9242 * will take an actual object or the name of a class
9244 * @param mix $obj Name of class or real object to test
9245 * @param string $property name of property to find
9246 * @return bool true if property exists
9248 function object_property_exists( $obj, $property ) {
9249 if (is_string( $obj )) {
9250 $properties = get_class_vars( $obj );
9251 } else {
9252 $properties = get_object_vars( $obj );
9254 return array_key_exists( $property, $properties );
9258 * Converts an object into an associative array
9260 * This function converts an object into an associative array by iterating
9261 * over its public properties. Because this function uses the foreach
9262 * construct, Iterators are respected. It works recursively on arrays of objects.
9263 * Arrays and simple values are returned as is.
9265 * If class has magic properties, it can implement IteratorAggregate
9266 * and return all available properties in getIterator()
9268 * @param mixed $var
9269 * @return array
9271 function convert_to_array($var) {
9272 $result = array();
9274 // Loop over elements/properties.
9275 foreach ($var as $key => $value) {
9276 // Recursively convert objects.
9277 if (is_object($value) || is_array($value)) {
9278 $result[$key] = convert_to_array($value);
9279 } else {
9280 // Simple values are untouched.
9281 $result[$key] = $value;
9284 return $result;
9288 * Detect a custom script replacement in the data directory that will
9289 * replace an existing moodle script
9291 * @return string|bool full path name if a custom script exists, false if no custom script exists
9293 function custom_script_path() {
9294 global $CFG, $SCRIPT;
9296 if ($SCRIPT === null) {
9297 // Probably some weird external script.
9298 return false;
9301 $scriptpath = $CFG->customscripts . $SCRIPT;
9303 // Check the custom script exists.
9304 if (file_exists($scriptpath) and is_file($scriptpath)) {
9305 return $scriptpath;
9306 } else {
9307 return false;
9312 * Returns whether or not the user object is a remote MNET user. This function
9313 * is in moodlelib because it does not rely on loading any of the MNET code.
9315 * @param object $user A valid user object
9316 * @return bool True if the user is from a remote Moodle.
9318 function is_mnet_remote_user($user) {
9319 global $CFG;
9321 if (!isset($CFG->mnet_localhost_id)) {
9322 include_once($CFG->dirroot . '/mnet/lib.php');
9323 $env = new mnet_environment();
9324 $env->init();
9325 unset($env);
9328 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9332 * This function will search for browser prefereed languages, setting Moodle
9333 * to use the best one available if $SESSION->lang is undefined
9335 function setup_lang_from_browser() {
9336 global $CFG, $SESSION, $USER;
9338 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9339 // Lang is defined in session or user profile, nothing to do.
9340 return;
9343 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9344 return;
9347 // Extract and clean langs from headers.
9348 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9349 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9350 $rawlangs = explode(',', $rawlangs); // Convert to array.
9351 $langs = array();
9353 $order = 1.0;
9354 foreach ($rawlangs as $lang) {
9355 if (strpos($lang, ';') === false) {
9356 $langs[(string)$order] = $lang;
9357 $order = $order-0.01;
9358 } else {
9359 $parts = explode(';', $lang);
9360 $pos = strpos($parts[1], '=');
9361 $langs[substr($parts[1], $pos+1)] = $parts[0];
9364 krsort($langs, SORT_NUMERIC);
9366 // Look for such langs under standard locations.
9367 foreach ($langs as $lang) {
9368 // Clean it properly for include.
9369 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9370 if (get_string_manager()->translation_exists($lang, false)) {
9371 // Lang exists, set it in session.
9372 $SESSION->lang = $lang;
9373 // We have finished. Go out.
9374 break;
9377 return;
9381 * Check if $url matches anything in proxybypass list
9383 * Any errors just result in the proxy being used (least bad)
9385 * @param string $url url to check
9386 * @return boolean true if we should bypass the proxy
9388 function is_proxybypass( $url ) {
9389 global $CFG;
9391 // Sanity check.
9392 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9393 return false;
9396 // Get the host part out of the url.
9397 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9398 return false;
9401 // Get the possible bypass hosts into an array.
9402 $matches = explode( ',', $CFG->proxybypass );
9404 // Check for a match.
9405 // (IPs need to match the left hand side and hosts the right of the url,
9406 // but we can recklessly check both as there can't be a false +ve).
9407 foreach ($matches as $match) {
9408 $match = trim($match);
9410 // Try for IP match (Left side).
9411 $lhs = substr($host, 0, strlen($match));
9412 if (strcasecmp($match, $lhs)==0) {
9413 return true;
9416 // Try for host match (Right side).
9417 $rhs = substr($host, -strlen($match));
9418 if (strcasecmp($match, $rhs)==0) {
9419 return true;
9423 // Nothing matched.
9424 return false;
9428 * Check if the passed navigation is of the new style
9430 * @param mixed $navigation
9431 * @return bool true for yes false for no
9433 function is_newnav($navigation) {
9434 if (is_array($navigation) && !empty($navigation['newnav'])) {
9435 return true;
9436 } else {
9437 return false;
9442 * Checks whether the given variable name is defined as a variable within the given object.
9444 * This will NOT work with stdClass objects, which have no class variables.
9446 * @param string $var The variable name
9447 * @param object $object The object to check
9448 * @return boolean
9450 function in_object_vars($var, $object) {
9451 $classvars = get_class_vars(get_class($object));
9452 $classvars = array_keys($classvars);
9453 return in_array($var, $classvars);
9457 * Returns an array without repeated objects.
9458 * This function is similar to array_unique, but for arrays that have objects as values
9460 * @param array $array
9461 * @param bool $keepkeyassoc
9462 * @return array
9464 function object_array_unique($array, $keepkeyassoc = true) {
9465 $duplicatekeys = array();
9466 $tmp = array();
9468 foreach ($array as $key => $val) {
9469 // Convert objects to arrays, in_array() does not support objects.
9470 if (is_object($val)) {
9471 $val = (array)$val;
9474 if (!in_array($val, $tmp)) {
9475 $tmp[] = $val;
9476 } else {
9477 $duplicatekeys[] = $key;
9481 foreach ($duplicatekeys as $key) {
9482 unset($array[$key]);
9485 return $keepkeyassoc ? $array : array_values($array);
9489 * Is a userid the primary administrator?
9491 * @param int $userid int id of user to check
9492 * @return boolean
9494 function is_primary_admin($userid) {
9495 $primaryadmin = get_admin();
9497 if ($userid == $primaryadmin->id) {
9498 return true;
9499 } else {
9500 return false;
9505 * Returns the site identifier
9507 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9509 function get_site_identifier() {
9510 global $CFG;
9511 // Check to see if it is missing. If so, initialise it.
9512 if (empty($CFG->siteidentifier)) {
9513 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9515 // Return it.
9516 return $CFG->siteidentifier;
9520 * Check whether the given password has no more than the specified
9521 * number of consecutive identical characters.
9523 * @param string $password password to be checked against the password policy
9524 * @param integer $maxchars maximum number of consecutive identical characters
9525 * @return bool
9527 function check_consecutive_identical_characters($password, $maxchars) {
9529 if ($maxchars < 1) {
9530 return true; // Zero 0 is to disable this check.
9532 if (strlen($password) <= $maxchars) {
9533 return true; // Too short to fail this test.
9536 $previouschar = '';
9537 $consecutivecount = 1;
9538 foreach (str_split($password) as $char) {
9539 if ($char != $previouschar) {
9540 $consecutivecount = 1;
9541 } else {
9542 $consecutivecount++;
9543 if ($consecutivecount > $maxchars) {
9544 return false; // Check failed already.
9548 $previouschar = $char;
9551 return true;
9555 * Helper function to do partial function binding.
9556 * so we can use it for preg_replace_callback, for example
9557 * this works with php functions, user functions, static methods and class methods
9558 * it returns you a callback that you can pass on like so:
9560 * $callback = partial('somefunction', $arg1, $arg2);
9561 * or
9562 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9563 * or even
9564 * $obj = new someclass();
9565 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9567 * and then the arguments that are passed through at calltime are appended to the argument list.
9569 * @param mixed $function a php callback
9570 * @param mixed $arg1,... $argv arguments to partially bind with
9571 * @return array Array callback
9573 function partial() {
9574 if (!class_exists('partial')) {
9576 * Used to manage function binding.
9577 * @copyright 2009 Penny Leach
9578 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9580 class partial{
9581 /** @var array */
9582 public $values = array();
9583 /** @var string The function to call as a callback. */
9584 public $func;
9586 * Constructor
9587 * @param string $func
9588 * @param array $args
9590 public function __construct($func, $args) {
9591 $this->values = $args;
9592 $this->func = $func;
9595 * Calls the callback function.
9596 * @return mixed
9598 public function method() {
9599 $args = func_get_args();
9600 return call_user_func_array($this->func, array_merge($this->values, $args));
9604 $args = func_get_args();
9605 $func = array_shift($args);
9606 $p = new partial($func, $args);
9607 return array($p, 'method');
9611 * helper function to load up and initialise the mnet environment
9612 * this must be called before you use mnet functions.
9614 * @return mnet_environment the equivalent of old $MNET global
9616 function get_mnet_environment() {
9617 global $CFG;
9618 require_once($CFG->dirroot . '/mnet/lib.php');
9619 static $instance = null;
9620 if (empty($instance)) {
9621 $instance = new mnet_environment();
9622 $instance->init();
9624 return $instance;
9628 * during xmlrpc server code execution, any code wishing to access
9629 * information about the remote peer must use this to get it.
9631 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9633 function get_mnet_remote_client() {
9634 if (!defined('MNET_SERVER')) {
9635 debugging(get_string('notinxmlrpcserver', 'mnet'));
9636 return false;
9638 global $MNET_REMOTE_CLIENT;
9639 if (isset($MNET_REMOTE_CLIENT)) {
9640 return $MNET_REMOTE_CLIENT;
9642 return false;
9646 * during the xmlrpc server code execution, this will be called
9647 * to setup the object returned by {@link get_mnet_remote_client}
9649 * @param mnet_remote_client $client the client to set up
9650 * @throws moodle_exception
9652 function set_mnet_remote_client($client) {
9653 if (!defined('MNET_SERVER')) {
9654 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9656 global $MNET_REMOTE_CLIENT;
9657 $MNET_REMOTE_CLIENT = $client;
9661 * return the jump url for a given remote user
9662 * this is used for rewriting forum post links in emails, etc
9664 * @param stdclass $user the user to get the idp url for
9666 function mnet_get_idp_jump_url($user) {
9667 global $CFG;
9669 static $mnetjumps = array();
9670 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9671 $idp = mnet_get_peer_host($user->mnethostid);
9672 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9673 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9675 return $mnetjumps[$user->mnethostid];
9679 * Gets the homepage to use for the current user
9681 * @return int One of HOMEPAGE_*
9683 function get_home_page() {
9684 global $CFG;
9686 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9687 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9688 return HOMEPAGE_MY;
9689 } else {
9690 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9693 return HOMEPAGE_SITE;
9697 * Gets the name of a course to be displayed when showing a list of courses.
9698 * By default this is just $course->fullname but user can configure it. The
9699 * result of this function should be passed through print_string.
9700 * @param stdClass|course_in_list $course Moodle course object
9701 * @return string Display name of course (either fullname or short + fullname)
9703 function get_course_display_name_for_list($course) {
9704 global $CFG;
9705 if (!empty($CFG->courselistshortnames)) {
9706 if (!($course instanceof stdClass)) {
9707 $course = (object)convert_to_array($course);
9709 return get_string('courseextendednamedisplay', '', $course);
9710 } else {
9711 return $course->fullname;
9716 * Safe analogue of unserialize() that can only parse arrays
9718 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
9719 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
9720 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
9722 * @param string $expression
9723 * @return array|bool either parsed array or false if parsing was impossible.
9725 function unserialize_array($expression) {
9726 $subs = [];
9727 // Find nested arrays, parse them and store in $subs , substitute with special string.
9728 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
9729 $key = '--SUB' . count($subs) . '--';
9730 $subs[$key] = unserialize_array($matches[2]);
9731 if ($subs[$key] === false) {
9732 return false;
9734 $expression = str_replace($matches[2], $key . ';', $expression);
9737 // Check the expression is an array.
9738 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
9739 return false;
9741 // Get the size and elements of an array (key;value;key;value;....).
9742 $parts = explode(';', $matches1[2]);
9743 $size = intval($matches1[1]);
9744 if (count($parts) < $size * 2 + 1) {
9745 return false;
9747 // Analyze each part and make sure it is an integer or string or a substitute.
9748 $value = [];
9749 for ($i = 0; $i < $size * 2; $i++) {
9750 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
9751 $parts[$i] = (int)$matches2[1];
9752 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
9753 $parts[$i] = $matches3[2];
9754 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
9755 $parts[$i] = $subs[$parts[$i]];
9756 } else {
9757 return false;
9760 // Combine keys and values.
9761 for ($i = 0; $i < $size * 2; $i += 2) {
9762 $value[$parts[$i]] = $parts[$i+1];
9764 return $value;
9768 * The lang_string class
9770 * This special class is used to create an object representation of a string request.
9771 * It is special because processing doesn't occur until the object is first used.
9772 * The class was created especially to aid performance in areas where strings were
9773 * required to be generated but were not necessarily used.
9774 * As an example the admin tree when generated uses over 1500 strings, of which
9775 * normally only 1/3 are ever actually printed at any time.
9776 * The performance advantage is achieved by not actually processing strings that
9777 * arn't being used, as such reducing the processing required for the page.
9779 * How to use the lang_string class?
9780 * There are two methods of using the lang_string class, first through the
9781 * forth argument of the get_string function, and secondly directly.
9782 * The following are examples of both.
9783 * 1. Through get_string calls e.g.
9784 * $string = get_string($identifier, $component, $a, true);
9785 * $string = get_string('yes', 'moodle', null, true);
9786 * 2. Direct instantiation
9787 * $string = new lang_string($identifier, $component, $a, $lang);
9788 * $string = new lang_string('yes');
9790 * How do I use a lang_string object?
9791 * The lang_string object makes use of a magic __toString method so that you
9792 * are able to use the object exactly as you would use a string in most cases.
9793 * This means you are able to collect it into a variable and then directly
9794 * echo it, or concatenate it into another string, or similar.
9795 * The other thing you can do is manually get the string by calling the
9796 * lang_strings out method e.g.
9797 * $string = new lang_string('yes');
9798 * $string->out();
9799 * Also worth noting is that the out method can take one argument, $lang which
9800 * allows the developer to change the language on the fly.
9802 * When should I use a lang_string object?
9803 * The lang_string object is designed to be used in any situation where a
9804 * string may not be needed, but needs to be generated.
9805 * The admin tree is a good example of where lang_string objects should be
9806 * used.
9807 * A more practical example would be any class that requries strings that may
9808 * not be printed (after all classes get renderer by renderers and who knows
9809 * what they will do ;))
9811 * When should I not use a lang_string object?
9812 * Don't use lang_strings when you are going to use a string immediately.
9813 * There is no need as it will be processed immediately and there will be no
9814 * advantage, and in fact perhaps a negative hit as a class has to be
9815 * instantiated for a lang_string object, however get_string won't require
9816 * that.
9818 * Limitations:
9819 * 1. You cannot use a lang_string object as an array offset. Doing so will
9820 * result in PHP throwing an error. (You can use it as an object property!)
9822 * @package core
9823 * @category string
9824 * @copyright 2011 Sam Hemelryk
9825 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9827 class lang_string {
9829 /** @var string The strings identifier */
9830 protected $identifier;
9831 /** @var string The strings component. Default '' */
9832 protected $component = '';
9833 /** @var array|stdClass Any arguments required for the string. Default null */
9834 protected $a = null;
9835 /** @var string The language to use when processing the string. Default null */
9836 protected $lang = null;
9838 /** @var string The processed string (once processed) */
9839 protected $string = null;
9842 * A special boolean. If set to true then the object has been woken up and
9843 * cannot be regenerated. If this is set then $this->string MUST be used.
9844 * @var bool
9846 protected $forcedstring = false;
9849 * Constructs a lang_string object
9851 * This function should do as little processing as possible to ensure the best
9852 * performance for strings that won't be used.
9854 * @param string $identifier The strings identifier
9855 * @param string $component The strings component
9856 * @param stdClass|array $a Any arguments the string requires
9857 * @param string $lang The language to use when processing the string.
9858 * @throws coding_exception
9860 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9861 if (empty($component)) {
9862 $component = 'moodle';
9865 $this->identifier = $identifier;
9866 $this->component = $component;
9867 $this->lang = $lang;
9869 // We MUST duplicate $a to ensure that it if it changes by reference those
9870 // changes are not carried across.
9871 // To do this we always ensure $a or its properties/values are strings
9872 // and that any properties/values that arn't convertable are forgotten.
9873 if (!empty($a)) {
9874 if (is_scalar($a)) {
9875 $this->a = $a;
9876 } else if ($a instanceof lang_string) {
9877 $this->a = $a->out();
9878 } else if (is_object($a) or is_array($a)) {
9879 $a = (array)$a;
9880 $this->a = array();
9881 foreach ($a as $key => $value) {
9882 // Make sure conversion errors don't get displayed (results in '').
9883 if (is_array($value)) {
9884 $this->a[$key] = '';
9885 } else if (is_object($value)) {
9886 if (method_exists($value, '__toString')) {
9887 $this->a[$key] = $value->__toString();
9888 } else {
9889 $this->a[$key] = '';
9891 } else {
9892 $this->a[$key] = (string)$value;
9898 if (debugging(false, DEBUG_DEVELOPER)) {
9899 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9900 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9902 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9903 throw new coding_exception('Invalid string compontent. Please check your string definition');
9905 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9906 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9912 * Processes the string.
9914 * This function actually processes the string, stores it in the string property
9915 * and then returns it.
9916 * You will notice that this function is VERY similar to the get_string method.
9917 * That is because it is pretty much doing the same thing.
9918 * However as this function is an upgrade it isn't as tolerant to backwards
9919 * compatibility.
9921 * @return string
9922 * @throws coding_exception
9924 protected function get_string() {
9925 global $CFG;
9927 // Check if we need to process the string.
9928 if ($this->string === null) {
9929 // Check the quality of the identifier.
9930 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9931 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);
9934 // Process the string.
9935 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9936 // Debugging feature lets you display string identifier and component.
9937 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9938 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9941 // Return the string.
9942 return $this->string;
9946 * Returns the string
9948 * @param string $lang The langauge to use when processing the string
9949 * @return string
9951 public function out($lang = null) {
9952 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9953 if ($this->forcedstring) {
9954 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9955 return $this->get_string();
9957 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9958 return $translatedstring->out();
9960 return $this->get_string();
9964 * Magic __toString method for printing a string
9966 * @return string
9968 public function __toString() {
9969 return $this->get_string();
9973 * Magic __set_state method used for var_export
9975 * @return string
9977 public function __set_state() {
9978 return $this->get_string();
9982 * Prepares the lang_string for sleep and stores only the forcedstring and
9983 * string properties... the string cannot be regenerated so we need to ensure
9984 * it is generated for this.
9986 * @return string
9988 public function __sleep() {
9989 $this->get_string();
9990 $this->forcedstring = true;
9991 return array('forcedstring', 'string', 'lang');