MDL-52105 enrol_self: Fix wrong holdkey cap restriction for manager
[moodle.git] / lib / moodlelib.php
blob9e57b24751ae8f2bb3cd283a9fb8c789bd42ccae
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', 'radius', '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', "http://hubdirectory.moodle.org");
495 * Moodle.org url (should be moodle.org)
497 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
500 * Moodle mobile app service name
502 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
505 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
507 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
510 * Course display settings: display all sections on one page.
512 define('COURSE_DISPLAY_SINGLEPAGE', 0);
514 * Course display settings: split pages into a page per section.
516 define('COURSE_DISPLAY_MULTIPAGE', 1);
519 * Authentication constant: String used in password field when password is not stored.
521 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
523 // PARAMETER HANDLING.
526 * Returns a particular value for the named variable, taken from
527 * POST or GET. If the parameter doesn't exist then an error is
528 * thrown because we require this variable.
530 * This function should be used to initialise all required values
531 * in a script that are based on parameters. Usually it will be
532 * used like this:
533 * $id = required_param('id', PARAM_INT);
535 * Please note the $type parameter is now required and the value can not be array.
537 * @param string $parname the name of the page parameter we want
538 * @param string $type expected type of parameter
539 * @return mixed
540 * @throws coding_exception
542 function required_param($parname, $type) {
543 if (func_num_args() != 2 or empty($parname) or empty($type)) {
544 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
546 // POST has precedence.
547 if (isset($_POST[$parname])) {
548 $param = $_POST[$parname];
549 } else if (isset($_GET[$parname])) {
550 $param = $_GET[$parname];
551 } else {
552 print_error('missingparam', '', '', $parname);
555 if (is_array($param)) {
556 debugging('Invalid array parameter detected in required_param(): '.$parname);
557 // TODO: switch to fatal error in Moodle 2.3.
558 return required_param_array($parname, $type);
561 return clean_param($param, $type);
565 * Returns a particular array value for the named variable, taken from
566 * POST or GET. If the parameter doesn't exist then an error is
567 * thrown because we require this variable.
569 * This function should be used to initialise all required values
570 * in a script that are based on parameters. Usually it will be
571 * used like this:
572 * $ids = required_param_array('ids', PARAM_INT);
574 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
576 * @param string $parname the name of the page parameter we want
577 * @param string $type expected type of parameter
578 * @return array
579 * @throws coding_exception
581 function required_param_array($parname, $type) {
582 if (func_num_args() != 2 or empty($parname) or empty($type)) {
583 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
585 // POST has precedence.
586 if (isset($_POST[$parname])) {
587 $param = $_POST[$parname];
588 } else if (isset($_GET[$parname])) {
589 $param = $_GET[$parname];
590 } else {
591 print_error('missingparam', '', '', $parname);
593 if (!is_array($param)) {
594 print_error('missingparam', '', '', $parname);
597 $result = array();
598 foreach ($param as $key => $value) {
599 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
600 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
601 continue;
603 $result[$key] = clean_param($value, $type);
606 return $result;
610 * Returns a particular value for the named variable, taken from
611 * POST or GET, otherwise returning a given default.
613 * This function should be used to initialise all optional values
614 * in a script that are based on parameters. Usually it will be
615 * used like this:
616 * $name = optional_param('name', 'Fred', PARAM_TEXT);
618 * Please note the $type parameter is now required and the value can not be array.
620 * @param string $parname the name of the page parameter we want
621 * @param mixed $default the default value to return if nothing is found
622 * @param string $type expected type of parameter
623 * @return mixed
624 * @throws coding_exception
626 function optional_param($parname, $default, $type) {
627 if (func_num_args() != 3 or empty($parname) or empty($type)) {
628 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
631 // POST has precedence.
632 if (isset($_POST[$parname])) {
633 $param = $_POST[$parname];
634 } else if (isset($_GET[$parname])) {
635 $param = $_GET[$parname];
636 } else {
637 return $default;
640 if (is_array($param)) {
641 debugging('Invalid array parameter detected in required_param(): '.$parname);
642 // TODO: switch to $default in Moodle 2.3.
643 return optional_param_array($parname, $default, $type);
646 return clean_param($param, $type);
650 * Returns a particular array value for the named variable, taken from
651 * POST or GET, otherwise returning a given default.
653 * This function should be used to initialise all optional values
654 * in a script that are based on parameters. Usually it will be
655 * used like this:
656 * $ids = optional_param('id', array(), PARAM_INT);
658 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
660 * @param string $parname the name of the page parameter we want
661 * @param mixed $default the default value to return if nothing is found
662 * @param string $type expected type of parameter
663 * @return array
664 * @throws coding_exception
666 function optional_param_array($parname, $default, $type) {
667 if (func_num_args() != 3 or empty($parname) or empty($type)) {
668 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
671 // POST has precedence.
672 if (isset($_POST[$parname])) {
673 $param = $_POST[$parname];
674 } else if (isset($_GET[$parname])) {
675 $param = $_GET[$parname];
676 } else {
677 return $default;
679 if (!is_array($param)) {
680 debugging('optional_param_array() expects array parameters only: '.$parname);
681 return $default;
684 $result = array();
685 foreach ($param as $key => $value) {
686 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
687 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
688 continue;
690 $result[$key] = clean_param($value, $type);
693 return $result;
697 * Strict validation of parameter values, the values are only converted
698 * to requested PHP type. Internally it is using clean_param, the values
699 * before and after cleaning must be equal - otherwise
700 * an invalid_parameter_exception is thrown.
701 * Objects and classes are not accepted.
703 * @param mixed $param
704 * @param string $type PARAM_ constant
705 * @param bool $allownull are nulls valid value?
706 * @param string $debuginfo optional debug information
707 * @return mixed the $param value converted to PHP type
708 * @throws invalid_parameter_exception if $param is not of given type
710 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
711 if (is_null($param)) {
712 if ($allownull == NULL_ALLOWED) {
713 return null;
714 } else {
715 throw new invalid_parameter_exception($debuginfo);
718 if (is_array($param) or is_object($param)) {
719 throw new invalid_parameter_exception($debuginfo);
722 $cleaned = clean_param($param, $type);
724 if ($type == PARAM_FLOAT) {
725 // Do not detect precision loss here.
726 if (is_float($param) or is_int($param)) {
727 // These always fit.
728 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
729 throw new invalid_parameter_exception($debuginfo);
731 } else if ((string)$param !== (string)$cleaned) {
732 // Conversion to string is usually lossless.
733 throw new invalid_parameter_exception($debuginfo);
736 return $cleaned;
740 * Makes sure array contains only the allowed types, this function does not validate array key names!
742 * <code>
743 * $options = clean_param($options, PARAM_INT);
744 * </code>
746 * @param array $param the variable array we are cleaning
747 * @param string $type expected format of param after cleaning.
748 * @param bool $recursive clean recursive arrays
749 * @return array
750 * @throws coding_exception
752 function clean_param_array(array $param = null, $type, $recursive = false) {
753 // Convert null to empty array.
754 $param = (array)$param;
755 foreach ($param as $key => $value) {
756 if (is_array($value)) {
757 if ($recursive) {
758 $param[$key] = clean_param_array($value, $type, true);
759 } else {
760 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
762 } else {
763 $param[$key] = clean_param($value, $type);
766 return $param;
770 * Used by {@link optional_param()} and {@link required_param()} to
771 * clean the variables and/or cast to specific types, based on
772 * an options field.
773 * <code>
774 * $course->format = clean_param($course->format, PARAM_ALPHA);
775 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
776 * </code>
778 * @param mixed $param the variable we are cleaning
779 * @param string $type expected format of param after cleaning.
780 * @return mixed
781 * @throws coding_exception
783 function clean_param($param, $type) {
784 global $CFG;
786 if (is_array($param)) {
787 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
788 } else if (is_object($param)) {
789 if (method_exists($param, '__toString')) {
790 $param = $param->__toString();
791 } else {
792 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
796 switch ($type) {
797 case PARAM_RAW:
798 // No cleaning at all.
799 $param = fix_utf8($param);
800 return $param;
802 case PARAM_RAW_TRIMMED:
803 // No cleaning, but strip leading and trailing whitespace.
804 $param = fix_utf8($param);
805 return trim($param);
807 case PARAM_CLEAN:
808 // General HTML cleaning, try to use more specific type if possible this is deprecated!
809 // Please use more specific type instead.
810 if (is_numeric($param)) {
811 return $param;
813 $param = fix_utf8($param);
814 // Sweep for scripts, etc.
815 return clean_text($param);
817 case PARAM_CLEANHTML:
818 // Clean html fragment.
819 $param = fix_utf8($param);
820 // Sweep for scripts, etc.
821 $param = clean_text($param, FORMAT_HTML);
822 return trim($param);
824 case PARAM_INT:
825 // Convert to integer.
826 return (int)$param;
828 case PARAM_FLOAT:
829 // Convert to float.
830 return (float)$param;
832 case PARAM_ALPHA:
833 // Remove everything not `a-z`.
834 return preg_replace('/[^a-zA-Z]/i', '', $param);
836 case PARAM_ALPHAEXT:
837 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
838 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
840 case PARAM_ALPHANUM:
841 // Remove everything not `a-zA-Z0-9`.
842 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
844 case PARAM_ALPHANUMEXT:
845 // Remove everything not `a-zA-Z0-9_-`.
846 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
848 case PARAM_SEQUENCE:
849 // Remove everything not `0-9,`.
850 return preg_replace('/[^0-9,]/i', '', $param);
852 case PARAM_BOOL:
853 // Convert to 1 or 0.
854 $tempstr = strtolower($param);
855 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
856 $param = 1;
857 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
858 $param = 0;
859 } else {
860 $param = empty($param) ? 0 : 1;
862 return $param;
864 case PARAM_NOTAGS:
865 // Strip all tags.
866 $param = fix_utf8($param);
867 return strip_tags($param);
869 case PARAM_TEXT:
870 // Leave only tags needed for multilang.
871 $param = fix_utf8($param);
872 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
873 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
874 do {
875 if (strpos($param, '</lang>') !== false) {
876 // Old and future mutilang syntax.
877 $param = strip_tags($param, '<lang>');
878 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
879 break;
881 $open = false;
882 foreach ($matches[0] as $match) {
883 if ($match === '</lang>') {
884 if ($open) {
885 $open = false;
886 continue;
887 } else {
888 break 2;
891 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
892 break 2;
893 } else {
894 $open = true;
897 if ($open) {
898 break;
900 return $param;
902 } else if (strpos($param, '</span>') !== false) {
903 // Current problematic multilang syntax.
904 $param = strip_tags($param, '<span>');
905 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
906 break;
908 $open = false;
909 foreach ($matches[0] as $match) {
910 if ($match === '</span>') {
911 if ($open) {
912 $open = false;
913 continue;
914 } else {
915 break 2;
918 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
919 break 2;
920 } else {
921 $open = true;
924 if ($open) {
925 break;
927 return $param;
929 } while (false);
930 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
931 return strip_tags($param);
933 case PARAM_COMPONENT:
934 // We do not want any guessing here, either the name is correct or not
935 // please note only normalised component names are accepted.
936 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
937 return '';
939 if (strpos($param, '__') !== false) {
940 return '';
942 if (strpos($param, 'mod_') === 0) {
943 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
944 if (substr_count($param, '_') != 1) {
945 return '';
948 return $param;
950 case PARAM_PLUGIN:
951 case PARAM_AREA:
952 // We do not want any guessing here, either the name is correct or not.
953 if (!is_valid_plugin_name($param)) {
954 return '';
956 return $param;
958 case PARAM_SAFEDIR:
959 // Remove everything not a-zA-Z0-9_- .
960 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
962 case PARAM_SAFEPATH:
963 // Remove everything not a-zA-Z0-9/_- .
964 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
966 case PARAM_FILE:
967 // Strip all suspicious characters from filename.
968 $param = fix_utf8($param);
969 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
970 if ($param === '.' || $param === '..') {
971 $param = '';
973 return $param;
975 case PARAM_PATH:
976 // Strip all suspicious characters from file path.
977 $param = fix_utf8($param);
978 $param = str_replace('\\', '/', $param);
980 // Explode the path and clean each element using the PARAM_FILE rules.
981 $breadcrumb = explode('/', $param);
982 foreach ($breadcrumb as $key => $crumb) {
983 if ($crumb === '.' && $key === 0) {
984 // Special condition to allow for relative current path such as ./currentdirfile.txt.
985 } else {
986 $crumb = clean_param($crumb, PARAM_FILE);
988 $breadcrumb[$key] = $crumb;
990 $param = implode('/', $breadcrumb);
992 // Remove multiple current path (./././) and multiple slashes (///).
993 $param = preg_replace('~//+~', '/', $param);
994 $param = preg_replace('~/(\./)+~', '/', $param);
995 return $param;
997 case PARAM_HOST:
998 // Allow FQDN or IPv4 dotted quad.
999 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1000 // Match ipv4 dotted quad.
1001 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1002 // Confirm values are ok.
1003 if ( $match[0] > 255
1004 || $match[1] > 255
1005 || $match[3] > 255
1006 || $match[4] > 255 ) {
1007 // Hmmm, what kind of dotted quad is this?
1008 $param = '';
1010 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1011 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1012 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1014 // All is ok - $param is respected.
1015 } else {
1016 // All is not ok...
1017 $param='';
1019 return $param;
1021 case PARAM_URL: // Allow safe ftp, http, mailto urls.
1022 $param = fix_utf8($param);
1023 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1024 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1025 // All is ok, param is respected.
1026 } else {
1027 // Not really ok.
1028 $param ='';
1030 return $param;
1032 case PARAM_LOCALURL:
1033 // Allow http absolute, root relative and relative URLs within wwwroot.
1034 $param = clean_param($param, PARAM_URL);
1035 if (!empty($param)) {
1037 // Simulate the HTTPS version of the site.
1038 $httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot);
1040 if ($param === $CFG->wwwroot) {
1041 // Exact match;
1042 } else if (!empty($CFG->loginhttps) && $param === $httpswwwroot) {
1043 // Exact match;
1044 } else if (preg_match(':^/:', $param)) {
1045 // Root-relative, ok!
1046 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1047 // Absolute, and matches our wwwroot.
1048 } else if (!empty($CFG->loginhttps) && preg_match('/^' . preg_quote($httpswwwroot . '/', '/') . '/i', $param)) {
1049 // Absolute, and matches our httpswwwroot.
1050 } else {
1051 // Relative - let's make sure there are no tricks.
1052 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1053 // Looks ok.
1054 } else {
1055 $param = '';
1059 return $param;
1061 case PARAM_PEM:
1062 $param = trim($param);
1063 // PEM formatted strings may contain letters/numbers and the symbols:
1064 // forward slash: /
1065 // plus sign: +
1066 // equal sign: =
1067 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1068 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1069 list($wholething, $body) = $matches;
1070 unset($wholething, $matches);
1071 $b64 = clean_param($body, PARAM_BASE64);
1072 if (!empty($b64)) {
1073 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1074 } else {
1075 return '';
1078 return '';
1080 case PARAM_BASE64:
1081 if (!empty($param)) {
1082 // PEM formatted strings may contain letters/numbers and the symbols
1083 // forward slash: /
1084 // plus sign: +
1085 // equal sign: =.
1086 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1087 return '';
1089 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1090 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1091 // than (or equal to) 64 characters long.
1092 for ($i=0, $j=count($lines); $i < $j; $i++) {
1093 if ($i + 1 == $j) {
1094 if (64 < strlen($lines[$i])) {
1095 return '';
1097 continue;
1100 if (64 != strlen($lines[$i])) {
1101 return '';
1104 return implode("\n", $lines);
1105 } else {
1106 return '';
1109 case PARAM_TAG:
1110 $param = fix_utf8($param);
1111 // Please note it is not safe to use the tag name directly anywhere,
1112 // it must be processed with s(), urlencode() before embedding anywhere.
1113 // Remove some nasties.
1114 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1115 // Convert many whitespace chars into one.
1116 $param = preg_replace('/\s+/u', ' ', $param);
1117 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1118 return $param;
1120 case PARAM_TAGLIST:
1121 $param = fix_utf8($param);
1122 $tags = explode(',', $param);
1123 $result = array();
1124 foreach ($tags as $tag) {
1125 $res = clean_param($tag, PARAM_TAG);
1126 if ($res !== '') {
1127 $result[] = $res;
1130 if ($result) {
1131 return implode(',', $result);
1132 } else {
1133 return '';
1136 case PARAM_CAPABILITY:
1137 if (get_capability_info($param)) {
1138 return $param;
1139 } else {
1140 return '';
1143 case PARAM_PERMISSION:
1144 $param = (int)$param;
1145 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1146 return $param;
1147 } else {
1148 return CAP_INHERIT;
1151 case PARAM_AUTH:
1152 $param = clean_param($param, PARAM_PLUGIN);
1153 if (empty($param)) {
1154 return '';
1155 } else if (exists_auth_plugin($param)) {
1156 return $param;
1157 } else {
1158 return '';
1161 case PARAM_LANG:
1162 $param = clean_param($param, PARAM_SAFEDIR);
1163 if (get_string_manager()->translation_exists($param)) {
1164 return $param;
1165 } else {
1166 // Specified language is not installed or param malformed.
1167 return '';
1170 case PARAM_THEME:
1171 $param = clean_param($param, PARAM_PLUGIN);
1172 if (empty($param)) {
1173 return '';
1174 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1175 return $param;
1176 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1177 return $param;
1178 } else {
1179 // Specified theme is not installed.
1180 return '';
1183 case PARAM_USERNAME:
1184 $param = fix_utf8($param);
1185 $param = trim($param);
1186 // Convert uppercase to lowercase MDL-16919.
1187 $param = core_text::strtolower($param);
1188 if (empty($CFG->extendedusernamechars)) {
1189 $param = str_replace(" " , "", $param);
1190 // Regular expression, eliminate all chars EXCEPT:
1191 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1192 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1194 return $param;
1196 case PARAM_EMAIL:
1197 $param = fix_utf8($param);
1198 if (validate_email($param)) {
1199 return $param;
1200 } else {
1201 return '';
1204 case PARAM_STRINGID:
1205 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1206 return $param;
1207 } else {
1208 return '';
1211 case PARAM_TIMEZONE:
1212 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1213 $param = fix_utf8($param);
1214 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1215 if (preg_match($timezonepattern, $param)) {
1216 return $param;
1217 } else {
1218 return '';
1221 default:
1222 // Doh! throw error, switched parameters in optional_param or another serious problem.
1223 print_error("unknownparamtype", '', '', $type);
1228 * Makes sure the data is using valid utf8, invalid characters are discarded.
1230 * Note: this function is not intended for full objects with methods and private properties.
1232 * @param mixed $value
1233 * @return mixed with proper utf-8 encoding
1235 function fix_utf8($value) {
1236 if (is_null($value) or $value === '') {
1237 return $value;
1239 } else if (is_string($value)) {
1240 if ((string)(int)$value === $value) {
1241 // Shortcut.
1242 return $value;
1244 // No null bytes expected in our data, so let's remove it.
1245 $value = str_replace("\0", '', $value);
1247 // Note: this duplicates min_fix_utf8() intentionally.
1248 static $buggyiconv = null;
1249 if ($buggyiconv === null) {
1250 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1253 if ($buggyiconv) {
1254 if (function_exists('mb_convert_encoding')) {
1255 $subst = mb_substitute_character();
1256 mb_substitute_character('');
1257 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1258 mb_substitute_character($subst);
1260 } else {
1261 // Warn admins on admin/index.php page.
1262 $result = $value;
1265 } else {
1266 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1269 return $result;
1271 } else if (is_array($value)) {
1272 foreach ($value as $k => $v) {
1273 $value[$k] = fix_utf8($v);
1275 return $value;
1277 } else if (is_object($value)) {
1278 // Do not modify original.
1279 $value = clone($value);
1280 foreach ($value as $k => $v) {
1281 $value->$k = fix_utf8($v);
1283 return $value;
1285 } else {
1286 // This is some other type, no utf-8 here.
1287 return $value;
1292 * Return true if given value is integer or string with integer value
1294 * @param mixed $value String or Int
1295 * @return bool true if number, false if not
1297 function is_number($value) {
1298 if (is_int($value)) {
1299 return true;
1300 } else if (is_string($value)) {
1301 return ((string)(int)$value) === $value;
1302 } else {
1303 return false;
1308 * Returns host part from url.
1310 * @param string $url full url
1311 * @return string host, null if not found
1313 function get_host_from_url($url) {
1314 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1315 if ($matches) {
1316 return $matches[1];
1318 return null;
1322 * Tests whether anything was returned by text editor
1324 * This function is useful for testing whether something you got back from
1325 * the HTML editor actually contains anything. Sometimes the HTML editor
1326 * appear to be empty, but actually you get back a <br> tag or something.
1328 * @param string $string a string containing HTML.
1329 * @return boolean does the string contain any actual content - that is text,
1330 * images, objects, etc.
1332 function html_is_blank($string) {
1333 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1337 * Set a key in global configuration
1339 * Set a key/value pair in both this session's {@link $CFG} global variable
1340 * and in the 'config' database table for future sessions.
1342 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1343 * In that case it doesn't affect $CFG.
1345 * A NULL value will delete the entry.
1347 * NOTE: this function is called from lib/db/upgrade.php
1349 * @param string $name the key to set
1350 * @param string $value the value to set (without magic quotes)
1351 * @param string $plugin (optional) the plugin scope, default null
1352 * @return bool true or exception
1354 function set_config($name, $value, $plugin=null) {
1355 global $CFG, $DB;
1357 if (empty($plugin)) {
1358 if (!array_key_exists($name, $CFG->config_php_settings)) {
1359 // So it's defined for this invocation at least.
1360 if (is_null($value)) {
1361 unset($CFG->$name);
1362 } else {
1363 // Settings from db are always strings.
1364 $CFG->$name = (string)$value;
1368 if ($DB->get_field('config', 'name', array('name' => $name))) {
1369 if ($value === null) {
1370 $DB->delete_records('config', array('name' => $name));
1371 } else {
1372 $DB->set_field('config', 'value', $value, array('name' => $name));
1374 } else {
1375 if ($value !== null) {
1376 $config = new stdClass();
1377 $config->name = $name;
1378 $config->value = $value;
1379 $DB->insert_record('config', $config, false);
1382 if ($name === 'siteidentifier') {
1383 cache_helper::update_site_identifier($value);
1385 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1386 } else {
1387 // Plugin scope.
1388 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1389 if ($value===null) {
1390 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1391 } else {
1392 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1394 } else {
1395 if ($value !== null) {
1396 $config = new stdClass();
1397 $config->plugin = $plugin;
1398 $config->name = $name;
1399 $config->value = $value;
1400 $DB->insert_record('config_plugins', $config, false);
1403 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1406 return true;
1410 * Get configuration values from the global config table
1411 * or the config_plugins table.
1413 * If called with one parameter, it will load all the config
1414 * variables for one plugin, and return them as an object.
1416 * If called with 2 parameters it will return a string single
1417 * value or false if the value is not found.
1419 * NOTE: this function is called from lib/db/upgrade.php
1421 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1422 * that we need only fetch it once per request.
1423 * @param string $plugin full component name
1424 * @param string $name default null
1425 * @return mixed hash-like object or single value, return false no config found
1426 * @throws dml_exception
1428 function get_config($plugin, $name = null) {
1429 global $CFG, $DB;
1431 static $siteidentifier = null;
1433 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1434 $forced =& $CFG->config_php_settings;
1435 $iscore = true;
1436 $plugin = 'core';
1437 } else {
1438 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1439 $forced =& $CFG->forced_plugin_settings[$plugin];
1440 } else {
1441 $forced = array();
1443 $iscore = false;
1446 if ($siteidentifier === null) {
1447 try {
1448 // This may fail during installation.
1449 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1450 // install the database.
1451 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1452 } catch (dml_exception $ex) {
1453 // Set siteidentifier to false. We don't want to trip this continually.
1454 $siteidentifier = false;
1455 throw $ex;
1459 if (!empty($name)) {
1460 if (array_key_exists($name, $forced)) {
1461 return (string)$forced[$name];
1462 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1463 return $siteidentifier;
1467 $cache = cache::make('core', 'config');
1468 $result = $cache->get($plugin);
1469 if ($result === false) {
1470 // The user is after a recordset.
1471 if (!$iscore) {
1472 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1473 } else {
1474 // This part is not really used any more, but anyway...
1475 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1477 $cache->set($plugin, $result);
1480 if (!empty($name)) {
1481 if (array_key_exists($name, $result)) {
1482 return $result[$name];
1484 return false;
1487 if ($plugin === 'core') {
1488 $result['siteidentifier'] = $siteidentifier;
1491 foreach ($forced as $key => $value) {
1492 if (is_null($value) or is_array($value) or is_object($value)) {
1493 // We do not want any extra mess here, just real settings that could be saved in db.
1494 unset($result[$key]);
1495 } else {
1496 // Convert to string as if it went through the DB.
1497 $result[$key] = (string)$value;
1501 return (object)$result;
1505 * Removes a key from global configuration.
1507 * NOTE: this function is called from lib/db/upgrade.php
1509 * @param string $name the key to set
1510 * @param string $plugin (optional) the plugin scope
1511 * @return boolean whether the operation succeeded.
1513 function unset_config($name, $plugin=null) {
1514 global $CFG, $DB;
1516 if (empty($plugin)) {
1517 unset($CFG->$name);
1518 $DB->delete_records('config', array('name' => $name));
1519 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1520 } else {
1521 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1522 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1525 return true;
1529 * Remove all the config variables for a given plugin.
1531 * NOTE: this function is called from lib/db/upgrade.php
1533 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1534 * @return boolean whether the operation succeeded.
1536 function unset_all_config_for_plugin($plugin) {
1537 global $DB;
1538 // Delete from the obvious config_plugins first.
1539 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1540 // Next delete any suspect settings from config.
1541 $like = $DB->sql_like('name', '?', true, true, false, '|');
1542 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1543 $DB->delete_records_select('config', $like, $params);
1544 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1545 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1547 return true;
1551 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1553 * All users are verified if they still have the necessary capability.
1555 * @param string $value the value of the config setting.
1556 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1557 * @param bool $includeadmins include administrators.
1558 * @return array of user objects.
1560 function get_users_from_config($value, $capability, $includeadmins = true) {
1561 if (empty($value) or $value === '$@NONE@$') {
1562 return array();
1565 // We have to make sure that users still have the necessary capability,
1566 // it should be faster to fetch them all first and then test if they are present
1567 // instead of validating them one-by-one.
1568 $users = get_users_by_capability(context_system::instance(), $capability);
1569 if ($includeadmins) {
1570 $admins = get_admins();
1571 foreach ($admins as $admin) {
1572 $users[$admin->id] = $admin;
1576 if ($value === '$@ALL@$') {
1577 return $users;
1580 $result = array(); // Result in correct order.
1581 $allowed = explode(',', $value);
1582 foreach ($allowed as $uid) {
1583 if (isset($users[$uid])) {
1584 $user = $users[$uid];
1585 $result[$user->id] = $user;
1589 return $result;
1594 * Invalidates browser caches and cached data in temp.
1596 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1597 * {@link phpunit_util::reset_dataroot()}
1599 * @return void
1601 function purge_all_caches() {
1602 global $CFG, $DB;
1604 reset_text_filters_cache();
1605 js_reset_all_caches();
1606 theme_reset_all_caches();
1607 get_string_manager()->reset_caches();
1608 core_text::reset_caches();
1609 if (class_exists('core_plugin_manager')) {
1610 core_plugin_manager::reset_caches();
1613 // Bump up cacherev field for all courses.
1614 try {
1615 increment_revision_number('course', 'cacherev', '');
1616 } catch (moodle_exception $e) {
1617 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1620 $DB->reset_caches();
1621 cache_helper::purge_all();
1623 // Purge all other caches: rss, simplepie, etc.
1624 remove_dir($CFG->cachedir.'', true);
1626 // Make sure cache dir is writable, throws exception if not.
1627 make_cache_directory('');
1629 // This is the only place where we purge local caches, we are only adding files there.
1630 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1631 remove_dir($CFG->localcachedir, true);
1632 set_config('localcachedirpurged', time());
1633 make_localcache_directory('', true);
1634 \core\task\manager::clear_static_caches();
1638 * Get volatile flags
1640 * @param string $type
1641 * @param int $changedsince default null
1642 * @return array records array
1644 function get_cache_flags($type, $changedsince = null) {
1645 global $DB;
1647 $params = array('type' => $type, 'expiry' => time());
1648 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1649 if ($changedsince !== null) {
1650 $params['changedsince'] = $changedsince;
1651 $sqlwhere .= " AND timemodified > :changedsince";
1653 $cf = array();
1654 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1655 foreach ($flags as $flag) {
1656 $cf[$flag->name] = $flag->value;
1659 return $cf;
1663 * Get volatile flags
1665 * @param string $type
1666 * @param string $name
1667 * @param int $changedsince default null
1668 * @return string|false The cache flag value or false
1670 function get_cache_flag($type, $name, $changedsince=null) {
1671 global $DB;
1673 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1675 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1676 if ($changedsince !== null) {
1677 $params['changedsince'] = $changedsince;
1678 $sqlwhere .= " AND timemodified > :changedsince";
1681 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1685 * Set a volatile flag
1687 * @param string $type the "type" namespace for the key
1688 * @param string $name the key to set
1689 * @param string $value the value to set (without magic quotes) - null will remove the flag
1690 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1691 * @return bool Always returns true
1693 function set_cache_flag($type, $name, $value, $expiry = null) {
1694 global $DB;
1696 $timemodified = time();
1697 if ($expiry === null || $expiry < $timemodified) {
1698 $expiry = $timemodified + 24 * 60 * 60;
1699 } else {
1700 $expiry = (int)$expiry;
1703 if ($value === null) {
1704 unset_cache_flag($type, $name);
1705 return true;
1708 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1709 // This is a potential problem in DEBUG_DEVELOPER.
1710 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1711 return true; // No need to update.
1713 $f->value = $value;
1714 $f->expiry = $expiry;
1715 $f->timemodified = $timemodified;
1716 $DB->update_record('cache_flags', $f);
1717 } else {
1718 $f = new stdClass();
1719 $f->flagtype = $type;
1720 $f->name = $name;
1721 $f->value = $value;
1722 $f->expiry = $expiry;
1723 $f->timemodified = $timemodified;
1724 $DB->insert_record('cache_flags', $f);
1726 return true;
1730 * Removes a single volatile flag
1732 * @param string $type the "type" namespace for the key
1733 * @param string $name the key to set
1734 * @return bool
1736 function unset_cache_flag($type, $name) {
1737 global $DB;
1738 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1739 return true;
1743 * Garbage-collect volatile flags
1745 * @return bool Always returns true
1747 function gc_cache_flags() {
1748 global $DB;
1749 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1750 return true;
1753 // USER PREFERENCE API.
1756 * Refresh user preference cache. This is used most often for $USER
1757 * object that is stored in session, but it also helps with performance in cron script.
1759 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1761 * @package core
1762 * @category preference
1763 * @access public
1764 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1765 * @param int $cachelifetime Cache life time on the current page (in seconds)
1766 * @throws coding_exception
1767 * @return null
1769 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1770 global $DB;
1771 // Static cache, we need to check on each page load, not only every 2 minutes.
1772 static $loadedusers = array();
1774 if (!isset($user->id)) {
1775 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1778 if (empty($user->id) or isguestuser($user->id)) {
1779 // No permanent storage for not-logged-in users and guest.
1780 if (!isset($user->preference)) {
1781 $user->preference = array();
1783 return;
1786 $timenow = time();
1788 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1789 // Already loaded at least once on this page. Are we up to date?
1790 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1791 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1792 return;
1794 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1795 // No change since the lastcheck on this page.
1796 $user->preference['_lastloaded'] = $timenow;
1797 return;
1801 // OK, so we have to reload all preferences.
1802 $loadedusers[$user->id] = true;
1803 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1804 $user->preference['_lastloaded'] = $timenow;
1808 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1810 * NOTE: internal function, do not call from other code.
1812 * @package core
1813 * @access private
1814 * @param integer $userid the user whose prefs were changed.
1816 function mark_user_preferences_changed($userid) {
1817 global $CFG;
1819 if (empty($userid) or isguestuser($userid)) {
1820 // No cache flags for guest and not-logged-in users.
1821 return;
1824 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1828 * Sets a preference for the specified user.
1830 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1832 * @package core
1833 * @category preference
1834 * @access public
1835 * @param string $name The key to set as preference for the specified user
1836 * @param string $value The value to set for the $name key in the specified user's
1837 * record, null means delete current value.
1838 * @param stdClass|int|null $user A moodle user object or id, null means current user
1839 * @throws coding_exception
1840 * @return bool Always true or exception
1842 function set_user_preference($name, $value, $user = null) {
1843 global $USER, $DB;
1845 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1846 throw new coding_exception('Invalid preference name in set_user_preference() call');
1849 if (is_null($value)) {
1850 // Null means delete current.
1851 return unset_user_preference($name, $user);
1852 } else if (is_object($value)) {
1853 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1854 } else if (is_array($value)) {
1855 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1857 // Value column maximum length is 1333 characters.
1858 $value = (string)$value;
1859 if (core_text::strlen($value) > 1333) {
1860 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1863 if (is_null($user)) {
1864 $user = $USER;
1865 } else if (isset($user->id)) {
1866 // It is a valid object.
1867 } else if (is_numeric($user)) {
1868 $user = (object)array('id' => (int)$user);
1869 } else {
1870 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1873 check_user_preferences_loaded($user);
1875 if (empty($user->id) or isguestuser($user->id)) {
1876 // No permanent storage for not-logged-in users and guest.
1877 $user->preference[$name] = $value;
1878 return true;
1881 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1882 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1883 // Preference already set to this value.
1884 return true;
1886 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1888 } else {
1889 $preference = new stdClass();
1890 $preference->userid = $user->id;
1891 $preference->name = $name;
1892 $preference->value = $value;
1893 $DB->insert_record('user_preferences', $preference);
1896 // Update value in cache.
1897 $user->preference[$name] = $value;
1899 // Set reload flag for other sessions.
1900 mark_user_preferences_changed($user->id);
1902 return true;
1906 * Sets a whole array of preferences for the current user
1908 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1910 * @package core
1911 * @category preference
1912 * @access public
1913 * @param array $prefarray An array of key/value pairs to be set
1914 * @param stdClass|int|null $user A moodle user object or id, null means current user
1915 * @return bool Always true or exception
1917 function set_user_preferences(array $prefarray, $user = null) {
1918 foreach ($prefarray as $name => $value) {
1919 set_user_preference($name, $value, $user);
1921 return true;
1925 * Unsets a preference completely by deleting it from the database
1927 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1929 * @package core
1930 * @category preference
1931 * @access public
1932 * @param string $name The key to unset as preference for the specified user
1933 * @param stdClass|int|null $user A moodle user object or id, null means current user
1934 * @throws coding_exception
1935 * @return bool Always true or exception
1937 function unset_user_preference($name, $user = null) {
1938 global $USER, $DB;
1940 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1941 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1944 if (is_null($user)) {
1945 $user = $USER;
1946 } else if (isset($user->id)) {
1947 // It is a valid object.
1948 } else if (is_numeric($user)) {
1949 $user = (object)array('id' => (int)$user);
1950 } else {
1951 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1954 check_user_preferences_loaded($user);
1956 if (empty($user->id) or isguestuser($user->id)) {
1957 // No permanent storage for not-logged-in user and guest.
1958 unset($user->preference[$name]);
1959 return true;
1962 // Delete from DB.
1963 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1965 // Delete the preference from cache.
1966 unset($user->preference[$name]);
1968 // Set reload flag for other sessions.
1969 mark_user_preferences_changed($user->id);
1971 return true;
1975 * Used to fetch user preference(s)
1977 * If no arguments are supplied this function will return
1978 * all of the current user preferences as an array.
1980 * If a name is specified then this function
1981 * attempts to return that particular preference value. If
1982 * none is found, then the optional value $default is returned,
1983 * otherwise null.
1985 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1987 * @package core
1988 * @category preference
1989 * @access public
1990 * @param string $name Name of the key to use in finding a preference value
1991 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1992 * @param stdClass|int|null $user A moodle user object or id, null means current user
1993 * @throws coding_exception
1994 * @return string|mixed|null A string containing the value of a single preference. An
1995 * array with all of the preferences or null
1997 function get_user_preferences($name = null, $default = null, $user = null) {
1998 global $USER;
2000 if (is_null($name)) {
2001 // All prefs.
2002 } else if (is_numeric($name) or $name === '_lastloaded') {
2003 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2006 if (is_null($user)) {
2007 $user = $USER;
2008 } else if (isset($user->id)) {
2009 // Is a valid object.
2010 } else if (is_numeric($user)) {
2011 $user = (object)array('id' => (int)$user);
2012 } else {
2013 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2016 check_user_preferences_loaded($user);
2018 if (empty($name)) {
2019 // All values.
2020 return $user->preference;
2021 } else if (isset($user->preference[$name])) {
2022 // The single string value.
2023 return $user->preference[$name];
2024 } else {
2025 // Default value (null if not specified).
2026 return $default;
2030 // FUNCTIONS FOR HANDLING TIME.
2033 * Given Gregorian date parts in user time produce a GMT timestamp.
2035 * @package core
2036 * @category time
2037 * @param int $year The year part to create timestamp of
2038 * @param int $month The month part to create timestamp of
2039 * @param int $day The day part to create timestamp of
2040 * @param int $hour The hour part to create timestamp of
2041 * @param int $minute The minute part to create timestamp of
2042 * @param int $second The second part to create timestamp of
2043 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2044 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2045 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2046 * applied only if timezone is 99 or string.
2047 * @return int GMT timestamp
2049 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2050 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2051 $date->setDate((int)$year, (int)$month, (int)$day);
2052 $date->setTime((int)$hour, (int)$minute, (int)$second);
2054 $time = $date->getTimestamp();
2056 if ($time === false) {
2057 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2058 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2061 // Moodle BC DST stuff.
2062 if (!$applydst) {
2063 $time += dst_offset_on($time, $timezone);
2066 return $time;
2071 * Format a date/time (seconds) as weeks, days, hours etc as needed
2073 * Given an amount of time in seconds, returns string
2074 * formatted nicely as weeks, days, hours etc as needed
2076 * @package core
2077 * @category time
2078 * @uses MINSECS
2079 * @uses HOURSECS
2080 * @uses DAYSECS
2081 * @uses YEARSECS
2082 * @param int $totalsecs Time in seconds
2083 * @param stdClass $str Should be a time object
2084 * @return string A nicely formatted date/time string
2086 function format_time($totalsecs, $str = null) {
2088 $totalsecs = abs($totalsecs);
2090 if (!$str) {
2091 // Create the str structure the slow way.
2092 $str = new stdClass();
2093 $str->day = get_string('day');
2094 $str->days = get_string('days');
2095 $str->hour = get_string('hour');
2096 $str->hours = get_string('hours');
2097 $str->min = get_string('min');
2098 $str->mins = get_string('mins');
2099 $str->sec = get_string('sec');
2100 $str->secs = get_string('secs');
2101 $str->year = get_string('year');
2102 $str->years = get_string('years');
2105 $years = floor($totalsecs/YEARSECS);
2106 $remainder = $totalsecs - ($years*YEARSECS);
2107 $days = floor($remainder/DAYSECS);
2108 $remainder = $totalsecs - ($days*DAYSECS);
2109 $hours = floor($remainder/HOURSECS);
2110 $remainder = $remainder - ($hours*HOURSECS);
2111 $mins = floor($remainder/MINSECS);
2112 $secs = $remainder - ($mins*MINSECS);
2114 $ss = ($secs == 1) ? $str->sec : $str->secs;
2115 $sm = ($mins == 1) ? $str->min : $str->mins;
2116 $sh = ($hours == 1) ? $str->hour : $str->hours;
2117 $sd = ($days == 1) ? $str->day : $str->days;
2118 $sy = ($years == 1) ? $str->year : $str->years;
2120 $oyears = '';
2121 $odays = '';
2122 $ohours = '';
2123 $omins = '';
2124 $osecs = '';
2126 if ($years) {
2127 $oyears = $years .' '. $sy;
2129 if ($days) {
2130 $odays = $days .' '. $sd;
2132 if ($hours) {
2133 $ohours = $hours .' '. $sh;
2135 if ($mins) {
2136 $omins = $mins .' '. $sm;
2138 if ($secs) {
2139 $osecs = $secs .' '. $ss;
2142 if ($years) {
2143 return trim($oyears .' '. $odays);
2145 if ($days) {
2146 return trim($odays .' '. $ohours);
2148 if ($hours) {
2149 return trim($ohours .' '. $omins);
2151 if ($mins) {
2152 return trim($omins .' '. $osecs);
2154 if ($secs) {
2155 return $osecs;
2157 return get_string('now');
2161 * Returns a formatted string that represents a date in user time.
2163 * @package core
2164 * @category time
2165 * @param int $date the timestamp in UTC, as obtained from the database.
2166 * @param string $format strftime format. You should probably get this using
2167 * get_string('strftime...', 'langconfig');
2168 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2169 * not 99 then daylight saving will not be added.
2170 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2171 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2172 * If false then the leading zero is maintained.
2173 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2174 * @return string the formatted date/time.
2176 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2177 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2178 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2182 * Returns a formatted date ensuring it is UTF-8.
2184 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2185 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2187 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2188 * @param string $format strftime format.
2189 * @param int|float|string $tz the user timezone
2190 * @return string the formatted date/time.
2191 * @since Moodle 2.3.3
2193 function date_format_string($date, $format, $tz = 99) {
2194 global $CFG;
2196 $localewincharset = null;
2197 // Get the calendar type user is using.
2198 if ($CFG->ostype == 'WINDOWS') {
2199 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2200 $localewincharset = $calendartype->locale_win_charset();
2203 if ($localewincharset) {
2204 $format = core_text::convert($format, 'utf-8', $localewincharset);
2207 date_default_timezone_set(core_date::get_user_timezone($tz));
2208 $datestring = strftime($format, $date);
2209 core_date::set_default_server_timezone();
2211 if ($localewincharset) {
2212 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2215 return $datestring;
2219 * Given a $time timestamp in GMT (seconds since epoch),
2220 * returns an array that represents the Gregorian date in user time
2222 * @package core
2223 * @category time
2224 * @param int $time Timestamp in GMT
2225 * @param float|int|string $timezone user timezone
2226 * @return array An array that represents the date in user time
2228 function usergetdate($time, $timezone=99) {
2229 date_default_timezone_set(core_date::get_user_timezone($timezone));
2230 $result = getdate($time);
2231 core_date::set_default_server_timezone();
2233 return $result;
2237 * Given a GMT timestamp (seconds since epoch), offsets it by
2238 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2240 * NOTE: this function does not include DST properly,
2241 * you should use the PHP date stuff instead!
2243 * @package core
2244 * @category time
2245 * @param int $date Timestamp in GMT
2246 * @param float|int|string $timezone user timezone
2247 * @return int
2249 function usertime($date, $timezone=99) {
2250 $userdate = new DateTime('@' . $date);
2251 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2252 $dst = dst_offset_on($date, $timezone);
2254 return $date - $userdate->getOffset() + $dst;
2258 * Given a time, return the GMT timestamp of the most recent midnight
2259 * for the current user.
2261 * @package core
2262 * @category time
2263 * @param int $date Timestamp in GMT
2264 * @param float|int|string $timezone user timezone
2265 * @return int Returns a GMT timestamp
2267 function usergetmidnight($date, $timezone=99) {
2269 $userdate = usergetdate($date, $timezone);
2271 // Time of midnight of this user's day, in GMT.
2272 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2277 * Returns a string that prints the user's timezone
2279 * @package core
2280 * @category time
2281 * @param float|int|string $timezone user timezone
2282 * @return string
2284 function usertimezone($timezone=99) {
2285 $tz = core_date::get_user_timezone($timezone);
2286 return core_date::get_localised_timezone($tz);
2290 * Returns a float or a string which denotes the user's timezone
2291 * 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)
2292 * means that for this timezone there are also DST rules to be taken into account
2293 * Checks various settings and picks the most dominant of those which have a value
2295 * @package core
2296 * @category time
2297 * @param float|int|string $tz timezone to calculate GMT time offset before
2298 * calculating user timezone, 99 is default user timezone
2299 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2300 * @return float|string
2302 function get_user_timezone($tz = 99) {
2303 global $USER, $CFG;
2305 $timezones = array(
2306 $tz,
2307 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2308 isset($USER->timezone) ? $USER->timezone : 99,
2309 isset($CFG->timezone) ? $CFG->timezone : 99,
2312 $tz = 99;
2314 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2315 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2316 $tz = $next['value'];
2318 return is_numeric($tz) ? (float) $tz : $tz;
2322 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2323 * - Note: Daylight saving only works for string timezones and not for float.
2325 * @package core
2326 * @category time
2327 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2328 * @param int|float|string $strtimezone user timezone
2329 * @return int
2331 function dst_offset_on($time, $strtimezone = null) {
2332 $tz = core_date::get_user_timezone($strtimezone);
2333 $date = new DateTime('@' . $time);
2334 $date->setTimezone(new DateTimeZone($tz));
2335 if ($date->format('I') == '1') {
2336 if ($tz === 'Australia/Lord_Howe') {
2337 return 1800;
2339 return 3600;
2341 return 0;
2345 * Calculates when the day appears in specific month
2347 * @package core
2348 * @category time
2349 * @param int $startday starting day of the month
2350 * @param int $weekday The day when week starts (normally taken from user preferences)
2351 * @param int $month The month whose day is sought
2352 * @param int $year The year of the month whose day is sought
2353 * @return int
2355 function find_day_in_month($startday, $weekday, $month, $year) {
2356 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2358 $daysinmonth = days_in_month($month, $year);
2359 $daysinweek = count($calendartype->get_weekdays());
2361 if ($weekday == -1) {
2362 // Don't care about weekday, so return:
2363 // abs($startday) if $startday != -1
2364 // $daysinmonth otherwise.
2365 return ($startday == -1) ? $daysinmonth : abs($startday);
2368 // From now on we 're looking for a specific weekday.
2369 // Give "end of month" its actual value, since we know it.
2370 if ($startday == -1) {
2371 $startday = -1 * $daysinmonth;
2374 // Starting from day $startday, the sign is the direction.
2375 if ($startday < 1) {
2376 $startday = abs($startday);
2377 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2379 // This is the last such weekday of the month.
2380 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2381 if ($lastinmonth > $daysinmonth) {
2382 $lastinmonth -= $daysinweek;
2385 // Find the first such weekday <= $startday.
2386 while ($lastinmonth > $startday) {
2387 $lastinmonth -= $daysinweek;
2390 return $lastinmonth;
2391 } else {
2392 $indexweekday = dayofweek($startday, $month, $year);
2394 $diff = $weekday - $indexweekday;
2395 if ($diff < 0) {
2396 $diff += $daysinweek;
2399 // This is the first such weekday of the month equal to or after $startday.
2400 $firstfromindex = $startday + $diff;
2402 return $firstfromindex;
2407 * Calculate the number of days in a given month
2409 * @package core
2410 * @category time
2411 * @param int $month The month whose day count is sought
2412 * @param int $year The year of the month whose day count is sought
2413 * @return int
2415 function days_in_month($month, $year) {
2416 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2417 return $calendartype->get_num_days_in_month($year, $month);
2421 * Calculate the position in the week of a specific calendar day
2423 * @package core
2424 * @category time
2425 * @param int $day The day of the date whose position in the week is sought
2426 * @param int $month The month of the date whose position in the week is sought
2427 * @param int $year The year of the date whose position in the week is sought
2428 * @return int
2430 function dayofweek($day, $month, $year) {
2431 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2432 return $calendartype->get_weekday($year, $month, $day);
2435 // USER AUTHENTICATION AND LOGIN.
2438 * Returns full login url.
2440 * @return string login url
2442 function get_login_url() {
2443 global $CFG;
2445 $url = "$CFG->wwwroot/login/index.php";
2447 if (!empty($CFG->loginhttps)) {
2448 $url = str_replace('http:', 'https:', $url);
2451 return $url;
2455 * This function checks that the current user is logged in and has the
2456 * required privileges
2458 * This function checks that the current user is logged in, and optionally
2459 * whether they are allowed to be in a particular course and view a particular
2460 * course module.
2461 * If they are not logged in, then it redirects them to the site login unless
2462 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2463 * case they are automatically logged in as guests.
2464 * If $courseid is given and the user is not enrolled in that course then the
2465 * user is redirected to the course enrolment page.
2466 * If $cm is given and the course module is hidden and the user is not a teacher
2467 * in the course then the user is redirected to the course home page.
2469 * When $cm parameter specified, this function sets page layout to 'module'.
2470 * You need to change it manually later if some other layout needed.
2472 * @package core_access
2473 * @category access
2475 * @param mixed $courseorid id of the course or course object
2476 * @param bool $autologinguest default true
2477 * @param object $cm course module object
2478 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2479 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2480 * in order to keep redirects working properly. MDL-14495
2481 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2482 * @return mixed Void, exit, and die depending on path
2483 * @throws coding_exception
2484 * @throws require_login_exception
2486 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2487 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2489 // Must not redirect when byteserving already started.
2490 if (!empty($_SERVER['HTTP_RANGE'])) {
2491 $preventredirect = true;
2494 if (AJAX_SCRIPT) {
2495 // We cannot redirect for AJAX scripts either.
2496 $preventredirect = true;
2499 // Setup global $COURSE, themes, language and locale.
2500 if (!empty($courseorid)) {
2501 if (is_object($courseorid)) {
2502 $course = $courseorid;
2503 } else if ($courseorid == SITEID) {
2504 $course = clone($SITE);
2505 } else {
2506 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2508 if ($cm) {
2509 if ($cm->course != $course->id) {
2510 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2512 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2513 if (!($cm instanceof cm_info)) {
2514 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2515 // db queries so this is not really a performance concern, however it is obviously
2516 // better if you use get_fast_modinfo to get the cm before calling this.
2517 $modinfo = get_fast_modinfo($course);
2518 $cm = $modinfo->get_cm($cm->id);
2521 } else {
2522 // Do not touch global $COURSE via $PAGE->set_course(),
2523 // the reasons is we need to be able to call require_login() at any time!!
2524 $course = $SITE;
2525 if ($cm) {
2526 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2530 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2531 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2532 // risk leading the user back to the AJAX request URL.
2533 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2534 $setwantsurltome = false;
2537 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2538 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2539 if ($preventredirect) {
2540 throw new require_login_session_timeout_exception();
2541 } else {
2542 if ($setwantsurltome) {
2543 $SESSION->wantsurl = qualified_me();
2545 redirect(get_login_url());
2549 // If the user is not even logged in yet then make sure they are.
2550 if (!isloggedin()) {
2551 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2552 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2553 // Misconfigured site guest, just redirect to login page.
2554 redirect(get_login_url());
2555 exit; // Never reached.
2557 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2558 complete_user_login($guest);
2559 $USER->autologinguest = true;
2560 $SESSION->lang = $lang;
2561 } else {
2562 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2563 if ($preventredirect) {
2564 throw new require_login_exception('You are not logged in');
2567 if ($setwantsurltome) {
2568 $SESSION->wantsurl = qualified_me();
2571 $referer = get_local_referer(false);
2572 if (!empty($referer)) {
2573 $SESSION->fromurl = $referer;
2576 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2577 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2578 foreach($authsequence as $authname) {
2579 $authplugin = get_auth_plugin($authname);
2580 $authplugin->pre_loginpage_hook();
2581 if (isloggedin()) {
2582 break;
2586 // If we're still not logged in then go to the login page
2587 if (!isloggedin()) {
2588 redirect(get_login_url());
2589 exit; // Never reached.
2594 // Loginas as redirection if needed.
2595 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2596 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2597 if ($USER->loginascontext->instanceid != $course->id) {
2598 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2603 // Check whether the user should be changing password (but only if it is REALLY them).
2604 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2605 $userauth = get_auth_plugin($USER->auth);
2606 if ($userauth->can_change_password() and !$preventredirect) {
2607 if ($setwantsurltome) {
2608 $SESSION->wantsurl = qualified_me();
2610 if ($changeurl = $userauth->change_password_url()) {
2611 // Use plugin custom url.
2612 redirect($changeurl);
2613 } else {
2614 // Use moodle internal method.
2615 if (empty($CFG->loginhttps)) {
2616 redirect($CFG->wwwroot .'/login/change_password.php');
2617 } else {
2618 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2619 redirect($wwwroot .'/login/change_password.php');
2622 } else {
2623 print_error('nopasswordchangeforced', 'auth');
2627 // Check that the user account is properly set up.
2628 if (user_not_fully_set_up($USER)) {
2629 if ($preventredirect) {
2630 throw new require_login_exception('User not fully set-up');
2632 if ($setwantsurltome) {
2633 $SESSION->wantsurl = qualified_me();
2635 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2638 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2639 sesskey();
2641 // Do not bother admins with any formalities.
2642 if (is_siteadmin()) {
2643 // Set the global $COURSE.
2644 if ($cm) {
2645 $PAGE->set_cm($cm, $course);
2646 $PAGE->set_pagelayout('incourse');
2647 } else if (!empty($courseorid)) {
2648 $PAGE->set_course($course);
2650 // Set accesstime or the user will appear offline which messes up messaging.
2651 user_accesstime_log($course->id);
2652 return;
2655 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2656 if (!$USER->policyagreed and !is_siteadmin()) {
2657 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2658 if ($preventredirect) {
2659 throw new require_login_exception('Policy not agreed');
2661 if ($setwantsurltome) {
2662 $SESSION->wantsurl = qualified_me();
2664 redirect($CFG->wwwroot .'/user/policy.php');
2665 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2666 if ($preventredirect) {
2667 throw new require_login_exception('Policy not agreed');
2669 if ($setwantsurltome) {
2670 $SESSION->wantsurl = qualified_me();
2672 redirect($CFG->wwwroot .'/user/policy.php');
2676 // Fetch the system context, the course context, and prefetch its child contexts.
2677 $sysctx = context_system::instance();
2678 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2679 if ($cm) {
2680 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2681 } else {
2682 $cmcontext = null;
2685 // If the site is currently under maintenance, then print a message.
2686 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2687 if ($preventredirect) {
2688 throw new require_login_exception('Maintenance in progress');
2691 print_maintenance_message();
2694 // Make sure the course itself is not hidden.
2695 if ($course->id == SITEID) {
2696 // Frontpage can not be hidden.
2697 } else {
2698 if (is_role_switched($course->id)) {
2699 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2700 } else {
2701 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2702 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2703 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2704 if ($preventredirect) {
2705 throw new require_login_exception('Course is hidden');
2707 $PAGE->set_context(null);
2708 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2709 // the navigation will mess up when trying to find it.
2710 navigation_node::override_active_url(new moodle_url('/'));
2711 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2716 // Is the user enrolled?
2717 if ($course->id == SITEID) {
2718 // Everybody is enrolled on the frontpage.
2719 } else {
2720 if (\core\session\manager::is_loggedinas()) {
2721 // Make sure the REAL person can access this course first.
2722 $realuser = \core\session\manager::get_realuser();
2723 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2724 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2725 if ($preventredirect) {
2726 throw new require_login_exception('Invalid course login-as access');
2728 $PAGE->set_context(null);
2729 echo $OUTPUT->header();
2730 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2734 $access = false;
2736 if (is_role_switched($course->id)) {
2737 // Ok, user had to be inside this course before the switch.
2738 $access = true;
2740 } else if (is_viewing($coursecontext, $USER)) {
2741 // Ok, no need to mess with enrol.
2742 $access = true;
2744 } else {
2745 if (isset($USER->enrol['enrolled'][$course->id])) {
2746 if ($USER->enrol['enrolled'][$course->id] > time()) {
2747 $access = true;
2748 if (isset($USER->enrol['tempguest'][$course->id])) {
2749 unset($USER->enrol['tempguest'][$course->id]);
2750 remove_temp_course_roles($coursecontext);
2752 } else {
2753 // Expired.
2754 unset($USER->enrol['enrolled'][$course->id]);
2757 if (isset($USER->enrol['tempguest'][$course->id])) {
2758 if ($USER->enrol['tempguest'][$course->id] == 0) {
2759 $access = true;
2760 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2761 $access = true;
2762 } else {
2763 // Expired.
2764 unset($USER->enrol['tempguest'][$course->id]);
2765 remove_temp_course_roles($coursecontext);
2769 if (!$access) {
2770 // Cache not ok.
2771 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2772 if ($until !== false) {
2773 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2774 if ($until == 0) {
2775 $until = ENROL_MAX_TIMESTAMP;
2777 $USER->enrol['enrolled'][$course->id] = $until;
2778 $access = true;
2780 } else {
2781 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2782 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2783 $enrols = enrol_get_plugins(true);
2784 // First ask all enabled enrol instances in course if they want to auto enrol user.
2785 foreach ($instances as $instance) {
2786 if (!isset($enrols[$instance->enrol])) {
2787 continue;
2789 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2790 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2791 if ($until !== false) {
2792 if ($until == 0) {
2793 $until = ENROL_MAX_TIMESTAMP;
2795 $USER->enrol['enrolled'][$course->id] = $until;
2796 $access = true;
2797 break;
2800 // If not enrolled yet try to gain temporary guest access.
2801 if (!$access) {
2802 foreach ($instances as $instance) {
2803 if (!isset($enrols[$instance->enrol])) {
2804 continue;
2806 // Get a duration for the guest access, a timestamp in the future or false.
2807 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2808 if ($until !== false and $until > time()) {
2809 $USER->enrol['tempguest'][$course->id] = $until;
2810 $access = true;
2811 break;
2819 if (!$access) {
2820 if ($preventredirect) {
2821 throw new require_login_exception('Not enrolled');
2823 if ($setwantsurltome) {
2824 $SESSION->wantsurl = qualified_me();
2826 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2830 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2831 if ($cm && !$cm->uservisible) {
2832 if ($preventredirect) {
2833 throw new require_login_exception('Activity is hidden');
2835 if ($course->id != SITEID) {
2836 $url = new moodle_url('/course/view.php', array('id' => $course->id));
2837 } else {
2838 $url = new moodle_url('/');
2840 redirect($url, get_string('activityiscurrentlyhidden'));
2843 // Set the global $COURSE.
2844 if ($cm) {
2845 $PAGE->set_cm($cm, $course);
2846 $PAGE->set_pagelayout('incourse');
2847 } else if (!empty($courseorid)) {
2848 $PAGE->set_course($course);
2851 // Finally access granted, update lastaccess times.
2852 user_accesstime_log($course->id);
2857 * This function just makes sure a user is logged out.
2859 * @package core_access
2860 * @category access
2862 function require_logout() {
2863 global $USER, $DB;
2865 if (!isloggedin()) {
2866 // This should not happen often, no need for hooks or events here.
2867 \core\session\manager::terminate_current();
2868 return;
2871 // Execute hooks before action.
2872 $authplugins = array();
2873 $authsequence = get_enabled_auth_plugins();
2874 foreach ($authsequence as $authname) {
2875 $authplugins[$authname] = get_auth_plugin($authname);
2876 $authplugins[$authname]->prelogout_hook();
2879 // Store info that gets removed during logout.
2880 $sid = session_id();
2881 $event = \core\event\user_loggedout::create(
2882 array(
2883 'userid' => $USER->id,
2884 'objectid' => $USER->id,
2885 'other' => array('sessionid' => $sid),
2888 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2889 $event->add_record_snapshot('sessions', $session);
2892 // Clone of $USER object to be used by auth plugins.
2893 $user = fullclone($USER);
2895 // Delete session record and drop $_SESSION content.
2896 \core\session\manager::terminate_current();
2898 // Trigger event AFTER action.
2899 $event->trigger();
2901 // Hook to execute auth plugins redirection after event trigger.
2902 foreach ($authplugins as $authplugin) {
2903 $authplugin->postlogout_hook($user);
2908 * Weaker version of require_login()
2910 * This is a weaker version of {@link require_login()} which only requires login
2911 * when called from within a course rather than the site page, unless
2912 * the forcelogin option is turned on.
2913 * @see require_login()
2915 * @package core_access
2916 * @category access
2918 * @param mixed $courseorid The course object or id in question
2919 * @param bool $autologinguest Allow autologin guests if that is wanted
2920 * @param object $cm Course activity module if known
2921 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2922 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2923 * in order to keep redirects working properly. MDL-14495
2924 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2925 * @return void
2926 * @throws coding_exception
2928 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2929 global $CFG, $PAGE, $SITE;
2930 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
2931 or (!is_object($courseorid) and $courseorid == SITEID));
2932 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2933 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2934 // db queries so this is not really a performance concern, however it is obviously
2935 // better if you use get_fast_modinfo to get the cm before calling this.
2936 if (is_object($courseorid)) {
2937 $course = $courseorid;
2938 } else {
2939 $course = clone($SITE);
2941 $modinfo = get_fast_modinfo($course);
2942 $cm = $modinfo->get_cm($cm->id);
2944 if (!empty($CFG->forcelogin)) {
2945 // Login required for both SITE and courses.
2946 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2948 } else if ($issite && !empty($cm) and !$cm->uservisible) {
2949 // Always login for hidden activities.
2950 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2952 } else if ($issite) {
2953 // Login for SITE not required.
2954 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
2955 if (!empty($courseorid)) {
2956 if (is_object($courseorid)) {
2957 $course = $courseorid;
2958 } else {
2959 $course = clone $SITE;
2961 if ($cm) {
2962 if ($cm->course != $course->id) {
2963 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2965 $PAGE->set_cm($cm, $course);
2966 $PAGE->set_pagelayout('incourse');
2967 } else {
2968 $PAGE->set_course($course);
2970 } else {
2971 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
2972 $PAGE->set_course($PAGE->course);
2974 user_accesstime_log(SITEID);
2975 return;
2977 } else {
2978 // Course login always required.
2979 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2984 * Require key login. Function terminates with error if key not found or incorrect.
2986 * @uses NO_MOODLE_COOKIES
2987 * @uses PARAM_ALPHANUM
2988 * @param string $script unique script identifier
2989 * @param int $instance optional instance id
2990 * @return int Instance ID
2992 function require_user_key_login($script, $instance=null) {
2993 global $DB;
2995 if (!NO_MOODLE_COOKIES) {
2996 print_error('sessioncookiesdisable');
2999 // Extra safety.
3000 \core\session\manager::write_close();
3002 $keyvalue = required_param('key', PARAM_ALPHANUM);
3004 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3005 print_error('invalidkey');
3008 if (!empty($key->validuntil) and $key->validuntil < time()) {
3009 print_error('expiredkey');
3012 if ($key->iprestriction) {
3013 $remoteaddr = getremoteaddr(null);
3014 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3015 print_error('ipmismatch');
3019 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3020 print_error('invaliduserid');
3023 // Emulate normal session.
3024 enrol_check_plugins($user);
3025 \core\session\manager::set_user($user);
3027 // Note we are not using normal login.
3028 if (!defined('USER_KEY_LOGIN')) {
3029 define('USER_KEY_LOGIN', true);
3032 // Return instance id - it might be empty.
3033 return $key->instance;
3037 * Creates a new private user access key.
3039 * @param string $script unique target identifier
3040 * @param int $userid
3041 * @param int $instance optional instance id
3042 * @param string $iprestriction optional ip restricted access
3043 * @param int $validuntil key valid only until given data
3044 * @return string access key value
3046 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3047 global $DB;
3049 $key = new stdClass();
3050 $key->script = $script;
3051 $key->userid = $userid;
3052 $key->instance = $instance;
3053 $key->iprestriction = $iprestriction;
3054 $key->validuntil = $validuntil;
3055 $key->timecreated = time();
3057 // Something long and unique.
3058 $key->value = md5($userid.'_'.time().random_string(40));
3059 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3060 // Must be unique.
3061 $key->value = md5($userid.'_'.time().random_string(40));
3063 $DB->insert_record('user_private_key', $key);
3064 return $key->value;
3068 * Delete the user's new private user access keys for a particular script.
3070 * @param string $script unique target identifier
3071 * @param int $userid
3072 * @return void
3074 function delete_user_key($script, $userid) {
3075 global $DB;
3076 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3080 * Gets a private user access key (and creates one if one doesn't exist).
3082 * @param string $script unique target identifier
3083 * @param int $userid
3084 * @param int $instance optional instance id
3085 * @param string $iprestriction optional ip restricted access
3086 * @param int $validuntil key valid only until given date
3087 * @return string access key value
3089 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3090 global $DB;
3092 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3093 'instance' => $instance, 'iprestriction' => $iprestriction,
3094 'validuntil' => $validuntil))) {
3095 return $key->value;
3096 } else {
3097 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3103 * Modify the user table by setting the currently logged in user's last login to now.
3105 * @return bool Always returns true
3107 function update_user_login_times() {
3108 global $USER, $DB;
3110 if (isguestuser()) {
3111 // Do not update guest access times/ips for performance.
3112 return true;
3115 $now = time();
3117 $user = new stdClass();
3118 $user->id = $USER->id;
3120 // Make sure all users that logged in have some firstaccess.
3121 if ($USER->firstaccess == 0) {
3122 $USER->firstaccess = $user->firstaccess = $now;
3125 // Store the previous current as lastlogin.
3126 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3128 $USER->currentlogin = $user->currentlogin = $now;
3130 // Function user_accesstime_log() may not update immediately, better do it here.
3131 $USER->lastaccess = $user->lastaccess = $now;
3132 $USER->lastip = $user->lastip = getremoteaddr();
3134 // Note: do not call user_update_user() here because this is part of the login process,
3135 // the login event means that these fields were updated.
3136 $DB->update_record('user', $user);
3137 return true;
3141 * Determines if a user has completed setting up their account.
3143 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3144 * @return bool
3146 function user_not_fully_set_up($user) {
3147 if (isguestuser($user)) {
3148 return false;
3150 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3154 * Check whether the user has exceeded the bounce threshold
3156 * @param stdClass $user A {@link $USER} object
3157 * @return bool true => User has exceeded bounce threshold
3159 function over_bounce_threshold($user) {
3160 global $CFG, $DB;
3162 if (empty($CFG->handlebounces)) {
3163 return false;
3166 if (empty($user->id)) {
3167 // No real (DB) user, nothing to do here.
3168 return false;
3171 // Set sensible defaults.
3172 if (empty($CFG->minbounces)) {
3173 $CFG->minbounces = 10;
3175 if (empty($CFG->bounceratio)) {
3176 $CFG->bounceratio = .20;
3178 $bouncecount = 0;
3179 $sendcount = 0;
3180 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3181 $bouncecount = $bounce->value;
3183 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3184 $sendcount = $send->value;
3186 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3190 * Used to increment or reset email sent count
3192 * @param stdClass $user object containing an id
3193 * @param bool $reset will reset the count to 0
3194 * @return void
3196 function set_send_count($user, $reset=false) {
3197 global $DB;
3199 if (empty($user->id)) {
3200 // No real (DB) user, nothing to do here.
3201 return;
3204 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3205 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3206 $DB->update_record('user_preferences', $pref);
3207 } else if (!empty($reset)) {
3208 // If it's not there and we're resetting, don't bother. Make a new one.
3209 $pref = new stdClass();
3210 $pref->name = 'email_send_count';
3211 $pref->value = 1;
3212 $pref->userid = $user->id;
3213 $DB->insert_record('user_preferences', $pref, false);
3218 * Increment or reset user's email bounce count
3220 * @param stdClass $user object containing an id
3221 * @param bool $reset will reset the count to 0
3223 function set_bounce_count($user, $reset=false) {
3224 global $DB;
3226 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3227 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3228 $DB->update_record('user_preferences', $pref);
3229 } else if (!empty($reset)) {
3230 // If it's not there and we're resetting, don't bother. Make a new one.
3231 $pref = new stdClass();
3232 $pref->name = 'email_bounce_count';
3233 $pref->value = 1;
3234 $pref->userid = $user->id;
3235 $DB->insert_record('user_preferences', $pref, false);
3240 * Determines if the logged in user is currently moving an activity
3242 * @param int $courseid The id of the course being tested
3243 * @return bool
3245 function ismoving($courseid) {
3246 global $USER;
3248 if (!empty($USER->activitycopy)) {
3249 return ($USER->activitycopycourse == $courseid);
3251 return false;
3255 * Returns a persons full name
3257 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3258 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3259 * specify one.
3261 * @param stdClass $user A {@link $USER} object to get full name of.
3262 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3263 * @return string
3265 function fullname($user, $override=false) {
3266 global $CFG, $SESSION;
3268 if (!isset($user->firstname) and !isset($user->lastname)) {
3269 return '';
3272 // Get all of the name fields.
3273 $allnames = get_all_user_name_fields();
3274 if ($CFG->debugdeveloper) {
3275 foreach ($allnames as $allname) {
3276 if (!property_exists($user, $allname)) {
3277 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3278 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3279 // Message has been sent, no point in sending the message multiple times.
3280 break;
3285 if (!$override) {
3286 if (!empty($CFG->forcefirstname)) {
3287 $user->firstname = $CFG->forcefirstname;
3289 if (!empty($CFG->forcelastname)) {
3290 $user->lastname = $CFG->forcelastname;
3294 if (!empty($SESSION->fullnamedisplay)) {
3295 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3298 $template = null;
3299 // If the fullnamedisplay setting is available, set the template to that.
3300 if (isset($CFG->fullnamedisplay)) {
3301 $template = $CFG->fullnamedisplay;
3303 // If the template is empty, or set to language, return the language string.
3304 if ((empty($template) || $template == 'language') && !$override) {
3305 return get_string('fullnamedisplay', null, $user);
3308 // Check to see if we are displaying according to the alternative full name format.
3309 if ($override) {
3310 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3311 // Default to show just the user names according to the fullnamedisplay string.
3312 return get_string('fullnamedisplay', null, $user);
3313 } else {
3314 // If the override is true, then change the template to use the complete name.
3315 $template = $CFG->alternativefullnameformat;
3319 $requirednames = array();
3320 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3321 foreach ($allnames as $allname) {
3322 if (strpos($template, $allname) !== false) {
3323 $requirednames[] = $allname;
3327 $displayname = $template;
3328 // Switch in the actual data into the template.
3329 foreach ($requirednames as $altname) {
3330 if (isset($user->$altname)) {
3331 // Using empty() on the below if statement causes breakages.
3332 if ((string)$user->$altname == '') {
3333 $displayname = str_replace($altname, 'EMPTY', $displayname);
3334 } else {
3335 $displayname = str_replace($altname, $user->$altname, $displayname);
3337 } else {
3338 $displayname = str_replace($altname, 'EMPTY', $displayname);
3341 // Tidy up any misc. characters (Not perfect, but gets most characters).
3342 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3343 // katakana and parenthesis.
3344 $patterns = array();
3345 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3346 // filled in by a user.
3347 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3348 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3349 // This regular expression is to remove any double spaces in the display name.
3350 $patterns[] = '/\s{2,}/u';
3351 foreach ($patterns as $pattern) {
3352 $displayname = preg_replace($pattern, ' ', $displayname);
3355 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3356 $displayname = trim($displayname);
3357 if (empty($displayname)) {
3358 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3359 // people in general feel is a good setting to fall back on.
3360 $displayname = $user->firstname;
3362 return $displayname;
3366 * A centralised location for the all name fields. Returns an array / sql string snippet.
3368 * @param bool $returnsql True for an sql select field snippet.
3369 * @param string $tableprefix table query prefix to use in front of each field.
3370 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3371 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3372 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3373 * @return array|string All name fields.
3375 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3376 // This array is provided in this order because when called by fullname() (above) if firstname is before
3377 // firstnamephonetic str_replace() will change the wrong placeholder.
3378 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3379 'lastnamephonetic' => 'lastnamephonetic',
3380 'middlename' => 'middlename',
3381 'alternatename' => 'alternatename',
3382 'firstname' => 'firstname',
3383 'lastname' => 'lastname');
3385 // Let's add a prefix to the array of user name fields if provided.
3386 if ($prefix) {
3387 foreach ($alternatenames as $key => $altname) {
3388 $alternatenames[$key] = $prefix . $altname;
3392 // If we want the end result to have firstname and lastname at the front / top of the result.
3393 if ($order) {
3394 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3395 for ($i = 0; $i < 2; $i++) {
3396 // Get the last element.
3397 $lastelement = end($alternatenames);
3398 // Remove it from the array.
3399 unset($alternatenames[$lastelement]);
3400 // Put the element back on the top of the array.
3401 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3405 // Create an sql field snippet if requested.
3406 if ($returnsql) {
3407 if ($tableprefix) {
3408 if ($fieldprefix) {
3409 foreach ($alternatenames as $key => $altname) {
3410 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3412 } else {
3413 foreach ($alternatenames as $key => $altname) {
3414 $alternatenames[$key] = $tableprefix . '.' . $altname;
3418 $alternatenames = implode(',', $alternatenames);
3420 return $alternatenames;
3424 * Reduces lines of duplicated code for getting user name fields.
3426 * See also {@link user_picture::unalias()}
3428 * @param object $addtoobject Object to add user name fields to.
3429 * @param object $secondobject Object that contains user name field information.
3430 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3431 * @param array $additionalfields Additional fields to be matched with data in the second object.
3432 * The key can be set to the user table field name.
3433 * @return object User name fields.
3435 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3436 $fields = get_all_user_name_fields(false, null, $prefix);
3437 if ($additionalfields) {
3438 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3439 // the key is a number and then sets the key to the array value.
3440 foreach ($additionalfields as $key => $value) {
3441 if (is_numeric($key)) {
3442 $additionalfields[$value] = $prefix . $value;
3443 unset($additionalfields[$key]);
3444 } else {
3445 $additionalfields[$key] = $prefix . $value;
3448 $fields = array_merge($fields, $additionalfields);
3450 foreach ($fields as $key => $field) {
3451 // Important that we have all of the user name fields present in the object that we are sending back.
3452 $addtoobject->$key = '';
3453 if (isset($secondobject->$field)) {
3454 $addtoobject->$key = $secondobject->$field;
3457 return $addtoobject;
3461 * Returns an array of values in order of occurance in a provided string.
3462 * The key in the result is the character postion in the string.
3464 * @param array $values Values to be found in the string format
3465 * @param string $stringformat The string which may contain values being searched for.
3466 * @return array An array of values in order according to placement in the string format.
3468 function order_in_string($values, $stringformat) {
3469 $valuearray = array();
3470 foreach ($values as $value) {
3471 $pattern = "/$value\b/";
3472 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3473 if (preg_match($pattern, $stringformat)) {
3474 $replacement = "thing";
3475 // Replace the value with something more unique to ensure we get the right position when using strpos().
3476 $newformat = preg_replace($pattern, $replacement, $stringformat);
3477 $position = strpos($newformat, $replacement);
3478 $valuearray[$position] = $value;
3481 ksort($valuearray);
3482 return $valuearray;
3486 * Checks if current user is shown any extra fields when listing users.
3488 * @param object $context Context
3489 * @param array $already Array of fields that we're going to show anyway
3490 * so don't bother listing them
3491 * @return array Array of field names from user table, not including anything
3492 * listed in $already
3494 function get_extra_user_fields($context, $already = array()) {
3495 global $CFG;
3497 // Only users with permission get the extra fields.
3498 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3499 return array();
3502 // Split showuseridentity on comma.
3503 if (empty($CFG->showuseridentity)) {
3504 // Explode gives wrong result with empty string.
3505 $extra = array();
3506 } else {
3507 $extra = explode(',', $CFG->showuseridentity);
3509 $renumber = false;
3510 foreach ($extra as $key => $field) {
3511 if (in_array($field, $already)) {
3512 unset($extra[$key]);
3513 $renumber = true;
3516 if ($renumber) {
3517 // For consistency, if entries are removed from array, renumber it
3518 // so they are numbered as you would expect.
3519 $extra = array_merge($extra);
3521 return $extra;
3525 * If the current user is to be shown extra user fields when listing or
3526 * selecting users, returns a string suitable for including in an SQL select
3527 * clause to retrieve those fields.
3529 * @param context $context Context
3530 * @param string $alias Alias of user table, e.g. 'u' (default none)
3531 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3532 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3533 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3535 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3536 $fields = get_extra_user_fields($context, $already);
3537 $result = '';
3538 // Add punctuation for alias.
3539 if ($alias !== '') {
3540 $alias .= '.';
3542 foreach ($fields as $field) {
3543 $result .= ', ' . $alias . $field;
3544 if ($prefix) {
3545 $result .= ' AS ' . $prefix . $field;
3548 return $result;
3552 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3553 * @param string $field Field name, e.g. 'phone1'
3554 * @return string Text description taken from language file, e.g. 'Phone number'
3556 function get_user_field_name($field) {
3557 // Some fields have language strings which are not the same as field name.
3558 switch ($field) {
3559 case 'url' : {
3560 return get_string('webpage');
3562 case 'icq' : {
3563 return get_string('icqnumber');
3565 case 'skype' : {
3566 return get_string('skypeid');
3568 case 'aim' : {
3569 return get_string('aimid');
3571 case 'yahoo' : {
3572 return get_string('yahooid');
3574 case 'msn' : {
3575 return get_string('msnid');
3578 // Otherwise just use the same lang string.
3579 return get_string($field);
3583 * Returns whether a given authentication plugin exists.
3585 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3586 * @return boolean Whether the plugin is available.
3588 function exists_auth_plugin($auth) {
3589 global $CFG;
3591 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3592 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3594 return false;
3598 * Checks if a given plugin is in the list of enabled authentication plugins.
3600 * @param string $auth Authentication plugin.
3601 * @return boolean Whether the plugin is enabled.
3603 function is_enabled_auth($auth) {
3604 if (empty($auth)) {
3605 return false;
3608 $enabled = get_enabled_auth_plugins();
3610 return in_array($auth, $enabled);
3614 * Returns an authentication plugin instance.
3616 * @param string $auth name of authentication plugin
3617 * @return auth_plugin_base An instance of the required authentication plugin.
3619 function get_auth_plugin($auth) {
3620 global $CFG;
3622 // Check the plugin exists first.
3623 if (! exists_auth_plugin($auth)) {
3624 print_error('authpluginnotfound', 'debug', '', $auth);
3627 // Return auth plugin instance.
3628 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3629 $class = "auth_plugin_$auth";
3630 return new $class;
3634 * Returns array of active auth plugins.
3636 * @param bool $fix fix $CFG->auth if needed
3637 * @return array
3639 function get_enabled_auth_plugins($fix=false) {
3640 global $CFG;
3642 $default = array('manual', 'nologin');
3644 if (empty($CFG->auth)) {
3645 $auths = array();
3646 } else {
3647 $auths = explode(',', $CFG->auth);
3650 if ($fix) {
3651 $auths = array_unique($auths);
3652 foreach ($auths as $k => $authname) {
3653 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3654 unset($auths[$k]);
3657 $newconfig = implode(',', $auths);
3658 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3659 set_config('auth', $newconfig);
3663 return (array_merge($default, $auths));
3667 * Returns true if an internal authentication method is being used.
3668 * if method not specified then, global default is assumed
3670 * @param string $auth Form of authentication required
3671 * @return bool
3673 function is_internal_auth($auth) {
3674 // Throws error if bad $auth.
3675 $authplugin = get_auth_plugin($auth);
3676 return $authplugin->is_internal();
3680 * Returns true if the user is a 'restored' one.
3682 * Used in the login process to inform the user and allow him/her to reset the password
3684 * @param string $username username to be checked
3685 * @return bool
3687 function is_restored_user($username) {
3688 global $CFG, $DB;
3690 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3694 * Returns an array of user fields
3696 * @return array User field/column names
3698 function get_user_fieldnames() {
3699 global $DB;
3701 $fieldarray = $DB->get_columns('user');
3702 unset($fieldarray['id']);
3703 $fieldarray = array_keys($fieldarray);
3705 return $fieldarray;
3709 * Creates a bare-bones user record
3711 * @todo Outline auth types and provide code example
3713 * @param string $username New user's username to add to record
3714 * @param string $password New user's password to add to record
3715 * @param string $auth Form of authentication required
3716 * @return stdClass A complete user object
3718 function create_user_record($username, $password, $auth = 'manual') {
3719 global $CFG, $DB;
3720 require_once($CFG->dirroot.'/user/profile/lib.php');
3721 require_once($CFG->dirroot.'/user/lib.php');
3723 // Just in case check text case.
3724 $username = trim(core_text::strtolower($username));
3726 $authplugin = get_auth_plugin($auth);
3727 $customfields = $authplugin->get_custom_user_profile_fields();
3728 $newuser = new stdClass();
3729 if ($newinfo = $authplugin->get_userinfo($username)) {
3730 $newinfo = truncate_userinfo($newinfo);
3731 foreach ($newinfo as $key => $value) {
3732 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3733 $newuser->$key = $value;
3738 if (!empty($newuser->email)) {
3739 if (email_is_not_allowed($newuser->email)) {
3740 unset($newuser->email);
3744 if (!isset($newuser->city)) {
3745 $newuser->city = '';
3748 $newuser->auth = $auth;
3749 $newuser->username = $username;
3751 // Fix for MDL-8480
3752 // user CFG lang for user if $newuser->lang is empty
3753 // or $user->lang is not an installed language.
3754 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3755 $newuser->lang = $CFG->lang;
3757 $newuser->confirmed = 1;
3758 $newuser->lastip = getremoteaddr();
3759 $newuser->timecreated = time();
3760 $newuser->timemodified = $newuser->timecreated;
3761 $newuser->mnethostid = $CFG->mnet_localhost_id;
3763 $newuser->id = user_create_user($newuser, false, false);
3765 // Save user profile data.
3766 profile_save_data($newuser);
3768 $user = get_complete_user_data('id', $newuser->id);
3769 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3770 set_user_preference('auth_forcepasswordchange', 1, $user);
3772 // Set the password.
3773 update_internal_user_password($user, $password);
3775 // Trigger event.
3776 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3778 return $user;
3782 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3784 * @param string $username user's username to update the record
3785 * @return stdClass A complete user object
3787 function update_user_record($username) {
3788 global $DB, $CFG;
3789 // Just in case check text case.
3790 $username = trim(core_text::strtolower($username));
3792 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3793 return update_user_record_by_id($oldinfo->id);
3797 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3799 * @param int $id user id
3800 * @return stdClass A complete user object
3802 function update_user_record_by_id($id) {
3803 global $DB, $CFG;
3804 require_once($CFG->dirroot."/user/profile/lib.php");
3805 require_once($CFG->dirroot.'/user/lib.php');
3807 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3808 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3810 $newuser = array();
3811 $userauth = get_auth_plugin($oldinfo->auth);
3813 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3814 $newinfo = truncate_userinfo($newinfo);
3815 $customfields = $userauth->get_custom_user_profile_fields();
3817 foreach ($newinfo as $key => $value) {
3818 $iscustom = in_array($key, $customfields);
3819 if (!$iscustom) {
3820 $key = strtolower($key);
3822 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3823 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3824 // Unknown or must not be changed.
3825 continue;
3827 $confval = $userauth->config->{'field_updatelocal_' . $key};
3828 $lockval = $userauth->config->{'field_lock_' . $key};
3829 if (empty($confval) || empty($lockval)) {
3830 continue;
3832 if ($confval === 'onlogin') {
3833 // MDL-4207 Don't overwrite modified user profile values with
3834 // empty LDAP values when 'unlocked if empty' is set. The purpose
3835 // of the setting 'unlocked if empty' is to allow the user to fill
3836 // in a value for the selected field _if LDAP is giving
3837 // nothing_ for this field. Thus it makes sense to let this value
3838 // stand in until LDAP is giving a value for this field.
3839 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3840 if ($iscustom || (in_array($key, $userauth->userfields) &&
3841 ((string)$oldinfo->$key !== (string)$value))) {
3842 $newuser[$key] = (string)$value;
3847 if ($newuser) {
3848 $newuser['id'] = $oldinfo->id;
3849 $newuser['timemodified'] = time();
3850 user_update_user((object) $newuser, false, false);
3852 // Save user profile data.
3853 profile_save_data((object) $newuser);
3855 // Trigger event.
3856 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
3860 return get_complete_user_data('id', $oldinfo->id);
3864 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
3866 * @param array $info Array of user properties to truncate if needed
3867 * @return array The now truncated information that was passed in
3869 function truncate_userinfo(array $info) {
3870 // Define the limits.
3871 $limit = array(
3872 'username' => 100,
3873 'idnumber' => 255,
3874 'firstname' => 100,
3875 'lastname' => 100,
3876 'email' => 100,
3877 'icq' => 15,
3878 'phone1' => 20,
3879 'phone2' => 20,
3880 'institution' => 255,
3881 'department' => 255,
3882 'address' => 255,
3883 'city' => 120,
3884 'country' => 2,
3885 'url' => 255,
3888 // Apply where needed.
3889 foreach (array_keys($info) as $key) {
3890 if (!empty($limit[$key])) {
3891 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
3895 return $info;
3899 * Marks user deleted in internal user database and notifies the auth plugin.
3900 * Also unenrols user from all roles and does other cleanup.
3902 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3904 * @param stdClass $user full user object before delete
3905 * @return boolean success
3906 * @throws coding_exception if invalid $user parameter detected
3908 function delete_user(stdClass $user) {
3909 global $CFG, $DB;
3910 require_once($CFG->libdir.'/grouplib.php');
3911 require_once($CFG->libdir.'/gradelib.php');
3912 require_once($CFG->dirroot.'/message/lib.php');
3913 require_once($CFG->dirroot.'/user/lib.php');
3915 // Make sure nobody sends bogus record type as parameter.
3916 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
3917 throw new coding_exception('Invalid $user parameter in delete_user() detected');
3920 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
3921 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
3922 debugging('Attempt to delete unknown user account.');
3923 return false;
3926 // There must be always exactly one guest record, originally the guest account was identified by username only,
3927 // now we use $CFG->siteguest for performance reasons.
3928 if ($user->username === 'guest' or isguestuser($user)) {
3929 debugging('Guest user account can not be deleted.');
3930 return false;
3933 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
3934 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
3935 if ($user->auth === 'manual' and is_siteadmin($user)) {
3936 debugging('Local administrator accounts can not be deleted.');
3937 return false;
3940 // Allow plugins to use this user object before we completely delete it.
3941 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
3942 foreach ($pluginsfunction as $plugintype => $plugins) {
3943 foreach ($plugins as $pluginfunction) {
3944 $pluginfunction($user);
3949 // Keep user record before updating it, as we have to pass this to user_deleted event.
3950 $olduser = clone $user;
3952 // Keep a copy of user context, we need it for event.
3953 $usercontext = context_user::instance($user->id);
3955 // Delete all grades - backup is kept in grade_grades_history table.
3956 grade_user_delete($user->id);
3958 // Move unread messages from this user to read.
3959 message_move_userfrom_unread2read($user->id);
3961 // TODO: remove from cohorts using standard API here.
3963 // Remove user tags.
3964 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
3966 // Unconditionally unenrol from all courses.
3967 enrol_user_delete($user);
3969 // Unenrol from all roles in all contexts.
3970 // This might be slow but it is really needed - modules might do some extra cleanup!
3971 role_unassign_all(array('userid' => $user->id));
3973 // Now do a brute force cleanup.
3975 // Remove from all cohorts.
3976 $DB->delete_records('cohort_members', array('userid' => $user->id));
3978 // Remove from all groups.
3979 $DB->delete_records('groups_members', array('userid' => $user->id));
3981 // Brute force unenrol from all courses.
3982 $DB->delete_records('user_enrolments', array('userid' => $user->id));
3984 // Purge user preferences.
3985 $DB->delete_records('user_preferences', array('userid' => $user->id));
3987 // Purge user extra profile info.
3988 $DB->delete_records('user_info_data', array('userid' => $user->id));
3990 // Purge log of previous password hashes.
3991 $DB->delete_records('user_password_history', array('userid' => $user->id));
3993 // Last course access not necessary either.
3994 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
3995 // Remove all user tokens.
3996 $DB->delete_records('external_tokens', array('userid' => $user->id));
3998 // Unauthorise the user for all services.
3999 $DB->delete_records('external_services_users', array('userid' => $user->id));
4001 // Remove users private keys.
4002 $DB->delete_records('user_private_key', array('userid' => $user->id));
4004 // Remove users customised pages.
4005 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4007 // Force logout - may fail if file based sessions used, sorry.
4008 \core\session\manager::kill_user_sessions($user->id);
4010 // Generate username from email address, or a fake email.
4011 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4012 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
4014 // Workaround for bulk deletes of users with the same email address.
4015 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4016 $delname++;
4019 // Mark internal user record as "deleted".
4020 $updateuser = new stdClass();
4021 $updateuser->id = $user->id;
4022 $updateuser->deleted = 1;
4023 $updateuser->username = $delname; // Remember it just in case.
4024 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4025 $updateuser->idnumber = ''; // Clear this field to free it up.
4026 $updateuser->picture = 0;
4027 $updateuser->timemodified = time();
4029 // Don't trigger update event, as user is being deleted.
4030 user_update_user($updateuser, false, false);
4032 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4033 context_helper::delete_instance(CONTEXT_USER, $user->id);
4035 // Any plugin that needs to cleanup should register this event.
4036 // Trigger event.
4037 $event = \core\event\user_deleted::create(
4038 array(
4039 'objectid' => $user->id,
4040 'relateduserid' => $user->id,
4041 'context' => $usercontext,
4042 'other' => array(
4043 'username' => $user->username,
4044 'email' => $user->email,
4045 'idnumber' => $user->idnumber,
4046 'picture' => $user->picture,
4047 'mnethostid' => $user->mnethostid
4051 $event->add_record_snapshot('user', $olduser);
4052 $event->trigger();
4054 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4055 // should know about this updated property persisted to the user's table.
4056 $user->timemodified = $updateuser->timemodified;
4058 // Notify auth plugin - do not block the delete even when plugin fails.
4059 $authplugin = get_auth_plugin($user->auth);
4060 $authplugin->user_delete($user);
4062 return true;
4066 * Retrieve the guest user object.
4068 * @return stdClass A {@link $USER} object
4070 function guest_user() {
4071 global $CFG, $DB;
4073 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4074 $newuser->confirmed = 1;
4075 $newuser->lang = $CFG->lang;
4076 $newuser->lastip = getremoteaddr();
4079 return $newuser;
4083 * Authenticates a user against the chosen authentication mechanism
4085 * Given a username and password, this function looks them
4086 * up using the currently selected authentication mechanism,
4087 * and if the authentication is successful, it returns a
4088 * valid $user object from the 'user' table.
4090 * Uses auth_ functions from the currently active auth module
4092 * After authenticate_user_login() returns success, you will need to
4093 * log that the user has logged in, and call complete_user_login() to set
4094 * the session up.
4096 * Note: this function works only with non-mnet accounts!
4098 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4099 * @param string $password User's password
4100 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4101 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4102 * @return stdClass|false A {@link $USER} object or false if error
4104 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4105 global $CFG, $DB;
4106 require_once("$CFG->libdir/authlib.php");
4108 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4109 // we have found the user
4111 } else if (!empty($CFG->authloginviaemail)) {
4112 if ($email = clean_param($username, PARAM_EMAIL)) {
4113 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4114 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4115 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4116 if (count($users) === 1) {
4117 // Use email for login only if unique.
4118 $user = reset($users);
4119 $user = get_complete_user_data('id', $user->id);
4120 $username = $user->username;
4122 unset($users);
4126 $authsenabled = get_enabled_auth_plugins();
4128 if ($user) {
4129 // Use manual if auth not set.
4130 $auth = empty($user->auth) ? 'manual' : $user->auth;
4132 if (in_array($user->auth, $authsenabled)) {
4133 $authplugin = get_auth_plugin($user->auth);
4134 $authplugin->pre_user_login_hook($user);
4137 if (!empty($user->suspended)) {
4138 $failurereason = AUTH_LOGIN_SUSPENDED;
4140 // Trigger login failed event.
4141 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4142 'other' => array('username' => $username, 'reason' => $failurereason)));
4143 $event->trigger();
4144 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4145 return false;
4147 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4148 // Legacy way to suspend user.
4149 $failurereason = AUTH_LOGIN_SUSPENDED;
4151 // Trigger login failed event.
4152 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4153 'other' => array('username' => $username, 'reason' => $failurereason)));
4154 $event->trigger();
4155 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4156 return false;
4158 $auths = array($auth);
4160 } else {
4161 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4162 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4163 $failurereason = AUTH_LOGIN_NOUSER;
4165 // Trigger login failed event.
4166 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4167 'reason' => $failurereason)));
4168 $event->trigger();
4169 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4170 return false;
4173 // User does not exist.
4174 $auths = $authsenabled;
4175 $user = new stdClass();
4176 $user->id = 0;
4179 if ($ignorelockout) {
4180 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4181 // or this function is called from a SSO script.
4182 } else if ($user->id) {
4183 // Verify login lockout after other ways that may prevent user login.
4184 if (login_is_lockedout($user)) {
4185 $failurereason = AUTH_LOGIN_LOCKOUT;
4187 // Trigger login failed event.
4188 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4189 'other' => array('username' => $username, 'reason' => $failurereason)));
4190 $event->trigger();
4192 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4193 return false;
4195 } else {
4196 // We can not lockout non-existing accounts.
4199 foreach ($auths as $auth) {
4200 $authplugin = get_auth_plugin($auth);
4202 // On auth fail fall through to the next plugin.
4203 if (!$authplugin->user_login($username, $password)) {
4204 continue;
4207 // Successful authentication.
4208 if ($user->id) {
4209 // User already exists in database.
4210 if (empty($user->auth)) {
4211 // For some reason auth isn't set yet.
4212 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4213 $user->auth = $auth;
4216 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4217 // the current hash algorithm while we have access to the user's password.
4218 update_internal_user_password($user, $password);
4220 if ($authplugin->is_synchronised_with_external()) {
4221 // Update user record from external DB.
4222 $user = update_user_record_by_id($user->id);
4224 } else {
4225 // The user is authenticated but user creation may be disabled.
4226 if (!empty($CFG->authpreventaccountcreation)) {
4227 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4229 // Trigger login failed event.
4230 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4231 'reason' => $failurereason)));
4232 $event->trigger();
4234 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4235 $_SERVER['HTTP_USER_AGENT']);
4236 return false;
4237 } else {
4238 $user = create_user_record($username, $password, $auth);
4242 $authplugin->sync_roles($user);
4244 foreach ($authsenabled as $hau) {
4245 $hauth = get_auth_plugin($hau);
4246 $hauth->user_authenticated_hook($user, $username, $password);
4249 if (empty($user->id)) {
4250 $failurereason = AUTH_LOGIN_NOUSER;
4251 // Trigger login failed event.
4252 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4253 'reason' => $failurereason)));
4254 $event->trigger();
4255 return false;
4258 if (!empty($user->suspended)) {
4259 // Just in case some auth plugin suspended account.
4260 $failurereason = AUTH_LOGIN_SUSPENDED;
4261 // Trigger login failed event.
4262 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4263 'other' => array('username' => $username, 'reason' => $failurereason)));
4264 $event->trigger();
4265 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4266 return false;
4269 login_attempt_valid($user);
4270 $failurereason = AUTH_LOGIN_OK;
4271 return $user;
4274 // Failed if all the plugins have failed.
4275 if (debugging('', DEBUG_ALL)) {
4276 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4279 if ($user->id) {
4280 login_attempt_failed($user);
4281 $failurereason = AUTH_LOGIN_FAILED;
4282 // Trigger login failed event.
4283 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4284 'other' => array('username' => $username, 'reason' => $failurereason)));
4285 $event->trigger();
4286 } else {
4287 $failurereason = AUTH_LOGIN_NOUSER;
4288 // Trigger login failed event.
4289 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4290 'reason' => $failurereason)));
4291 $event->trigger();
4294 return false;
4298 * Call to complete the user login process after authenticate_user_login()
4299 * has succeeded. It will setup the $USER variable and other required bits
4300 * and pieces.
4302 * NOTE:
4303 * - It will NOT log anything -- up to the caller to decide what to log.
4304 * - this function does not set any cookies any more!
4306 * @param stdClass $user
4307 * @return stdClass A {@link $USER} object - BC only, do not use
4309 function complete_user_login($user) {
4310 global $CFG, $USER, $SESSION;
4312 \core\session\manager::login_user($user);
4314 // Reload preferences from DB.
4315 unset($USER->preference);
4316 check_user_preferences_loaded($USER);
4318 // Update login times.
4319 update_user_login_times();
4321 // Extra session prefs init.
4322 set_login_session_preferences();
4324 // Trigger login event.
4325 $event = \core\event\user_loggedin::create(
4326 array(
4327 'userid' => $USER->id,
4328 'objectid' => $USER->id,
4329 'other' => array('username' => $USER->username),
4332 $event->trigger();
4334 if (isguestuser()) {
4335 // No need to continue when user is THE guest.
4336 return $USER;
4339 if (CLI_SCRIPT) {
4340 // We can redirect to password change URL only in browser.
4341 return $USER;
4344 // Select password change url.
4345 $userauth = get_auth_plugin($USER->auth);
4347 // Check whether the user should be changing password.
4348 if (get_user_preferences('auth_forcepasswordchange', false)) {
4349 if ($userauth->can_change_password()) {
4350 if ($changeurl = $userauth->change_password_url()) {
4351 redirect($changeurl);
4352 } else {
4353 $SESSION->wantsurl = core_login_get_return_url();
4354 redirect($CFG->httpswwwroot.'/login/change_password.php');
4356 } else {
4357 print_error('nopasswordchangeforced', 'auth');
4360 return $USER;
4364 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4366 * @param string $password String to check.
4367 * @return boolean True if the $password matches the format of an md5 sum.
4369 function password_is_legacy_hash($password) {
4370 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4374 * Compare password against hash stored in user object to determine if it is valid.
4376 * If necessary it also updates the stored hash to the current format.
4378 * @param stdClass $user (Password property may be updated).
4379 * @param string $password Plain text password.
4380 * @return bool True if password is valid.
4382 function validate_internal_user_password($user, $password) {
4383 global $CFG;
4385 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4386 // Internal password is not used at all, it can not validate.
4387 return false;
4390 // If hash isn't a legacy (md5) hash, validate using the library function.
4391 if (!password_is_legacy_hash($user->password)) {
4392 return password_verify($password, $user->password);
4395 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4396 // is valid we can then update it to the new algorithm.
4398 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4399 $validated = false;
4401 if ($user->password === md5($password.$sitesalt)
4402 or $user->password === md5($password)
4403 or $user->password === md5(addslashes($password).$sitesalt)
4404 or $user->password === md5(addslashes($password))) {
4405 // Note: we are intentionally using the addslashes() here because we
4406 // need to accept old password hashes of passwords with magic quotes.
4407 $validated = true;
4409 } else {
4410 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4411 $alt = 'passwordsaltalt'.$i;
4412 if (!empty($CFG->$alt)) {
4413 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4414 $validated = true;
4415 break;
4421 if ($validated) {
4422 // If the password matches the existing md5 hash, update to the
4423 // current hash algorithm while we have access to the user's password.
4424 update_internal_user_password($user, $password);
4427 return $validated;
4431 * Calculate hash for a plain text password.
4433 * @param string $password Plain text password to be hashed.
4434 * @param bool $fasthash If true, use a low cost factor when generating the hash
4435 * This is much faster to generate but makes the hash
4436 * less secure. It is used when lots of hashes need to
4437 * be generated quickly.
4438 * @return string The hashed password.
4440 * @throws moodle_exception If a problem occurs while generating the hash.
4442 function hash_internal_user_password($password, $fasthash = false) {
4443 global $CFG;
4445 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4446 $options = ($fasthash) ? array('cost' => 4) : array();
4448 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4450 if ($generatedhash === false || $generatedhash === null) {
4451 throw new moodle_exception('Failed to generate password hash.');
4454 return $generatedhash;
4458 * Update password hash in user object (if necessary).
4460 * The password is updated if:
4461 * 1. The password has changed (the hash of $user->password is different
4462 * to the hash of $password).
4463 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4464 * md5 algorithm).
4466 * Updating the password will modify the $user object and the database
4467 * record to use the current hashing algorithm.
4469 * @param stdClass $user User object (password property may be updated).
4470 * @param string $password Plain text password.
4471 * @param bool $fasthash If true, use a low cost factor when generating the hash
4472 * This is much faster to generate but makes the hash
4473 * less secure. It is used when lots of hashes need to
4474 * be generated quickly.
4475 * @return bool Always returns true.
4477 function update_internal_user_password($user, $password, $fasthash = false) {
4478 global $CFG, $DB;
4480 // Figure out what the hashed password should be.
4481 if (!isset($user->auth)) {
4482 debugging('User record in update_internal_user_password() must include field auth',
4483 DEBUG_DEVELOPER);
4484 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4486 $authplugin = get_auth_plugin($user->auth);
4487 if ($authplugin->prevent_local_passwords()) {
4488 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4489 } else {
4490 $hashedpassword = hash_internal_user_password($password, $fasthash);
4493 $algorithmchanged = false;
4495 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4496 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4497 $passwordchanged = ($user->password !== $hashedpassword);
4499 } else if (isset($user->password)) {
4500 // If verification fails then it means the password has changed.
4501 $passwordchanged = !password_verify($password, $user->password);
4502 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4503 } else {
4504 // While creating new user, password in unset in $user object, to avoid
4505 // saving it with user_create()
4506 $passwordchanged = true;
4509 if ($passwordchanged || $algorithmchanged) {
4510 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4511 $user->password = $hashedpassword;
4513 // Trigger event.
4514 $user = $DB->get_record('user', array('id' => $user->id));
4515 \core\event\user_password_updated::create_from_user($user)->trigger();
4518 return true;
4522 * Get a complete user record, which includes all the info in the user record.
4524 * Intended for setting as $USER session variable
4526 * @param string $field The user field to be checked for a given value.
4527 * @param string $value The value to match for $field.
4528 * @param int $mnethostid
4529 * @return mixed False, or A {@link $USER} object.
4531 function get_complete_user_data($field, $value, $mnethostid = null) {
4532 global $CFG, $DB;
4534 if (!$field || !$value) {
4535 return false;
4538 // Build the WHERE clause for an SQL query.
4539 $params = array('fieldval' => $value);
4540 $constraints = "$field = :fieldval AND deleted <> 1";
4542 // If we are loading user data based on anything other than id,
4543 // we must also restrict our search based on mnet host.
4544 if ($field != 'id') {
4545 if (empty($mnethostid)) {
4546 // If empty, we restrict to local users.
4547 $mnethostid = $CFG->mnet_localhost_id;
4550 if (!empty($mnethostid)) {
4551 $params['mnethostid'] = $mnethostid;
4552 $constraints .= " AND mnethostid = :mnethostid";
4555 // Get all the basic user data.
4556 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4557 return false;
4560 // Get various settings and preferences.
4562 // Preload preference cache.
4563 check_user_preferences_loaded($user);
4565 // Load course enrolment related stuff.
4566 $user->lastcourseaccess = array(); // During last session.
4567 $user->currentcourseaccess = array(); // During current session.
4568 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4569 foreach ($lastaccesses as $lastaccess) {
4570 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4574 $sql = "SELECT g.id, g.courseid
4575 FROM {groups} g, {groups_members} gm
4576 WHERE gm.groupid=g.id AND gm.userid=?";
4578 // This is a special hack to speedup calendar display.
4579 $user->groupmember = array();
4580 if (!isguestuser($user)) {
4581 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4582 foreach ($groups as $group) {
4583 if (!array_key_exists($group->courseid, $user->groupmember)) {
4584 $user->groupmember[$group->courseid] = array();
4586 $user->groupmember[$group->courseid][$group->id] = $group->id;
4591 // Add the custom profile fields to the user record.
4592 $user->profile = array();
4593 if (!isguestuser($user)) {
4594 require_once($CFG->dirroot.'/user/profile/lib.php');
4595 profile_load_custom_fields($user);
4598 // Rewrite some variables if necessary.
4599 if (!empty($user->description)) {
4600 // No need to cart all of it around.
4601 $user->description = true;
4603 if (isguestuser($user)) {
4604 // Guest language always same as site.
4605 $user->lang = $CFG->lang;
4606 // Name always in current language.
4607 $user->firstname = get_string('guestuser');
4608 $user->lastname = ' ';
4611 return $user;
4615 * Validate a password against the configured password policy
4617 * @param string $password the password to be checked against the password policy
4618 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4619 * @return bool true if the password is valid according to the policy. false otherwise.
4621 function check_password_policy($password, &$errmsg) {
4622 global $CFG;
4624 if (empty($CFG->passwordpolicy)) {
4625 return true;
4628 $errmsg = '';
4629 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4630 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4633 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4634 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4637 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4638 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4641 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4642 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4645 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4646 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4648 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4649 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4652 if ($errmsg == '') {
4653 return true;
4654 } else {
4655 return false;
4661 * When logging in, this function is run to set certain preferences for the current SESSION.
4663 function set_login_session_preferences() {
4664 global $SESSION;
4666 $SESSION->justloggedin = true;
4668 unset($SESSION->lang);
4669 unset($SESSION->forcelang);
4670 unset($SESSION->load_navigation_admin);
4675 * Delete a course, including all related data from the database, and any associated files.
4677 * @param mixed $courseorid The id of the course or course object to delete.
4678 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4679 * @return bool true if all the removals succeeded. false if there were any failures. If this
4680 * method returns false, some of the removals will probably have succeeded, and others
4681 * failed, but you have no way of knowing which.
4683 function delete_course($courseorid, $showfeedback = true) {
4684 global $DB;
4686 if (is_object($courseorid)) {
4687 $courseid = $courseorid->id;
4688 $course = $courseorid;
4689 } else {
4690 $courseid = $courseorid;
4691 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4692 return false;
4695 $context = context_course::instance($courseid);
4697 // Frontpage course can not be deleted!!
4698 if ($courseid == SITEID) {
4699 return false;
4702 // Allow plugins to use this course before we completely delete it.
4703 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
4704 foreach ($pluginsfunction as $plugintype => $plugins) {
4705 foreach ($plugins as $pluginfunction) {
4706 $pluginfunction($course);
4711 // Make the course completely empty.
4712 remove_course_contents($courseid, $showfeedback);
4714 // Delete the course and related context instance.
4715 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4717 $DB->delete_records("course", array("id" => $courseid));
4718 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4720 // Reset all course related caches here.
4721 if (class_exists('format_base', false)) {
4722 format_base::reset_course_cache($courseid);
4725 // Trigger a course deleted event.
4726 $event = \core\event\course_deleted::create(array(
4727 'objectid' => $course->id,
4728 'context' => $context,
4729 'other' => array(
4730 'shortname' => $course->shortname,
4731 'fullname' => $course->fullname,
4732 'idnumber' => $course->idnumber
4735 $event->add_record_snapshot('course', $course);
4736 $event->trigger();
4738 return true;
4742 * Clear a course out completely, deleting all content but don't delete the course itself.
4744 * This function does not verify any permissions.
4746 * Please note this function also deletes all user enrolments,
4747 * enrolment instances and role assignments by default.
4749 * $options:
4750 * - 'keep_roles_and_enrolments' - false by default
4751 * - 'keep_groups_and_groupings' - false by default
4753 * @param int $courseid The id of the course that is being deleted
4754 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4755 * @param array $options extra options
4756 * @return bool true if all the removals succeeded. false if there were any failures. If this
4757 * method returns false, some of the removals will probably have succeeded, and others
4758 * failed, but you have no way of knowing which.
4760 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4761 global $CFG, $DB, $OUTPUT;
4763 require_once($CFG->libdir.'/badgeslib.php');
4764 require_once($CFG->libdir.'/completionlib.php');
4765 require_once($CFG->libdir.'/questionlib.php');
4766 require_once($CFG->libdir.'/gradelib.php');
4767 require_once($CFG->dirroot.'/group/lib.php');
4768 require_once($CFG->dirroot.'/comment/lib.php');
4769 require_once($CFG->dirroot.'/rating/lib.php');
4770 require_once($CFG->dirroot.'/notes/lib.php');
4772 // Handle course badges.
4773 badges_handle_course_deletion($courseid);
4775 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4776 $strdeleted = get_string('deleted').' - ';
4778 // Some crazy wishlist of stuff we should skip during purging of course content.
4779 $options = (array)$options;
4781 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
4782 $coursecontext = context_course::instance($courseid);
4783 $fs = get_file_storage();
4785 // Delete course completion information, this has to be done before grades and enrols.
4786 $cc = new completion_info($course);
4787 $cc->clear_criteria();
4788 if ($showfeedback) {
4789 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4792 // Remove all data from gradebook - this needs to be done before course modules
4793 // because while deleting this information, the system may need to reference
4794 // the course modules that own the grades.
4795 remove_course_grades($courseid, $showfeedback);
4796 remove_grade_letters($coursecontext, $showfeedback);
4798 // Delete course blocks in any all child contexts,
4799 // they may depend on modules so delete them first.
4800 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4801 foreach ($childcontexts as $childcontext) {
4802 blocks_delete_all_for_context($childcontext->id);
4804 unset($childcontexts);
4805 blocks_delete_all_for_context($coursecontext->id);
4806 if ($showfeedback) {
4807 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4810 // Get the list of all modules that are properly installed.
4811 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
4813 // Delete every instance of every module,
4814 // this has to be done before deleting of course level stuff.
4815 $locations = core_component::get_plugin_list('mod');
4816 foreach ($locations as $modname => $moddir) {
4817 if ($modname === 'NEWMODULE') {
4818 continue;
4820 if (array_key_exists($modname, $allmodules)) {
4821 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
4822 FROM {".$modname."} m
4823 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
4824 WHERE m.course = :courseid";
4825 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
4826 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
4828 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
4829 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
4830 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
4832 if ($instances) {
4833 foreach ($instances as $cm) {
4834 if ($cm->id) {
4835 // Delete activity context questions and question categories.
4836 question_delete_activity($cm, $showfeedback);
4837 // Notify the competency subsystem.
4838 \core_competency\api::hook_course_module_deleted($cm);
4840 if (function_exists($moddelete)) {
4841 // This purges all module data in related tables, extra user prefs, settings, etc.
4842 $moddelete($cm->modinstance);
4843 } else {
4844 // NOTE: we should not allow installation of modules with missing delete support!
4845 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
4846 $DB->delete_records($modname, array('id' => $cm->modinstance));
4849 if ($cm->id) {
4850 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
4851 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4852 $DB->delete_records('course_modules', array('id' => $cm->id));
4856 if (function_exists($moddeletecourse)) {
4857 // Execute optional course cleanup callback. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
4858 debugging("Callback delete_course is deprecated. Function $moddeletecourse should be converted " .
4859 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER);
4860 $moddeletecourse($course, $showfeedback);
4862 if ($instances and $showfeedback) {
4863 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
4865 } else {
4866 // Ooops, this module is not properly installed, force-delete it in the next block.
4870 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
4872 // Remove all data from availability and completion tables that is associated
4873 // with course-modules belonging to this course. Note this is done even if the
4874 // features are not enabled now, in case they were enabled previously.
4875 $DB->delete_records_select('course_modules_completion',
4876 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4877 array($courseid));
4879 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
4880 $cms = $DB->get_records('course_modules', array('course' => $course->id));
4881 $allmodulesbyid = array_flip($allmodules);
4882 foreach ($cms as $cm) {
4883 if (array_key_exists($cm->module, $allmodulesbyid)) {
4884 try {
4885 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
4886 } catch (Exception $e) {
4887 // Ignore weird or missing table problems.
4890 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4891 $DB->delete_records('course_modules', array('id' => $cm->id));
4894 if ($showfeedback) {
4895 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
4898 // Cleanup the rest of plugins. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
4899 $cleanuplugintypes = array('report', 'coursereport', 'format');
4900 $callbacks = get_plugins_with_function('delete_course', 'lib.php');
4901 foreach ($cleanuplugintypes as $type) {
4902 if (!empty($callbacks[$type])) {
4903 foreach ($callbacks[$type] as $pluginfunction) {
4904 debugging("Callback delete_course is deprecated. Function $pluginfunction should be converted " .
4905 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER);
4906 $pluginfunction($course->id, $showfeedback);
4908 if ($showfeedback) {
4909 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
4914 // Delete questions and question categories.
4915 question_delete_course($course, $showfeedback);
4916 if ($showfeedback) {
4917 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
4920 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
4921 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4922 foreach ($childcontexts as $childcontext) {
4923 $childcontext->delete();
4925 unset($childcontexts);
4927 // Remove all roles and enrolments by default.
4928 if (empty($options['keep_roles_and_enrolments'])) {
4929 // This hack is used in restore when deleting contents of existing course.
4930 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
4931 enrol_course_delete($course);
4932 if ($showfeedback) {
4933 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
4937 // Delete any groups, removing members and grouping/course links first.
4938 if (empty($options['keep_groups_and_groupings'])) {
4939 groups_delete_groupings($course->id, $showfeedback);
4940 groups_delete_groups($course->id, $showfeedback);
4943 // Filters be gone!
4944 filter_delete_all_for_context($coursecontext->id);
4946 // Notes, you shall not pass!
4947 note_delete_all($course->id);
4949 // Die comments!
4950 comment::delete_comments($coursecontext->id);
4952 // Ratings are history too.
4953 $delopt = new stdclass();
4954 $delopt->contextid = $coursecontext->id;
4955 $rm = new rating_manager();
4956 $rm->delete_ratings($delopt);
4958 // Delete course tags.
4959 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
4961 // Notify the competency subsystem.
4962 \core_competency\api::hook_course_deleted($course);
4964 // Delete calendar events.
4965 $DB->delete_records('event', array('courseid' => $course->id));
4966 $fs->delete_area_files($coursecontext->id, 'calendar');
4968 // Delete all related records in other core tables that may have a courseid
4969 // This array stores the tables that need to be cleared, as
4970 // table_name => column_name that contains the course id.
4971 $tablestoclear = array(
4972 'backup_courses' => 'courseid', // Scheduled backup stuff.
4973 'user_lastaccess' => 'courseid', // User access info.
4975 foreach ($tablestoclear as $table => $col) {
4976 $DB->delete_records($table, array($col => $course->id));
4979 // Delete all course backup files.
4980 $fs->delete_area_files($coursecontext->id, 'backup');
4982 // Cleanup course record - remove links to deleted stuff.
4983 $oldcourse = new stdClass();
4984 $oldcourse->id = $course->id;
4985 $oldcourse->summary = '';
4986 $oldcourse->cacherev = 0;
4987 $oldcourse->legacyfiles = 0;
4988 if (!empty($options['keep_groups_and_groupings'])) {
4989 $oldcourse->defaultgroupingid = 0;
4991 $DB->update_record('course', $oldcourse);
4993 // Delete course sections.
4994 $DB->delete_records('course_sections', array('course' => $course->id));
4996 // Delete legacy, section and any other course files.
4997 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
4999 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5000 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5001 // Easy, do not delete the context itself...
5002 $coursecontext->delete_content();
5003 } else {
5004 // Hack alert!!!!
5005 // We can not drop all context stuff because it would bork enrolments and roles,
5006 // there might be also files used by enrol plugins...
5009 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5010 // also some non-standard unsupported plugins may try to store something there.
5011 fulldelete($CFG->dataroot.'/'.$course->id);
5013 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5014 $cachemodinfo = cache::make('core', 'coursemodinfo');
5015 $cachemodinfo->delete($courseid);
5017 // Trigger a course content deleted event.
5018 $event = \core\event\course_content_deleted::create(array(
5019 'objectid' => $course->id,
5020 'context' => $coursecontext,
5021 'other' => array('shortname' => $course->shortname,
5022 'fullname' => $course->fullname,
5023 'options' => $options) // Passing this for legacy reasons.
5025 $event->add_record_snapshot('course', $course);
5026 $event->trigger();
5028 return true;
5032 * Change dates in module - used from course reset.
5034 * @param string $modname forum, assignment, etc
5035 * @param array $fields array of date fields from mod table
5036 * @param int $timeshift time difference
5037 * @param int $courseid
5038 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5039 * @return bool success
5041 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5042 global $CFG, $DB;
5043 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5045 $return = true;
5046 $params = array($timeshift, $courseid);
5047 foreach ($fields as $field) {
5048 $updatesql = "UPDATE {".$modname."}
5049 SET $field = $field + ?
5050 WHERE course=? AND $field<>0";
5051 if ($modid) {
5052 $updatesql .= ' AND id=?';
5053 $params[] = $modid;
5055 $return = $DB->execute($updatesql, $params) && $return;
5058 $refreshfunction = $modname.'_refresh_events';
5059 if (function_exists($refreshfunction)) {
5060 $refreshfunction($courseid);
5063 return $return;
5067 * This function will empty a course of user data.
5068 * It will retain the activities and the structure of the course.
5070 * @param object $data an object containing all the settings including courseid (without magic quotes)
5071 * @return array status array of array component, item, error
5073 function reset_course_userdata($data) {
5074 global $CFG, $DB;
5075 require_once($CFG->libdir.'/gradelib.php');
5076 require_once($CFG->libdir.'/completionlib.php');
5077 require_once($CFG->dirroot.'/group/lib.php');
5079 $data->courseid = $data->id;
5080 $context = context_course::instance($data->courseid);
5082 $eventparams = array(
5083 'context' => $context,
5084 'courseid' => $data->id,
5085 'other' => array(
5086 'reset_options' => (array) $data
5089 $event = \core\event\course_reset_started::create($eventparams);
5090 $event->trigger();
5092 // Calculate the time shift of dates.
5093 if (!empty($data->reset_start_date)) {
5094 // Time part of course startdate should be zero.
5095 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5096 } else {
5097 $data->timeshift = 0;
5100 // Result array: component, item, error.
5101 $status = array();
5103 // Start the resetting.
5104 $componentstr = get_string('general');
5106 // Move the course start time.
5107 if (!empty($data->reset_start_date) and $data->timeshift) {
5108 // Change course start data.
5109 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5110 // Update all course and group events - do not move activity events.
5111 $updatesql = "UPDATE {event}
5112 SET timestart = timestart + ?
5113 WHERE courseid=? AND instance=0";
5114 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5116 // Update any date activity restrictions.
5117 if ($CFG->enableavailability) {
5118 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5121 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5124 if (!empty($data->reset_events)) {
5125 $DB->delete_records('event', array('courseid' => $data->courseid));
5126 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5129 if (!empty($data->reset_notes)) {
5130 require_once($CFG->dirroot.'/notes/lib.php');
5131 note_delete_all($data->courseid);
5132 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5135 if (!empty($data->delete_blog_associations)) {
5136 require_once($CFG->dirroot.'/blog/lib.php');
5137 blog_remove_associations_for_course($data->courseid);
5138 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5141 if (!empty($data->reset_completion)) {
5142 // Delete course and activity completion information.
5143 $course = $DB->get_record('course', array('id' => $data->courseid));
5144 $cc = new completion_info($course);
5145 $cc->delete_all_completion_data();
5146 $status[] = array('component' => $componentstr,
5147 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5150 if (!empty($data->reset_competency_ratings)) {
5151 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5152 $status[] = array('component' => $componentstr,
5153 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5156 $componentstr = get_string('roles');
5158 if (!empty($data->reset_roles_overrides)) {
5159 $children = $context->get_child_contexts();
5160 foreach ($children as $child) {
5161 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5163 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5164 // Force refresh for logged in users.
5165 $context->mark_dirty();
5166 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5169 if (!empty($data->reset_roles_local)) {
5170 $children = $context->get_child_contexts();
5171 foreach ($children as $child) {
5172 role_unassign_all(array('contextid' => $child->id));
5174 // Force refresh for logged in users.
5175 $context->mark_dirty();
5176 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5179 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5180 $data->unenrolled = array();
5181 if (!empty($data->unenrol_users)) {
5182 $plugins = enrol_get_plugins(true);
5183 $instances = enrol_get_instances($data->courseid, true);
5184 foreach ($instances as $key => $instance) {
5185 if (!isset($plugins[$instance->enrol])) {
5186 unset($instances[$key]);
5187 continue;
5191 foreach ($data->unenrol_users as $withroleid) {
5192 if ($withroleid) {
5193 $sql = "SELECT ue.*
5194 FROM {user_enrolments} ue
5195 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5196 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5197 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5198 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5200 } else {
5201 // Without any role assigned at course context.
5202 $sql = "SELECT ue.*
5203 FROM {user_enrolments} ue
5204 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5205 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5206 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5207 WHERE ra.id IS null";
5208 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5211 $rs = $DB->get_recordset_sql($sql, $params);
5212 foreach ($rs as $ue) {
5213 if (!isset($instances[$ue->enrolid])) {
5214 continue;
5216 $instance = $instances[$ue->enrolid];
5217 $plugin = $plugins[$instance->enrol];
5218 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5219 continue;
5222 $plugin->unenrol_user($instance, $ue->userid);
5223 $data->unenrolled[$ue->userid] = $ue->userid;
5225 $rs->close();
5228 if (!empty($data->unenrolled)) {
5229 $status[] = array(
5230 'component' => $componentstr,
5231 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5232 'error' => false
5236 $componentstr = get_string('groups');
5238 // Remove all group members.
5239 if (!empty($data->reset_groups_members)) {
5240 groups_delete_group_members($data->courseid);
5241 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5244 // Remove all groups.
5245 if (!empty($data->reset_groups_remove)) {
5246 groups_delete_groups($data->courseid, false);
5247 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5250 // Remove all grouping members.
5251 if (!empty($data->reset_groupings_members)) {
5252 groups_delete_groupings_groups($data->courseid, false);
5253 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5256 // Remove all groupings.
5257 if (!empty($data->reset_groupings_remove)) {
5258 groups_delete_groupings($data->courseid, false);
5259 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5262 // Look in every instance of every module for data to delete.
5263 $unsupportedmods = array();
5264 if ($allmods = $DB->get_records('modules') ) {
5265 foreach ($allmods as $mod) {
5266 $modname = $mod->name;
5267 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5268 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5269 if (file_exists($modfile)) {
5270 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5271 continue; // Skip mods with no instances.
5273 include_once($modfile);
5274 if (function_exists($moddeleteuserdata)) {
5275 $modstatus = $moddeleteuserdata($data);
5276 if (is_array($modstatus)) {
5277 $status = array_merge($status, $modstatus);
5278 } else {
5279 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5281 } else {
5282 $unsupportedmods[] = $mod;
5284 } else {
5285 debugging('Missing lib.php in '.$modname.' module!');
5290 // Mention unsupported mods.
5291 if (!empty($unsupportedmods)) {
5292 foreach ($unsupportedmods as $mod) {
5293 $status[] = array(
5294 'component' => get_string('modulenameplural', $mod->name),
5295 'item' => '',
5296 'error' => get_string('resetnotimplemented')
5301 $componentstr = get_string('gradebook', 'grades');
5302 // Reset gradebook,.
5303 if (!empty($data->reset_gradebook_items)) {
5304 remove_course_grades($data->courseid, false);
5305 grade_grab_course_grades($data->courseid);
5306 grade_regrade_final_grades($data->courseid);
5307 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5309 } else if (!empty($data->reset_gradebook_grades)) {
5310 grade_course_reset($data->courseid);
5311 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5313 // Reset comments.
5314 if (!empty($data->reset_comments)) {
5315 require_once($CFG->dirroot.'/comment/lib.php');
5316 comment::reset_course_page_comments($context);
5319 $event = \core\event\course_reset_ended::create($eventparams);
5320 $event->trigger();
5322 return $status;
5326 * Generate an email processing address.
5328 * @param int $modid
5329 * @param string $modargs
5330 * @return string Returns email processing address
5332 function generate_email_processing_address($modid, $modargs) {
5333 global $CFG;
5335 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5336 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5342 * @todo Finish documenting this function
5344 * @param string $modargs
5345 * @param string $body Currently unused
5347 function moodle_process_email($modargs, $body) {
5348 global $DB;
5350 // The first char should be an unencoded letter. We'll take this as an action.
5351 switch ($modargs{0}) {
5352 case 'B': { // Bounce.
5353 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5354 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5355 // Check the half md5 of their email.
5356 $md5check = substr(md5($user->email), 0, 16);
5357 if ($md5check == substr($modargs, -16)) {
5358 set_bounce_count($user);
5360 // Else maybe they've already changed it?
5363 break;
5364 // Maybe more later?
5368 // CORRESPONDENCE.
5371 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5373 * @param string $action 'get', 'buffer', 'close' or 'flush'
5374 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5376 function get_mailer($action='get') {
5377 global $CFG;
5379 /** @var moodle_phpmailer $mailer */
5380 static $mailer = null;
5381 static $counter = 0;
5383 if (!isset($CFG->smtpmaxbulk)) {
5384 $CFG->smtpmaxbulk = 1;
5387 if ($action == 'get') {
5388 $prevkeepalive = false;
5390 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5391 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5392 $counter++;
5393 // Reset the mailer.
5394 $mailer->Priority = 3;
5395 $mailer->CharSet = 'UTF-8'; // Our default.
5396 $mailer->ContentType = "text/plain";
5397 $mailer->Encoding = "8bit";
5398 $mailer->From = "root@localhost";
5399 $mailer->FromName = "Root User";
5400 $mailer->Sender = "";
5401 $mailer->Subject = "";
5402 $mailer->Body = "";
5403 $mailer->AltBody = "";
5404 $mailer->ConfirmReadingTo = "";
5406 $mailer->clearAllRecipients();
5407 $mailer->clearReplyTos();
5408 $mailer->clearAttachments();
5409 $mailer->clearCustomHeaders();
5410 return $mailer;
5413 $prevkeepalive = $mailer->SMTPKeepAlive;
5414 get_mailer('flush');
5417 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5418 $mailer = new moodle_phpmailer();
5420 $counter = 1;
5422 if ($CFG->smtphosts == 'qmail') {
5423 // Use Qmail system.
5424 $mailer->isQmail();
5426 } else if (empty($CFG->smtphosts)) {
5427 // Use PHP mail() = sendmail.
5428 $mailer->isMail();
5430 } else {
5431 // Use SMTP directly.
5432 $mailer->isSMTP();
5433 if (!empty($CFG->debugsmtp)) {
5434 $mailer->SMTPDebug = true;
5436 // Specify main and backup servers.
5437 $mailer->Host = $CFG->smtphosts;
5438 // Specify secure connection protocol.
5439 $mailer->SMTPSecure = $CFG->smtpsecure;
5440 // Use previous keepalive.
5441 $mailer->SMTPKeepAlive = $prevkeepalive;
5443 if ($CFG->smtpuser) {
5444 // Use SMTP authentication.
5445 $mailer->SMTPAuth = true;
5446 $mailer->Username = $CFG->smtpuser;
5447 $mailer->Password = $CFG->smtppass;
5451 return $mailer;
5454 $nothing = null;
5456 // Keep smtp session open after sending.
5457 if ($action == 'buffer') {
5458 if (!empty($CFG->smtpmaxbulk)) {
5459 get_mailer('flush');
5460 $m = get_mailer();
5461 if ($m->Mailer == 'smtp') {
5462 $m->SMTPKeepAlive = true;
5465 return $nothing;
5468 // Close smtp session, but continue buffering.
5469 if ($action == 'flush') {
5470 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5471 if (!empty($mailer->SMTPDebug)) {
5472 echo '<pre>'."\n";
5474 $mailer->SmtpClose();
5475 if (!empty($mailer->SMTPDebug)) {
5476 echo '</pre>';
5479 return $nothing;
5482 // Close smtp session, do not buffer anymore.
5483 if ($action == 'close') {
5484 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5485 get_mailer('flush');
5486 $mailer->SMTPKeepAlive = false;
5488 $mailer = null; // Better force new instance.
5489 return $nothing;
5494 * A helper function to test for email diversion
5496 * @param string $email
5497 * @return bool Returns true if the email should be diverted
5499 function email_should_be_diverted($email) {
5500 global $CFG;
5502 if (empty($CFG->divertallemailsto)) {
5503 return false;
5506 if (empty($CFG->divertallemailsexcept)) {
5507 return true;
5510 $patterns = array_map('trim', explode(',', $CFG->divertallemailsexcept));
5511 foreach ($patterns as $pattern) {
5512 if (preg_match("/$pattern/", $email)) {
5513 return false;
5517 return true;
5521 * Generate a unique email Message-ID using the moodle domain and install path
5523 * @param string $localpart An optional unique message id prefix.
5524 * @return string The formatted ID ready for appending to the email headers.
5526 function generate_email_messageid($localpart = null) {
5527 global $CFG;
5529 $urlinfo = parse_url($CFG->wwwroot);
5530 $base = '@' . $urlinfo['host'];
5532 // If multiple moodles are on the same domain we want to tell them
5533 // apart so we add the install path to the local part. This means
5534 // that the id local part should never contain a / character so
5535 // we can correctly parse the id to reassemble the wwwroot.
5536 if (isset($urlinfo['path'])) {
5537 $base = $urlinfo['path'] . $base;
5540 if (empty($localpart)) {
5541 $localpart = uniqid('', true);
5544 // Because we may have an option /installpath suffix to the local part
5545 // of the id we need to escape any / chars which are in the $localpart.
5546 $localpart = str_replace('/', '%2F', $localpart);
5548 return '<' . $localpart . $base . '>';
5552 * Send an email to a specified user
5554 * @param stdClass $user A {@link $USER} object
5555 * @param stdClass $from A {@link $USER} object
5556 * @param string $subject plain text subject line of the email
5557 * @param string $messagetext plain text version of the message
5558 * @param string $messagehtml complete html version of the message (optional)
5559 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5560 * @param string $attachname the name of the file (extension indicates MIME)
5561 * @param bool $usetrueaddress determines whether $from email address should
5562 * be sent out. Will be overruled by user profile setting for maildisplay
5563 * @param string $replyto Email address to reply to
5564 * @param string $replytoname Name of reply to recipient
5565 * @param int $wordwrapwidth custom word wrap width, default 79
5566 * @return bool Returns true if mail was sent OK and false if there was an error.
5568 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5569 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5571 global $CFG, $PAGE, $SITE;
5573 if (empty($user) or empty($user->id)) {
5574 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5575 return false;
5578 if (empty($user->email)) {
5579 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5580 return false;
5583 if (!empty($user->deleted)) {
5584 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5585 return false;
5588 if (defined('BEHAT_SITE_RUNNING')) {
5589 // Fake email sending in behat.
5590 return true;
5593 if (!empty($CFG->noemailever)) {
5594 // Hidden setting for development sites, set in config.php if needed.
5595 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5596 return true;
5599 if (email_should_be_diverted($user->email)) {
5600 $subject = "[DIVERTED {$user->email}] $subject";
5601 $user = clone($user);
5602 $user->email = $CFG->divertallemailsto;
5605 // Skip mail to suspended users.
5606 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5607 return true;
5610 if (!validate_email($user->email)) {
5611 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5612 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5613 return false;
5616 if (over_bounce_threshold($user)) {
5617 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5618 return false;
5621 // TLD .invalid is specifically reserved for invalid domain names.
5622 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5623 if (substr($user->email, -8) == '.invalid') {
5624 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5625 return true; // This is not an error.
5628 // If the user is a remote mnet user, parse the email text for URL to the
5629 // wwwroot and modify the url to direct the user's browser to login at their
5630 // home site (identity provider - idp) before hitting the link itself.
5631 if (is_mnet_remote_user($user)) {
5632 require_once($CFG->dirroot.'/mnet/lib.php');
5634 $jumpurl = mnet_get_idp_jump_url($user);
5635 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5637 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5638 $callback,
5639 $messagetext);
5640 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5641 $callback,
5642 $messagehtml);
5644 $mail = get_mailer();
5646 if (!empty($mail->SMTPDebug)) {
5647 echo '<pre>' . "\n";
5650 $temprecipients = array();
5651 $tempreplyto = array();
5653 $supportuser = core_user::get_support_user();
5655 // Make up an email address for handling bounces.
5656 if (!empty($CFG->handlebounces)) {
5657 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5658 $mail->Sender = generate_email_processing_address(0, $modargs);
5659 } else {
5660 $mail->Sender = $supportuser->email;
5663 if (!empty($CFG->emailonlyfromnoreplyaddress)) {
5664 $usetrueaddress = false;
5665 if (empty($replyto) && $from->maildisplay) {
5666 $replyto = $from->email;
5667 $replytoname = fullname($from);
5671 if (is_string($from)) { // So we can pass whatever we want if there is need.
5672 $mail->From = $CFG->noreplyaddress;
5673 $mail->FromName = $from;
5674 } else if ($usetrueaddress and $from->maildisplay) {
5675 $mail->From = $from->email;
5676 $mail->FromName = fullname($from);
5677 } else {
5678 $mail->From = $CFG->noreplyaddress;
5679 $mail->FromName = fullname($from);
5680 if (empty($replyto)) {
5681 $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
5685 if (!empty($replyto)) {
5686 $tempreplyto[] = array($replyto, $replytoname);
5689 $temprecipients[] = array($user->email, fullname($user));
5691 // Set word wrap.
5692 $mail->WordWrap = $wordwrapwidth;
5694 if (!empty($from->customheaders)) {
5695 // Add custom headers.
5696 if (is_array($from->customheaders)) {
5697 foreach ($from->customheaders as $customheader) {
5698 $mail->addCustomHeader($customheader);
5700 } else {
5701 $mail->addCustomHeader($from->customheaders);
5705 // If the X-PHP-Originating-Script email header is on then also add an additional
5706 // header with details of where exactly in moodle the email was triggered from,
5707 // either a call to message_send() or to email_to_user().
5708 if (ini_get('mail.add_x_header')) {
5710 $stack = debug_backtrace(false);
5711 $origin = $stack[0];
5713 foreach ($stack as $depth => $call) {
5714 if ($call['function'] == 'message_send') {
5715 $origin = $call;
5719 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
5720 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
5721 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
5724 if (!empty($from->priority)) {
5725 $mail->Priority = $from->priority;
5728 $renderer = $PAGE->get_renderer('core');
5729 $context = array(
5730 'sitefullname' => $SITE->fullname,
5731 'siteshortname' => $SITE->shortname,
5732 'sitewwwroot' => $CFG->wwwroot,
5733 'subject' => $subject,
5734 'to' => $user->email,
5735 'toname' => fullname($user),
5736 'from' => $mail->From,
5737 'fromname' => $mail->FromName,
5739 if (!empty($tempreplyto[0])) {
5740 $context['replyto'] = $tempreplyto[0][0];
5741 $context['replytoname'] = $tempreplyto[0][1];
5743 if ($user->id > 0) {
5744 $context['touserid'] = $user->id;
5745 $context['tousername'] = $user->username;
5748 if (!empty($user->mailformat) && $user->mailformat == 1) {
5749 // Only process html templates if the user preferences allow html email.
5751 if ($messagehtml) {
5752 // If html has been given then pass it through the template.
5753 $context['body'] = $messagehtml;
5754 $messagehtml = $renderer->render_from_template('core/email_html', $context);
5756 } else {
5757 // If no html has been given, BUT there is an html wrapping template then
5758 // auto convert the text to html and then wrap it.
5759 $autohtml = trim(text_to_html($messagetext));
5760 $context['body'] = $autohtml;
5761 $temphtml = $renderer->render_from_template('core/email_html', $context);
5762 if ($autohtml != $temphtml) {
5763 $messagehtml = $temphtml;
5768 $context['body'] = $messagetext;
5769 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
5770 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
5771 $messagetext = $renderer->render_from_template('core/email_text', $context);
5773 // Autogenerate a MessageID if it's missing.
5774 if (empty($mail->MessageID)) {
5775 $mail->MessageID = generate_email_messageid();
5778 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5779 // Don't ever send HTML to users who don't want it.
5780 $mail->isHTML(true);
5781 $mail->Encoding = 'quoted-printable';
5782 $mail->Body = $messagehtml;
5783 $mail->AltBody = "\n$messagetext\n";
5784 } else {
5785 $mail->IsHTML(false);
5786 $mail->Body = "\n$messagetext\n";
5789 if ($attachment && $attachname) {
5790 if (preg_match( "~\\.\\.~" , $attachment )) {
5791 // Security check for ".." in dir path.
5792 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5793 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5794 } else {
5795 require_once($CFG->libdir.'/filelib.php');
5796 $mimetype = mimeinfo('type', $attachname);
5798 $attachmentpath = $attachment;
5800 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5801 $attachpath = str_replace('\\', '/', $attachmentpath);
5802 // Make sure both variables are normalised before comparing.
5803 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
5805 // If the attachment is a full path to a file in the tempdir, use it as is,
5806 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5807 if (strpos($attachpath, $temppath) !== 0) {
5808 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
5811 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5815 // Check if the email should be sent in an other charset then the default UTF-8.
5816 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5818 // Use the defined site mail charset or eventually the one preferred by the recipient.
5819 $charset = $CFG->sitemailcharset;
5820 if (!empty($CFG->allowusermailcharset)) {
5821 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5822 $charset = $useremailcharset;
5826 // Convert all the necessary strings if the charset is supported.
5827 $charsets = get_list_of_charsets();
5828 unset($charsets['UTF-8']);
5829 if (in_array($charset, $charsets)) {
5830 $mail->CharSet = $charset;
5831 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
5832 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
5833 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
5834 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
5836 foreach ($temprecipients as $key => $values) {
5837 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5839 foreach ($tempreplyto as $key => $values) {
5840 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5845 foreach ($temprecipients as $values) {
5846 $mail->addAddress($values[0], $values[1]);
5848 foreach ($tempreplyto as $values) {
5849 $mail->addReplyTo($values[0], $values[1]);
5852 if ($mail->send()) {
5853 set_send_count($user);
5854 if (!empty($mail->SMTPDebug)) {
5855 echo '</pre>';
5857 return true;
5858 } else {
5859 // Trigger event for failing to send email.
5860 $event = \core\event\email_failed::create(array(
5861 'context' => context_system::instance(),
5862 'userid' => $from->id,
5863 'relateduserid' => $user->id,
5864 'other' => array(
5865 'subject' => $subject,
5866 'message' => $messagetext,
5867 'errorinfo' => $mail->ErrorInfo
5870 $event->trigger();
5871 if (CLI_SCRIPT) {
5872 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
5874 if (!empty($mail->SMTPDebug)) {
5875 echo '</pre>';
5877 return false;
5882 * Generate a signoff for emails based on support settings
5884 * @return string
5886 function generate_email_signoff() {
5887 global $CFG;
5889 $signoff = "\n";
5890 if (!empty($CFG->supportname)) {
5891 $signoff .= $CFG->supportname."\n";
5893 if (!empty($CFG->supportemail)) {
5894 $signoff .= $CFG->supportemail."\n";
5896 if (!empty($CFG->supportpage)) {
5897 $signoff .= $CFG->supportpage."\n";
5899 return $signoff;
5903 * Sets specified user's password and send the new password to the user via email.
5905 * @param stdClass $user A {@link $USER} object
5906 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
5907 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
5909 function setnew_password_and_mail($user, $fasthash = false) {
5910 global $CFG, $DB;
5912 // We try to send the mail in language the user understands,
5913 // unfortunately the filter_string() does not support alternative langs yet
5914 // so multilang will not work properly for site->fullname.
5915 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
5917 $site = get_site();
5919 $supportuser = core_user::get_support_user();
5921 $newpassword = generate_password();
5923 update_internal_user_password($user, $newpassword, $fasthash);
5925 $a = new stdClass();
5926 $a->firstname = fullname($user, true);
5927 $a->sitename = format_string($site->fullname);
5928 $a->username = $user->username;
5929 $a->newpassword = $newpassword;
5930 $a->link = $CFG->wwwroot .'/login/';
5931 $a->signoff = generate_email_signoff();
5933 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
5935 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
5937 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5938 return email_to_user($user, $supportuser, $subject, $message);
5943 * Resets specified user's password and send the new password to the user via email.
5945 * @param stdClass $user A {@link $USER} object
5946 * @return bool Returns true if mail was sent OK and false if there was an error.
5948 function reset_password_and_mail($user) {
5949 global $CFG;
5951 $site = get_site();
5952 $supportuser = core_user::get_support_user();
5954 $userauth = get_auth_plugin($user->auth);
5955 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
5956 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
5957 return false;
5960 $newpassword = generate_password();
5962 if (!$userauth->user_update_password($user, $newpassword)) {
5963 print_error("cannotsetpassword");
5966 $a = new stdClass();
5967 $a->firstname = $user->firstname;
5968 $a->lastname = $user->lastname;
5969 $a->sitename = format_string($site->fullname);
5970 $a->username = $user->username;
5971 $a->newpassword = $newpassword;
5972 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
5973 $a->signoff = generate_email_signoff();
5975 $message = get_string('newpasswordtext', '', $a);
5977 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
5979 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
5981 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5982 return email_to_user($user, $supportuser, $subject, $message);
5986 * Send email to specified user with confirmation text and activation link.
5988 * @param stdClass $user A {@link $USER} object
5989 * @return bool Returns true if mail was sent OK and false if there was an error.
5991 function send_confirmation_email($user) {
5992 global $CFG;
5994 $site = get_site();
5995 $supportuser = core_user::get_support_user();
5997 $data = new stdClass();
5998 $data->firstname = fullname($user);
5999 $data->sitename = format_string($site->fullname);
6000 $data->admin = generate_email_signoff();
6002 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6004 $username = urlencode($user->username);
6005 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
6006 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
6007 $message = get_string('emailconfirmation', '', $data);
6008 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6010 $user->mailformat = 1; // Always send HTML version as well.
6012 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6013 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6017 * Sends a password change confirmation email.
6019 * @param stdClass $user A {@link $USER} object
6020 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6021 * @return bool Returns true if mail was sent OK and false if there was an error.
6023 function send_password_change_confirmation_email($user, $resetrecord) {
6024 global $CFG;
6026 $site = get_site();
6027 $supportuser = core_user::get_support_user();
6028 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6030 $data = new stdClass();
6031 $data->firstname = $user->firstname;
6032 $data->lastname = $user->lastname;
6033 $data->username = $user->username;
6034 $data->sitename = format_string($site->fullname);
6035 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6036 $data->admin = generate_email_signoff();
6037 $data->resetminutes = $pwresetmins;
6039 $message = get_string('emailresetconfirmation', '', $data);
6040 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6042 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6043 return email_to_user($user, $supportuser, $subject, $message);
6048 * Sends an email containinginformation on how to change your password.
6050 * @param stdClass $user A {@link $USER} object
6051 * @return bool Returns true if mail was sent OK and false if there was an error.
6053 function send_password_change_info($user) {
6054 global $CFG;
6056 $site = get_site();
6057 $supportuser = core_user::get_support_user();
6058 $systemcontext = context_system::instance();
6060 $data = new stdClass();
6061 $data->firstname = $user->firstname;
6062 $data->lastname = $user->lastname;
6063 $data->sitename = format_string($site->fullname);
6064 $data->admin = generate_email_signoff();
6066 $userauth = get_auth_plugin($user->auth);
6068 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6069 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6070 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6071 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6072 return email_to_user($user, $supportuser, $subject, $message);
6075 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6076 // We have some external url for password changing.
6077 $data->link .= $userauth->change_password_url();
6079 } else {
6080 // No way to change password, sorry.
6081 $data->link = '';
6084 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6085 $message = get_string('emailpasswordchangeinfo', '', $data);
6086 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6087 } else {
6088 $message = get_string('emailpasswordchangeinfofail', '', $data);
6089 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6092 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6093 return email_to_user($user, $supportuser, $subject, $message);
6098 * Check that an email is allowed. It returns an error message if there was a problem.
6100 * @param string $email Content of email
6101 * @return string|false
6103 function email_is_not_allowed($email) {
6104 global $CFG;
6106 if (!empty($CFG->allowemailaddresses)) {
6107 $allowed = explode(' ', $CFG->allowemailaddresses);
6108 foreach ($allowed as $allowedpattern) {
6109 $allowedpattern = trim($allowedpattern);
6110 if (!$allowedpattern) {
6111 continue;
6113 if (strpos($allowedpattern, '.') === 0) {
6114 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6115 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6116 return false;
6119 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6120 return false;
6123 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6125 } else if (!empty($CFG->denyemailaddresses)) {
6126 $denied = explode(' ', $CFG->denyemailaddresses);
6127 foreach ($denied as $deniedpattern) {
6128 $deniedpattern = trim($deniedpattern);
6129 if (!$deniedpattern) {
6130 continue;
6132 if (strpos($deniedpattern, '.') === 0) {
6133 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6134 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6135 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6138 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6139 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6144 return false;
6147 // FILE HANDLING.
6150 * Returns local file storage instance
6152 * @return file_storage
6154 function get_file_storage() {
6155 global $CFG;
6157 static $fs = null;
6159 if ($fs) {
6160 return $fs;
6163 require_once("$CFG->libdir/filelib.php");
6165 if (isset($CFG->filedir)) {
6166 $filedir = $CFG->filedir;
6167 } else {
6168 $filedir = $CFG->dataroot.'/filedir';
6171 if (isset($CFG->trashdir)) {
6172 $trashdirdir = $CFG->trashdir;
6173 } else {
6174 $trashdirdir = $CFG->dataroot.'/trashdir';
6177 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
6179 return $fs;
6183 * Returns local file storage instance
6185 * @return file_browser
6187 function get_file_browser() {
6188 global $CFG;
6190 static $fb = null;
6192 if ($fb) {
6193 return $fb;
6196 require_once("$CFG->libdir/filelib.php");
6198 $fb = new file_browser();
6200 return $fb;
6204 * Returns file packer
6206 * @param string $mimetype default application/zip
6207 * @return file_packer
6209 function get_file_packer($mimetype='application/zip') {
6210 global $CFG;
6212 static $fp = array();
6214 if (isset($fp[$mimetype])) {
6215 return $fp[$mimetype];
6218 switch ($mimetype) {
6219 case 'application/zip':
6220 case 'application/vnd.moodle.profiling':
6221 $classname = 'zip_packer';
6222 break;
6224 case 'application/x-gzip' :
6225 $classname = 'tgz_packer';
6226 break;
6228 case 'application/vnd.moodle.backup':
6229 $classname = 'mbz_packer';
6230 break;
6232 default:
6233 return false;
6236 require_once("$CFG->libdir/filestorage/$classname.php");
6237 $fp[$mimetype] = new $classname();
6239 return $fp[$mimetype];
6243 * Returns current name of file on disk if it exists.
6245 * @param string $newfile File to be verified
6246 * @return string Current name of file on disk if true
6248 function valid_uploaded_file($newfile) {
6249 if (empty($newfile)) {
6250 return '';
6252 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6253 return $newfile['tmp_name'];
6254 } else {
6255 return '';
6260 * Returns the maximum size for uploading files.
6262 * There are seven possible upload limits:
6263 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6264 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6265 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6266 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6267 * 5. by the Moodle admin in $CFG->maxbytes
6268 * 6. by the teacher in the current course $course->maxbytes
6269 * 7. by the teacher for the current module, eg $assignment->maxbytes
6271 * These last two are passed to this function as arguments (in bytes).
6272 * Anything defined as 0 is ignored.
6273 * The smallest of all the non-zero numbers is returned.
6275 * @todo Finish documenting this function
6277 * @param int $sitebytes Set maximum size
6278 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6279 * @param int $modulebytes Current module ->maxbytes (in bytes)
6280 * @param bool $unused This parameter has been deprecated and is not used any more.
6281 * @return int The maximum size for uploading files.
6283 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6285 if (! $filesize = ini_get('upload_max_filesize')) {
6286 $filesize = '5M';
6288 $minimumsize = get_real_size($filesize);
6290 if ($postsize = ini_get('post_max_size')) {
6291 $postsize = get_real_size($postsize);
6292 if ($postsize < $minimumsize) {
6293 $minimumsize = $postsize;
6297 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6298 $minimumsize = $sitebytes;
6301 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6302 $minimumsize = $coursebytes;
6305 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6306 $minimumsize = $modulebytes;
6309 return $minimumsize;
6313 * Returns the maximum size for uploading files for the current user
6315 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6317 * @param context $context The context in which to check user capabilities
6318 * @param int $sitebytes Set maximum size
6319 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6320 * @param int $modulebytes Current module ->maxbytes (in bytes)
6321 * @param stdClass $user The user
6322 * @param bool $unused This parameter has been deprecated and is not used any more.
6323 * @return int The maximum size for uploading files.
6325 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6326 $unused = false) {
6327 global $USER;
6329 if (empty($user)) {
6330 $user = $USER;
6333 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6334 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6337 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6341 * Returns an array of possible sizes in local language
6343 * Related to {@link get_max_upload_file_size()} - this function returns an
6344 * array of possible sizes in an array, translated to the
6345 * local language.
6347 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6349 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6350 * with the value set to 0. This option will be the first in the list.
6352 * @uses SORT_NUMERIC
6353 * @param int $sitebytes Set maximum size
6354 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6355 * @param int $modulebytes Current module ->maxbytes (in bytes)
6356 * @param int|array $custombytes custom upload size/s which will be added to list,
6357 * Only value/s smaller then maxsize will be added to list.
6358 * @return array
6360 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6361 global $CFG;
6363 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6364 return array();
6367 if ($sitebytes == 0) {
6368 // Will get the minimum of upload_max_filesize or post_max_size.
6369 $sitebytes = get_max_upload_file_size();
6372 $filesize = array();
6373 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6374 5242880, 10485760, 20971520, 52428800, 104857600);
6376 // If custombytes is given and is valid then add it to the list.
6377 if (is_number($custombytes) and $custombytes > 0) {
6378 $custombytes = (int)$custombytes;
6379 if (!in_array($custombytes, $sizelist)) {
6380 $sizelist[] = $custombytes;
6382 } else if (is_array($custombytes)) {
6383 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6386 // Allow maxbytes to be selected if it falls outside the above boundaries.
6387 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6388 // Note: get_real_size() is used in order to prevent problems with invalid values.
6389 $sizelist[] = get_real_size($CFG->maxbytes);
6392 foreach ($sizelist as $sizebytes) {
6393 if ($sizebytes < $maxsize && $sizebytes > 0) {
6394 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6398 $limitlevel = '';
6399 $displaysize = '';
6400 if ($modulebytes &&
6401 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6402 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6403 $limitlevel = get_string('activity', 'core');
6404 $displaysize = display_size($modulebytes);
6405 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6407 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6408 $limitlevel = get_string('course', 'core');
6409 $displaysize = display_size($coursebytes);
6410 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6412 } else if ($sitebytes) {
6413 $limitlevel = get_string('site', 'core');
6414 $displaysize = display_size($sitebytes);
6415 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6418 krsort($filesize, SORT_NUMERIC);
6419 if ($limitlevel) {
6420 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6421 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6424 return $filesize;
6428 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6430 * If excludefiles is defined, then that file/directory is ignored
6431 * If getdirs is true, then (sub)directories are included in the output
6432 * If getfiles is true, then files are included in the output
6433 * (at least one of these must be true!)
6435 * @todo Finish documenting this function. Add examples of $excludefile usage.
6437 * @param string $rootdir A given root directory to start from
6438 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6439 * @param bool $descend If true then subdirectories are recursed as well
6440 * @param bool $getdirs If true then (sub)directories are included in the output
6441 * @param bool $getfiles If true then files are included in the output
6442 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6444 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6446 $dirs = array();
6448 if (!$getdirs and !$getfiles) { // Nothing to show.
6449 return $dirs;
6452 if (!is_dir($rootdir)) { // Must be a directory.
6453 return $dirs;
6456 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6457 return $dirs;
6460 if (!is_array($excludefiles)) {
6461 $excludefiles = array($excludefiles);
6464 while (false !== ($file = readdir($dir))) {
6465 $firstchar = substr($file, 0, 1);
6466 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6467 continue;
6469 $fullfile = $rootdir .'/'. $file;
6470 if (filetype($fullfile) == 'dir') {
6471 if ($getdirs) {
6472 $dirs[] = $file;
6474 if ($descend) {
6475 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6476 foreach ($subdirs as $subdir) {
6477 $dirs[] = $file .'/'. $subdir;
6480 } else if ($getfiles) {
6481 $dirs[] = $file;
6484 closedir($dir);
6486 asort($dirs);
6488 return $dirs;
6493 * Adds up all the files in a directory and works out the size.
6495 * @param string $rootdir The directory to start from
6496 * @param string $excludefile A file to exclude when summing directory size
6497 * @return int The summed size of all files and subfiles within the root directory
6499 function get_directory_size($rootdir, $excludefile='') {
6500 global $CFG;
6502 // Do it this way if we can, it's much faster.
6503 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6504 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6505 $output = null;
6506 $return = null;
6507 exec($command, $output, $return);
6508 if (is_array($output)) {
6509 // We told it to return k.
6510 return get_real_size(intval($output[0]).'k');
6514 if (!is_dir($rootdir)) {
6515 // Must be a directory.
6516 return 0;
6519 if (!$dir = @opendir($rootdir)) {
6520 // Can't open it for some reason.
6521 return 0;
6524 $size = 0;
6526 while (false !== ($file = readdir($dir))) {
6527 $firstchar = substr($file, 0, 1);
6528 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6529 continue;
6531 $fullfile = $rootdir .'/'. $file;
6532 if (filetype($fullfile) == 'dir') {
6533 $size += get_directory_size($fullfile, $excludefile);
6534 } else {
6535 $size += filesize($fullfile);
6538 closedir($dir);
6540 return $size;
6544 * Converts bytes into display form
6546 * @static string $gb Localized string for size in gigabytes
6547 * @static string $mb Localized string for size in megabytes
6548 * @static string $kb Localized string for size in kilobytes
6549 * @static string $b Localized string for size in bytes
6550 * @param int $size The size to convert to human readable form
6551 * @return string
6553 function display_size($size) {
6555 static $gb, $mb, $kb, $b;
6557 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6558 return get_string('unlimited');
6561 if (empty($gb)) {
6562 $gb = get_string('sizegb');
6563 $mb = get_string('sizemb');
6564 $kb = get_string('sizekb');
6565 $b = get_string('sizeb');
6568 if ($size >= 1073741824) {
6569 $size = round($size / 1073741824 * 10) / 10 . $gb;
6570 } else if ($size >= 1048576) {
6571 $size = round($size / 1048576 * 10) / 10 . $mb;
6572 } else if ($size >= 1024) {
6573 $size = round($size / 1024 * 10) / 10 . $kb;
6574 } else {
6575 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6577 return $size;
6581 * Cleans a given filename by removing suspicious or troublesome characters
6583 * @see clean_param()
6584 * @param string $string file name
6585 * @return string cleaned file name
6587 function clean_filename($string) {
6588 return clean_param($string, PARAM_FILE);
6592 // STRING TRANSLATION.
6595 * Returns the code for the current language
6597 * @category string
6598 * @return string
6600 function current_language() {
6601 global $CFG, $USER, $SESSION, $COURSE;
6603 if (!empty($SESSION->forcelang)) {
6604 // Allows overriding course-forced language (useful for admins to check
6605 // issues in courses whose language they don't understand).
6606 // Also used by some code to temporarily get language-related information in a
6607 // specific language (see force_current_language()).
6608 $return = $SESSION->forcelang;
6610 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6611 // Course language can override all other settings for this page.
6612 $return = $COURSE->lang;
6614 } else if (!empty($SESSION->lang)) {
6615 // Session language can override other settings.
6616 $return = $SESSION->lang;
6618 } else if (!empty($USER->lang)) {
6619 $return = $USER->lang;
6621 } else if (isset($CFG->lang)) {
6622 $return = $CFG->lang;
6624 } else {
6625 $return = 'en';
6628 // Just in case this slipped in from somewhere by accident.
6629 $return = str_replace('_utf8', '', $return);
6631 return $return;
6635 * Returns parent language of current active language if defined
6637 * @category string
6638 * @param string $lang null means current language
6639 * @return string
6641 function get_parent_language($lang=null) {
6643 // Let's hack around the current language.
6644 if (!empty($lang)) {
6645 $oldforcelang = force_current_language($lang);
6648 $parentlang = get_string('parentlanguage', 'langconfig');
6649 if ($parentlang === 'en') {
6650 $parentlang = '';
6653 // Let's hack around the current language.
6654 if (!empty($lang)) {
6655 force_current_language($oldforcelang);
6658 return $parentlang;
6662 * Force the current language to get strings and dates localised in the given language.
6664 * After calling this function, all strings will be provided in the given language
6665 * until this function is called again, or equivalent code is run.
6667 * @param string $language
6668 * @return string previous $SESSION->forcelang value
6670 function force_current_language($language) {
6671 global $SESSION;
6672 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6673 if ($language !== $sessionforcelang) {
6674 // Seting forcelang to null or an empty string disables it's effect.
6675 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6676 $SESSION->forcelang = $language;
6677 moodle_setlocale();
6680 return $sessionforcelang;
6684 * Returns current string_manager instance.
6686 * The param $forcereload is needed for CLI installer only where the string_manager instance
6687 * must be replaced during the install.php script life time.
6689 * @category string
6690 * @param bool $forcereload shall the singleton be released and new instance created instead?
6691 * @return core_string_manager
6693 function get_string_manager($forcereload=false) {
6694 global $CFG;
6696 static $singleton = null;
6698 if ($forcereload) {
6699 $singleton = null;
6701 if ($singleton === null) {
6702 if (empty($CFG->early_install_lang)) {
6704 if (empty($CFG->langlist)) {
6705 $translist = array();
6706 } else {
6707 $translist = explode(',', $CFG->langlist);
6710 if (!empty($CFG->config_php_settings['customstringmanager'])) {
6711 $classname = $CFG->config_php_settings['customstringmanager'];
6713 if (class_exists($classname)) {
6714 $implements = class_implements($classname);
6716 if (isset($implements['core_string_manager'])) {
6717 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist);
6718 return $singleton;
6720 } else {
6721 debugging('Unable to instantiate custom string manager: class '.$classname.
6722 ' does not implement the core_string_manager interface.');
6725 } else {
6726 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
6730 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6732 } else {
6733 $singleton = new core_string_manager_install();
6737 return $singleton;
6741 * Returns a localized string.
6743 * Returns the translated string specified by $identifier as
6744 * for $module. Uses the same format files as STphp.
6745 * $a is an object, string or number that can be used
6746 * within translation strings
6748 * eg 'hello {$a->firstname} {$a->lastname}'
6749 * or 'hello {$a}'
6751 * If you would like to directly echo the localized string use
6752 * the function {@link print_string()}
6754 * Example usage of this function involves finding the string you would
6755 * like a local equivalent of and using its identifier and module information
6756 * to retrieve it.<br/>
6757 * If you open moodle/lang/en/moodle.php and look near line 278
6758 * you will find a string to prompt a user for their word for 'course'
6759 * <code>
6760 * $string['course'] = 'Course';
6761 * </code>
6762 * So if you want to display the string 'Course'
6763 * in any language that supports it on your site
6764 * you just need to use the identifier 'course'
6765 * <code>
6766 * $mystring = '<strong>'. get_string('course') .'</strong>';
6767 * or
6768 * </code>
6769 * If the string you want is in another file you'd take a slightly
6770 * different approach. Looking in moodle/lang/en/calendar.php you find
6771 * around line 75:
6772 * <code>
6773 * $string['typecourse'] = 'Course event';
6774 * </code>
6775 * If you want to display the string "Course event" in any language
6776 * supported you would use the identifier 'typecourse' and the module 'calendar'
6777 * (because it is in the file calendar.php):
6778 * <code>
6779 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6780 * </code>
6782 * As a last resort, should the identifier fail to map to a string
6783 * the returned string will be [[ $identifier ]]
6785 * In Moodle 2.3 there is a new argument to this function $lazyload.
6786 * Setting $lazyload to true causes get_string to return a lang_string object
6787 * rather than the string itself. The fetching of the string is then put off until
6788 * the string object is first used. The object can be used by calling it's out
6789 * method or by casting the object to a string, either directly e.g.
6790 * (string)$stringobject
6791 * or indirectly by using the string within another string or echoing it out e.g.
6792 * echo $stringobject
6793 * return "<p>{$stringobject}</p>";
6794 * It is worth noting that using $lazyload and attempting to use the string as an
6795 * array key will cause a fatal error as objects cannot be used as array keys.
6796 * But you should never do that anyway!
6797 * For more information {@link lang_string}
6799 * @category string
6800 * @param string $identifier The key identifier for the localized string
6801 * @param string $component The module where the key identifier is stored,
6802 * usually expressed as the filename in the language pack without the
6803 * .php on the end but can also be written as mod/forum or grade/export/xls.
6804 * If none is specified then moodle.php is used.
6805 * @param string|object|array $a An object, string or number that can be used
6806 * within translation strings
6807 * @param bool $lazyload If set to true a string object is returned instead of
6808 * the string itself. The string then isn't calculated until it is first used.
6809 * @return string The localized string.
6810 * @throws coding_exception
6812 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6813 global $CFG;
6815 // If the lazy load argument has been supplied return a lang_string object
6816 // instead.
6817 // We need to make sure it is true (and a bool) as you will see below there
6818 // used to be a forth argument at one point.
6819 if ($lazyload === true) {
6820 return new lang_string($identifier, $component, $a);
6823 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
6824 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
6827 // There is now a forth argument again, this time it is a boolean however so
6828 // we can still check for the old extralocations parameter.
6829 if (!is_bool($lazyload) && !empty($lazyload)) {
6830 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6833 if (strpos($component, '/') !== false) {
6834 debugging('The module name you passed to get_string is the deprecated format ' .
6835 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
6836 $componentpath = explode('/', $component);
6838 switch ($componentpath[0]) {
6839 case 'mod':
6840 $component = $componentpath[1];
6841 break;
6842 case 'blocks':
6843 case 'block':
6844 $component = 'block_'.$componentpath[1];
6845 break;
6846 case 'enrol':
6847 $component = 'enrol_'.$componentpath[1];
6848 break;
6849 case 'format':
6850 $component = 'format_'.$componentpath[1];
6851 break;
6852 case 'grade':
6853 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6854 break;
6858 $result = get_string_manager()->get_string($identifier, $component, $a);
6860 // Debugging feature lets you display string identifier and component.
6861 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
6862 $result .= ' {' . $identifier . '/' . $component . '}';
6864 return $result;
6868 * Converts an array of strings to their localized value.
6870 * @param array $array An array of strings
6871 * @param string $component The language module that these strings can be found in.
6872 * @return stdClass translated strings.
6874 function get_strings($array, $component = '') {
6875 $string = new stdClass;
6876 foreach ($array as $item) {
6877 $string->$item = get_string($item, $component);
6879 return $string;
6883 * Prints out a translated string.
6885 * Prints out a translated string using the return value from the {@link get_string()} function.
6887 * Example usage of this function when the string is in the moodle.php file:<br/>
6888 * <code>
6889 * echo '<strong>';
6890 * print_string('course');
6891 * echo '</strong>';
6892 * </code>
6894 * Example usage of this function when the string is not in the moodle.php file:<br/>
6895 * <code>
6896 * echo '<h1>';
6897 * print_string('typecourse', 'calendar');
6898 * echo '</h1>';
6899 * </code>
6901 * @category string
6902 * @param string $identifier The key identifier for the localized string
6903 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
6904 * @param string|object|array $a An object, string or number that can be used within translation strings
6906 function print_string($identifier, $component = '', $a = null) {
6907 echo get_string($identifier, $component, $a);
6911 * Returns a list of charset codes
6913 * Returns a list of charset codes. It's hardcoded, so they should be added manually
6914 * (checking that such charset is supported by the texlib library!)
6916 * @return array And associative array with contents in the form of charset => charset
6918 function get_list_of_charsets() {
6920 $charsets = array(
6921 'EUC-JP' => 'EUC-JP',
6922 'ISO-2022-JP'=> 'ISO-2022-JP',
6923 'ISO-8859-1' => 'ISO-8859-1',
6924 'SHIFT-JIS' => 'SHIFT-JIS',
6925 'GB2312' => 'GB2312',
6926 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
6927 'UTF-8' => 'UTF-8');
6929 asort($charsets);
6931 return $charsets;
6935 * Returns a list of valid and compatible themes
6937 * @return array
6939 function get_list_of_themes() {
6940 global $CFG;
6942 $themes = array();
6944 if (!empty($CFG->themelist)) { // Use admin's list of themes.
6945 $themelist = explode(',', $CFG->themelist);
6946 } else {
6947 $themelist = array_keys(core_component::get_plugin_list("theme"));
6950 foreach ($themelist as $key => $themename) {
6951 $theme = theme_config::load($themename);
6952 $themes[$themename] = $theme;
6955 core_collator::asort_objects_by_method($themes, 'get_theme_name');
6957 return $themes;
6961 * Factory function for emoticon_manager
6963 * @return emoticon_manager singleton
6965 function get_emoticon_manager() {
6966 static $singleton = null;
6968 if (is_null($singleton)) {
6969 $singleton = new emoticon_manager();
6972 return $singleton;
6976 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
6978 * Whenever this manager mentiones 'emoticon object', the following data
6979 * structure is expected: stdClass with properties text, imagename, imagecomponent,
6980 * altidentifier and altcomponent
6982 * @see admin_setting_emoticons
6984 * @copyright 2010 David Mudrak
6985 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6987 class emoticon_manager {
6990 * Returns the currently enabled emoticons
6992 * @return array of emoticon objects
6994 public function get_emoticons() {
6995 global $CFG;
6997 if (empty($CFG->emoticons)) {
6998 return array();
7001 $emoticons = $this->decode_stored_config($CFG->emoticons);
7003 if (!is_array($emoticons)) {
7004 // Something is wrong with the format of stored setting.
7005 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7006 return array();
7009 return $emoticons;
7013 * Converts emoticon object into renderable pix_emoticon object
7015 * @param stdClass $emoticon emoticon object
7016 * @param array $attributes explicit HTML attributes to set
7017 * @return pix_emoticon
7019 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7020 $stringmanager = get_string_manager();
7021 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7022 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7023 } else {
7024 $alt = s($emoticon->text);
7026 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7030 * Encodes the array of emoticon objects into a string storable in config table
7032 * @see self::decode_stored_config()
7033 * @param array $emoticons array of emtocion objects
7034 * @return string
7036 public function encode_stored_config(array $emoticons) {
7037 return json_encode($emoticons);
7041 * Decodes the string into an array of emoticon objects
7043 * @see self::encode_stored_config()
7044 * @param string $encoded
7045 * @return string|null
7047 public function decode_stored_config($encoded) {
7048 $decoded = json_decode($encoded);
7049 if (!is_array($decoded)) {
7050 return null;
7052 return $decoded;
7056 * Returns default set of emoticons supported by Moodle
7058 * @return array of sdtClasses
7060 public function default_emoticons() {
7061 return array(
7062 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7063 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7064 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7065 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7066 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7067 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7068 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7069 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7070 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7071 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7072 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7073 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7074 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7075 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7076 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7077 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7078 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7079 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7080 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7081 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7082 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7083 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7084 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7085 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7086 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7087 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7088 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7089 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7090 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7091 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7096 * Helper method preparing the stdClass with the emoticon properties
7098 * @param string|array $text or array of strings
7099 * @param string $imagename to be used by {@link pix_emoticon}
7100 * @param string $altidentifier alternative string identifier, null for no alt
7101 * @param string $altcomponent where the alternative string is defined
7102 * @param string $imagecomponent to be used by {@link pix_emoticon}
7103 * @return stdClass
7105 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7106 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7107 return (object)array(
7108 'text' => $text,
7109 'imagename' => $imagename,
7110 'imagecomponent' => $imagecomponent,
7111 'altidentifier' => $altidentifier,
7112 'altcomponent' => $altcomponent,
7117 // ENCRYPTION.
7120 * rc4encrypt
7122 * @param string $data Data to encrypt.
7123 * @return string The now encrypted data.
7125 function rc4encrypt($data) {
7126 return endecrypt(get_site_identifier(), $data, '');
7130 * rc4decrypt
7132 * @param string $data Data to decrypt.
7133 * @return string The now decrypted data.
7135 function rc4decrypt($data) {
7136 return endecrypt(get_site_identifier(), $data, 'de');
7140 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7142 * @todo Finish documenting this function
7144 * @param string $pwd The password to use when encrypting or decrypting
7145 * @param string $data The data to be decrypted/encrypted
7146 * @param string $case Either 'de' for decrypt or '' for encrypt
7147 * @return string
7149 function endecrypt ($pwd, $data, $case) {
7151 if ($case == 'de') {
7152 $data = urldecode($data);
7155 $key[] = '';
7156 $box[] = '';
7157 $pwdlength = strlen($pwd);
7159 for ($i = 0; $i <= 255; $i++) {
7160 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7161 $box[$i] = $i;
7164 $x = 0;
7166 for ($i = 0; $i <= 255; $i++) {
7167 $x = ($x + $box[$i] + $key[$i]) % 256;
7168 $tempswap = $box[$i];
7169 $box[$i] = $box[$x];
7170 $box[$x] = $tempswap;
7173 $cipher = '';
7175 $a = 0;
7176 $j = 0;
7178 for ($i = 0; $i < strlen($data); $i++) {
7179 $a = ($a + 1) % 256;
7180 $j = ($j + $box[$a]) % 256;
7181 $temp = $box[$a];
7182 $box[$a] = $box[$j];
7183 $box[$j] = $temp;
7184 $k = $box[(($box[$a] + $box[$j]) % 256)];
7185 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7186 $cipher .= chr($cipherby);
7189 if ($case == 'de') {
7190 $cipher = urldecode(urlencode($cipher));
7191 } else {
7192 $cipher = urlencode($cipher);
7195 return $cipher;
7198 // ENVIRONMENT CHECKING.
7201 * This method validates a plug name. It is much faster than calling clean_param.
7203 * @param string $name a string that might be a plugin name.
7204 * @return bool if this string is a valid plugin name.
7206 function is_valid_plugin_name($name) {
7207 // This does not work for 'mod', bad luck, use any other type.
7208 return core_component::is_valid_plugin_name('tool', $name);
7212 * Get a list of all the plugins of a given type that define a certain API function
7213 * in a certain file. The plugin component names and function names are returned.
7215 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7216 * @param string $function the part of the name of the function after the
7217 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7218 * names like report_courselist_hook.
7219 * @param string $file the name of file within the plugin that defines the
7220 * function. Defaults to lib.php.
7221 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7222 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7224 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7225 global $CFG;
7227 // We don't include here as all plugin types files would be included.
7228 $plugins = get_plugins_with_function($function, $file, false);
7230 if (empty($plugins[$plugintype])) {
7231 return array();
7234 $allplugins = core_component::get_plugin_list($plugintype);
7236 // Reformat the array and include the files.
7237 $pluginfunctions = array();
7238 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7240 // Check that it has not been removed and the file is still available.
7241 if (!empty($allplugins[$pluginname])) {
7243 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7244 if (file_exists($filepath)) {
7245 include_once($filepath);
7246 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7251 return $pluginfunctions;
7255 * Get a list of all the plugins that define a certain API function in a certain file.
7257 * @param string $function the part of the name of the function after the
7258 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7259 * names like report_courselist_hook.
7260 * @param string $file the name of file within the plugin that defines the
7261 * function. Defaults to lib.php.
7262 * @param bool $include Whether to include the files that contain the functions or not.
7263 * @return array with [plugintype][plugin] = functionname
7265 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7266 global $CFG;
7268 $cache = \cache::make('core', 'plugin_functions');
7270 // Including both although I doubt that we will find two functions definitions with the same name.
7271 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7272 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7274 if ($pluginfunctions = $cache->get($key)) {
7276 // Checking that the files are still available.
7277 foreach ($pluginfunctions as $plugintype => $plugins) {
7279 $allplugins = \core_component::get_plugin_list($plugintype);
7280 foreach ($plugins as $plugin => $fullpath) {
7282 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7283 if (empty($allplugins[$plugin])) {
7284 unset($pluginfunctions[$plugintype][$plugin]);
7285 continue;
7288 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7289 if ($include && $fileexists) {
7290 // Include the files if it was requested.
7291 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7292 } else if (!$fileexists) {
7293 // If the file is not available any more it should not be returned.
7294 unset($pluginfunctions[$plugintype][$plugin]);
7298 return $pluginfunctions;
7301 $pluginfunctions = array();
7303 // To fill the cached. Also, everything should continue working with cache disabled.
7304 $plugintypes = \core_component::get_plugin_types();
7305 foreach ($plugintypes as $plugintype => $unused) {
7307 // We need to include files here.
7308 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7309 foreach ($pluginswithfile as $plugin => $notused) {
7311 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7313 $pluginfunction = false;
7314 if (function_exists($fullfunction)) {
7315 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7316 $pluginfunction = $fullfunction;
7318 } else if ($plugintype === 'mod') {
7319 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7320 $shortfunction = $plugin . '_' . $function;
7321 if (function_exists($shortfunction)) {
7322 $pluginfunction = $shortfunction;
7326 if ($pluginfunction) {
7327 if (empty($pluginfunctions[$plugintype])) {
7328 $pluginfunctions[$plugintype] = array();
7330 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7335 $cache->set($key, $pluginfunctions);
7337 return $pluginfunctions;
7342 * Lists plugin-like directories within specified directory
7344 * This function was originally used for standard Moodle plugins, please use
7345 * new core_component::get_plugin_list() now.
7347 * This function is used for general directory listing and backwards compatility.
7349 * @param string $directory relative directory from root
7350 * @param string $exclude dir name to exclude from the list (defaults to none)
7351 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7352 * @return array Sorted array of directory names found under the requested parameters
7354 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7355 global $CFG;
7357 $plugins = array();
7359 if (empty($basedir)) {
7360 $basedir = $CFG->dirroot .'/'. $directory;
7362 } else {
7363 $basedir = $basedir .'/'. $directory;
7366 if ($CFG->debugdeveloper and empty($exclude)) {
7367 // Make sure devs do not use this to list normal plugins,
7368 // this is intended for general directories that are not plugins!
7370 $subtypes = core_component::get_plugin_types();
7371 if (in_array($basedir, $subtypes)) {
7372 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7374 unset($subtypes);
7377 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7378 if (!$dirhandle = opendir($basedir)) {
7379 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7380 return array();
7382 while (false !== ($dir = readdir($dirhandle))) {
7383 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7384 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7385 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7386 continue;
7388 if (filetype($basedir .'/'. $dir) != 'dir') {
7389 continue;
7391 $plugins[] = $dir;
7393 closedir($dirhandle);
7395 if ($plugins) {
7396 asort($plugins);
7398 return $plugins;
7402 * Invoke plugin's callback functions
7404 * @param string $type plugin type e.g. 'mod'
7405 * @param string $name plugin name
7406 * @param string $feature feature name
7407 * @param string $action feature's action
7408 * @param array $params parameters of callback function, should be an array
7409 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7410 * @return mixed
7412 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7414 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7415 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7419 * Invoke component's callback functions
7421 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7422 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7423 * @param array $params parameters of callback function
7424 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7425 * @return mixed
7427 function component_callback($component, $function, array $params = array(), $default = null) {
7429 $functionname = component_callback_exists($component, $function);
7431 if ($functionname) {
7432 // Function exists, so just return function result.
7433 $ret = call_user_func_array($functionname, $params);
7434 if (is_null($ret)) {
7435 return $default;
7436 } else {
7437 return $ret;
7440 return $default;
7444 * Determine if a component callback exists and return the function name to call. Note that this
7445 * function will include the required library files so that the functioname returned can be
7446 * called directly.
7448 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7449 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7450 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7451 * @throws coding_exception if invalid component specfied
7453 function component_callback_exists($component, $function) {
7454 global $CFG; // This is needed for the inclusions.
7456 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7457 if (empty($cleancomponent)) {
7458 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7460 $component = $cleancomponent;
7462 list($type, $name) = core_component::normalize_component($component);
7463 $component = $type . '_' . $name;
7465 $oldfunction = $name.'_'.$function;
7466 $function = $component.'_'.$function;
7468 $dir = core_component::get_component_directory($component);
7469 if (empty($dir)) {
7470 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7473 // Load library and look for function.
7474 if (file_exists($dir.'/lib.php')) {
7475 require_once($dir.'/lib.php');
7478 if (!function_exists($function) and function_exists($oldfunction)) {
7479 if ($type !== 'mod' and $type !== 'core') {
7480 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7482 $function = $oldfunction;
7485 if (function_exists($function)) {
7486 return $function;
7488 return false;
7492 * Checks whether a plugin supports a specified feature.
7494 * @param string $type Plugin type e.g. 'mod'
7495 * @param string $name Plugin name e.g. 'forum'
7496 * @param string $feature Feature code (FEATURE_xx constant)
7497 * @param mixed $default default value if feature support unknown
7498 * @return mixed Feature result (false if not supported, null if feature is unknown,
7499 * otherwise usually true but may have other feature-specific value such as array)
7500 * @throws coding_exception
7502 function plugin_supports($type, $name, $feature, $default = null) {
7503 global $CFG;
7505 if ($type === 'mod' and $name === 'NEWMODULE') {
7506 // Somebody forgot to rename the module template.
7507 return false;
7510 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7511 if (empty($component)) {
7512 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7515 $function = null;
7517 if ($type === 'mod') {
7518 // We need this special case because we support subplugins in modules,
7519 // otherwise it would end up in infinite loop.
7520 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7521 include_once("$CFG->dirroot/mod/$name/lib.php");
7522 $function = $component.'_supports';
7523 if (!function_exists($function)) {
7524 // Legacy non-frankenstyle function name.
7525 $function = $name.'_supports';
7529 } else {
7530 if (!$path = core_component::get_plugin_directory($type, $name)) {
7531 // Non existent plugin type.
7532 return false;
7534 if (file_exists("$path/lib.php")) {
7535 include_once("$path/lib.php");
7536 $function = $component.'_supports';
7540 if ($function and function_exists($function)) {
7541 $supports = $function($feature);
7542 if (is_null($supports)) {
7543 // Plugin does not know - use default.
7544 return $default;
7545 } else {
7546 return $supports;
7550 // Plugin does not care, so use default.
7551 return $default;
7555 * Returns true if the current version of PHP is greater that the specified one.
7557 * @todo Check PHP version being required here is it too low?
7559 * @param string $version The version of php being tested.
7560 * @return bool
7562 function check_php_version($version='5.2.4') {
7563 return (version_compare(phpversion(), $version) >= 0);
7567 * Determine if moodle installation requires update.
7569 * Checks version numbers of main code and all plugins to see
7570 * if there are any mismatches.
7572 * @return bool
7574 function moodle_needs_upgrading() {
7575 global $CFG;
7577 if (empty($CFG->version)) {
7578 return true;
7581 // There is no need to purge plugininfo caches here because
7582 // these caches are not used during upgrade and they are purged after
7583 // every upgrade.
7585 if (empty($CFG->allversionshash)) {
7586 return true;
7589 $hash = core_component::get_all_versions_hash();
7591 return ($hash !== $CFG->allversionshash);
7595 * Returns the major version of this site
7597 * Moodle version numbers consist of three numbers separated by a dot, for
7598 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7599 * called major version. This function extracts the major version from either
7600 * $CFG->release (default) or eventually from the $release variable defined in
7601 * the main version.php.
7603 * @param bool $fromdisk should the version if source code files be used
7604 * @return string|false the major version like '2.3', false if could not be determined
7606 function moodle_major_version($fromdisk = false) {
7607 global $CFG;
7609 if ($fromdisk) {
7610 $release = null;
7611 require($CFG->dirroot.'/version.php');
7612 if (empty($release)) {
7613 return false;
7616 } else {
7617 if (empty($CFG->release)) {
7618 return false;
7620 $release = $CFG->release;
7623 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7624 return $matches[0];
7625 } else {
7626 return false;
7630 // MISCELLANEOUS.
7633 * Sets the system locale
7635 * @category string
7636 * @param string $locale Can be used to force a locale
7638 function moodle_setlocale($locale='') {
7639 global $CFG;
7641 static $currentlocale = ''; // Last locale caching.
7643 $oldlocale = $currentlocale;
7645 // Fetch the correct locale based on ostype.
7646 if ($CFG->ostype == 'WINDOWS') {
7647 $stringtofetch = 'localewin';
7648 } else {
7649 $stringtofetch = 'locale';
7652 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7653 if (!empty($locale)) {
7654 $currentlocale = $locale;
7655 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7656 $currentlocale = $CFG->locale;
7657 } else {
7658 $currentlocale = get_string($stringtofetch, 'langconfig');
7661 // Do nothing if locale already set up.
7662 if ($oldlocale == $currentlocale) {
7663 return;
7666 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7667 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7668 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7670 // Get current values.
7671 $monetary= setlocale (LC_MONETARY, 0);
7672 $numeric = setlocale (LC_NUMERIC, 0);
7673 $ctype = setlocale (LC_CTYPE, 0);
7674 if ($CFG->ostype != 'WINDOWS') {
7675 $messages= setlocale (LC_MESSAGES, 0);
7677 // Set locale to all.
7678 $result = setlocale (LC_ALL, $currentlocale);
7679 // If setting of locale fails try the other utf8 or utf-8 variant,
7680 // some operating systems support both (Debian), others just one (OSX).
7681 if ($result === false) {
7682 if (stripos($currentlocale, '.UTF-8') !== false) {
7683 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7684 setlocale (LC_ALL, $newlocale);
7685 } else if (stripos($currentlocale, '.UTF8') !== false) {
7686 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7687 setlocale (LC_ALL, $newlocale);
7690 // Set old values.
7691 setlocale (LC_MONETARY, $monetary);
7692 setlocale (LC_NUMERIC, $numeric);
7693 if ($CFG->ostype != 'WINDOWS') {
7694 setlocale (LC_MESSAGES, $messages);
7696 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7697 // To workaround a well-known PHP problem with Turkish letter Ii.
7698 setlocale (LC_CTYPE, $ctype);
7703 * Count words in a string.
7705 * Words are defined as things between whitespace.
7707 * @category string
7708 * @param string $string The text to be searched for words.
7709 * @return int The count of words in the specified string
7711 function count_words($string) {
7712 $string = strip_tags($string);
7713 // Decode HTML entities.
7714 $string = html_entity_decode($string);
7715 // Replace underscores (which are classed as word characters) with spaces.
7716 $string = preg_replace('/_/u', ' ', $string);
7717 // Remove any characters that shouldn't be treated as word boundaries.
7718 $string = preg_replace('/[\'"’-]/u', '', $string);
7719 // Remove dots and commas from within numbers only.
7720 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7722 return count(preg_split('/\w\b/u', $string)) - 1;
7726 * Count letters in a string.
7728 * Letters are defined as chars not in tags and different from whitespace.
7730 * @category string
7731 * @param string $string The text to be searched for letters.
7732 * @return int The count of letters in the specified text.
7734 function count_letters($string) {
7735 $string = strip_tags($string); // Tags are out now.
7736 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7738 return core_text::strlen($string);
7742 * Generate and return a random string of the specified length.
7744 * @param int $length The length of the string to be created.
7745 * @return string
7747 function random_string($length=15) {
7748 $randombytes = random_bytes_emulate($length);
7749 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7750 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7751 $pool .= '0123456789';
7752 $poollen = strlen($pool);
7753 $string = '';
7754 for ($i = 0; $i < $length; $i++) {
7755 $rand = ord($randombytes[$i]);
7756 $string .= substr($pool, ($rand%($poollen)), 1);
7758 return $string;
7762 * Generate a complex random string (useful for md5 salts)
7764 * This function is based on the above {@link random_string()} however it uses a
7765 * larger pool of characters and generates a string between 24 and 32 characters
7767 * @param int $length Optional if set generates a string to exactly this length
7768 * @return string
7770 function complex_random_string($length=null) {
7771 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7772 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7773 $poollen = strlen($pool);
7774 if ($length===null) {
7775 $length = floor(rand(24, 32));
7777 $randombytes = random_bytes_emulate($length);
7778 $string = '';
7779 for ($i = 0; $i < $length; $i++) {
7780 $rand = ord($randombytes[$i]);
7781 $string .= $pool[($rand%$poollen)];
7783 return $string;
7787 * Try to generates cryptographically secure pseudo-random bytes.
7789 * Note this is achieved by fallbacking between:
7790 * - PHP 7 random_bytes().
7791 * - OpenSSL openssl_random_pseudo_bytes().
7792 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
7794 * @param int $length requested length in bytes
7795 * @return string binary data
7797 function random_bytes_emulate($length) {
7798 global $CFG;
7799 if ($length <= 0) {
7800 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
7801 return '';
7803 if (function_exists('random_bytes')) {
7804 // Use PHP 7 goodness.
7805 $hash = @random_bytes($length);
7806 if ($hash !== false) {
7807 return $hash;
7810 if (function_exists('openssl_random_pseudo_bytes')) {
7811 // For PHP 5.3 and later with openssl extension.
7812 $hash = openssl_random_pseudo_bytes($length);
7813 if ($hash !== false) {
7814 return $hash;
7818 // Bad luck, there is no reliable random generator, let's just hash some unique stuff that is hard to guess.
7819 $hash = sha1(serialize($CFG) . serialize($_SERVER) . microtime(true) . uniqid('', true), true);
7820 // NOTE: the last param in sha1() is true, this means we are getting 20 bytes, not 40 chars as usual.
7821 if ($length <= 20) {
7822 return substr($hash, 0, $length);
7824 return $hash . random_bytes_emulate($length - 20);
7828 * Given some text (which may contain HTML) and an ideal length,
7829 * this function truncates the text neatly on a word boundary if possible
7831 * @category string
7832 * @param string $text text to be shortened
7833 * @param int $ideal ideal string length
7834 * @param boolean $exact if false, $text will not be cut mid-word
7835 * @param string $ending The string to append if the passed string is truncated
7836 * @return string $truncate shortened string
7838 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7839 // If the plain text is shorter than the maximum length, return the whole text.
7840 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7841 return $text;
7844 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7845 // and only tag in its 'line'.
7846 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
7848 $totallength = core_text::strlen($ending);
7849 $truncate = '';
7851 // This array stores information about open and close tags and their position
7852 // in the truncated string. Each item in the array is an object with fields
7853 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7854 // (byte position in truncated text).
7855 $tagdetails = array();
7857 foreach ($lines as $linematchings) {
7858 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7859 if (!empty($linematchings[1])) {
7860 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7861 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7862 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7863 // Record closing tag.
7864 $tagdetails[] = (object) array(
7865 'open' => false,
7866 'tag' => core_text::strtolower($tagmatchings[1]),
7867 'pos' => core_text::strlen($truncate),
7870 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7871 // Record opening tag.
7872 $tagdetails[] = (object) array(
7873 'open' => true,
7874 'tag' => core_text::strtolower($tagmatchings[1]),
7875 'pos' => core_text::strlen($truncate),
7877 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
7878 $tagdetails[] = (object) array(
7879 'open' => true,
7880 'tag' => core_text::strtolower('if'),
7881 'pos' => core_text::strlen($truncate),
7883 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
7884 $tagdetails[] = (object) array(
7885 'open' => false,
7886 'tag' => core_text::strtolower('if'),
7887 'pos' => core_text::strlen($truncate),
7891 // Add html-tag to $truncate'd text.
7892 $truncate .= $linematchings[1];
7895 // Calculate the length of the plain text part of the line; handle entities as one character.
7896 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7897 if ($totallength + $contentlength > $ideal) {
7898 // The number of characters which are left.
7899 $left = $ideal - $totallength;
7900 $entitieslength = 0;
7901 // Search for html entities.
7902 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)) {
7903 // Calculate the real length of all entities in the legal range.
7904 foreach ($entities[0] as $entity) {
7905 if ($entity[1]+1-$entitieslength <= $left) {
7906 $left--;
7907 $entitieslength += core_text::strlen($entity[0]);
7908 } else {
7909 // No more characters left.
7910 break;
7914 $breakpos = $left + $entitieslength;
7916 // If the words shouldn't be cut in the middle...
7917 if (!$exact) {
7918 // Search the last occurence of a space.
7919 for (; $breakpos > 0; $breakpos--) {
7920 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
7921 if ($char === '.' or $char === ' ') {
7922 $breakpos += 1;
7923 break;
7924 } else if (strlen($char) > 2) {
7925 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7926 $breakpos += 1;
7927 break;
7932 if ($breakpos == 0) {
7933 // This deals with the test_shorten_text_no_spaces case.
7934 $breakpos = $left + $entitieslength;
7935 } else if ($breakpos > $left + $entitieslength) {
7936 // This deals with the previous for loop breaking on the first char.
7937 $breakpos = $left + $entitieslength;
7940 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
7941 // Maximum length is reached, so get off the loop.
7942 break;
7943 } else {
7944 $truncate .= $linematchings[2];
7945 $totallength += $contentlength;
7948 // If the maximum length is reached, get off the loop.
7949 if ($totallength >= $ideal) {
7950 break;
7954 // Add the defined ending to the text.
7955 $truncate .= $ending;
7957 // Now calculate the list of open html tags based on the truncate position.
7958 $opentags = array();
7959 foreach ($tagdetails as $taginfo) {
7960 if ($taginfo->open) {
7961 // Add tag to the beginning of $opentags list.
7962 array_unshift($opentags, $taginfo->tag);
7963 } else {
7964 // Can have multiple exact same open tags, close the last one.
7965 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
7966 if ($pos !== false) {
7967 unset($opentags[$pos]);
7972 // Close all unclosed html-tags.
7973 foreach ($opentags as $tag) {
7974 if ($tag === 'if') {
7975 $truncate .= '<!--<![endif]-->';
7976 } else {
7977 $truncate .= '</' . $tag . '>';
7981 return $truncate;
7986 * Given dates in seconds, how many weeks is the date from startdate
7987 * The first week is 1, the second 2 etc ...
7989 * @param int $startdate Timestamp for the start date
7990 * @param int $thedate Timestamp for the end date
7991 * @return string
7993 function getweek ($startdate, $thedate) {
7994 if ($thedate < $startdate) {
7995 return 0;
7998 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8002 * Returns a randomly generated password of length $maxlen. inspired by
8004 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8005 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8007 * @param int $maxlen The maximum size of the password being generated.
8008 * @return string
8010 function generate_password($maxlen=10) {
8011 global $CFG;
8013 if (empty($CFG->passwordpolicy)) {
8014 $fillers = PASSWORD_DIGITS;
8015 $wordlist = file($CFG->wordlist);
8016 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8017 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8018 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8019 $password = $word1 . $filler1 . $word2;
8020 } else {
8021 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8022 $digits = $CFG->minpassworddigits;
8023 $lower = $CFG->minpasswordlower;
8024 $upper = $CFG->minpasswordupper;
8025 $nonalphanum = $CFG->minpasswordnonalphanum;
8026 $total = $lower + $upper + $digits + $nonalphanum;
8027 // Var minlength should be the greater one of the two ( $minlen and $total ).
8028 $minlen = $minlen < $total ? $total : $minlen;
8029 // Var maxlen can never be smaller than minlen.
8030 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8031 $additional = $maxlen - $total;
8033 // Make sure we have enough characters to fulfill
8034 // complexity requirements.
8035 $passworddigits = PASSWORD_DIGITS;
8036 while ($digits > strlen($passworddigits)) {
8037 $passworddigits .= PASSWORD_DIGITS;
8039 $passwordlower = PASSWORD_LOWER;
8040 while ($lower > strlen($passwordlower)) {
8041 $passwordlower .= PASSWORD_LOWER;
8043 $passwordupper = PASSWORD_UPPER;
8044 while ($upper > strlen($passwordupper)) {
8045 $passwordupper .= PASSWORD_UPPER;
8047 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8048 while ($nonalphanum > strlen($passwordnonalphanum)) {
8049 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8052 // Now mix and shuffle it all.
8053 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8054 substr(str_shuffle ($passwordupper), 0, $upper) .
8055 substr(str_shuffle ($passworddigits), 0, $digits) .
8056 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8057 substr(str_shuffle ($passwordlower .
8058 $passwordupper .
8059 $passworddigits .
8060 $passwordnonalphanum), 0 , $additional));
8063 return substr ($password, 0, $maxlen);
8067 * Given a float, prints it nicely.
8068 * Localized floats must not be used in calculations!
8070 * The stripzeros feature is intended for making numbers look nicer in small
8071 * areas where it is not necessary to indicate the degree of accuracy by showing
8072 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8073 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8075 * @param float $float The float to print
8076 * @param int $decimalpoints The number of decimal places to print.
8077 * @param bool $localized use localized decimal separator
8078 * @param bool $stripzeros If true, removes final zeros after decimal point
8079 * @return string locale float
8081 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8082 if (is_null($float)) {
8083 return '';
8085 if ($localized) {
8086 $separator = get_string('decsep', 'langconfig');
8087 } else {
8088 $separator = '.';
8090 $result = number_format($float, $decimalpoints, $separator, '');
8091 if ($stripzeros) {
8092 // Remove zeros and final dot if not needed.
8093 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8095 return $result;
8099 * Converts locale specific floating point/comma number back to standard PHP float value
8100 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8102 * @param string $localefloat locale aware float representation
8103 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8104 * @return mixed float|bool - false or the parsed float.
8106 function unformat_float($localefloat, $strict = false) {
8107 $localefloat = trim($localefloat);
8109 if ($localefloat == '') {
8110 return null;
8113 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8114 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8116 if ($strict && !is_numeric($localefloat)) {
8117 return false;
8120 return (float)$localefloat;
8124 * Given a simple array, this shuffles it up just like shuffle()
8125 * Unlike PHP's shuffle() this function works on any machine.
8127 * @param array $array The array to be rearranged
8128 * @return array
8130 function swapshuffle($array) {
8132 $last = count($array) - 1;
8133 for ($i = 0; $i <= $last; $i++) {
8134 $from = rand(0, $last);
8135 $curr = $array[$i];
8136 $array[$i] = $array[$from];
8137 $array[$from] = $curr;
8139 return $array;
8143 * Like {@link swapshuffle()}, but works on associative arrays
8145 * @param array $array The associative array to be rearranged
8146 * @return array
8148 function swapshuffle_assoc($array) {
8150 $newarray = array();
8151 $newkeys = swapshuffle(array_keys($array));
8153 foreach ($newkeys as $newkey) {
8154 $newarray[$newkey] = $array[$newkey];
8156 return $newarray;
8160 * Given an arbitrary array, and a number of draws,
8161 * this function returns an array with that amount
8162 * of items. The indexes are retained.
8164 * @todo Finish documenting this function
8166 * @param array $array
8167 * @param int $draws
8168 * @return array
8170 function draw_rand_array($array, $draws) {
8172 $return = array();
8174 $last = count($array);
8176 if ($draws > $last) {
8177 $draws = $last;
8180 while ($draws > 0) {
8181 $last--;
8183 $keys = array_keys($array);
8184 $rand = rand(0, $last);
8186 $return[$keys[$rand]] = $array[$keys[$rand]];
8187 unset($array[$keys[$rand]]);
8189 $draws--;
8192 return $return;
8196 * Calculate the difference between two microtimes
8198 * @param string $a The first Microtime
8199 * @param string $b The second Microtime
8200 * @return string
8202 function microtime_diff($a, $b) {
8203 list($adec, $asec) = explode(' ', $a);
8204 list($bdec, $bsec) = explode(' ', $b);
8205 return $bsec - $asec + $bdec - $adec;
8209 * Given a list (eg a,b,c,d,e) this function returns
8210 * an array of 1->a, 2->b, 3->c etc
8212 * @param string $list The string to explode into array bits
8213 * @param string $separator The separator used within the list string
8214 * @return array The now assembled array
8216 function make_menu_from_list($list, $separator=',') {
8218 $array = array_reverse(explode($separator, $list), true);
8219 foreach ($array as $key => $item) {
8220 $outarray[$key+1] = trim($item);
8222 return $outarray;
8226 * Creates an array that represents all the current grades that
8227 * can be chosen using the given grading type.
8229 * Negative numbers
8230 * are scales, zero is no grade, and positive numbers are maximum
8231 * grades.
8233 * @todo Finish documenting this function or better deprecated this completely!
8235 * @param int $gradingtype
8236 * @return array
8238 function make_grades_menu($gradingtype) {
8239 global $DB;
8241 $grades = array();
8242 if ($gradingtype < 0) {
8243 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8244 return make_menu_from_list($scale->scale);
8246 } else if ($gradingtype > 0) {
8247 for ($i=$gradingtype; $i>=0; $i--) {
8248 $grades[$i] = $i .' / '. $gradingtype;
8250 return $grades;
8252 return $grades;
8256 * make_unique_id_code
8258 * @todo Finish documenting this function
8260 * @uses $_SERVER
8261 * @param string $extra Extra string to append to the end of the code
8262 * @return string
8264 function make_unique_id_code($extra = '') {
8266 $hostname = 'unknownhost';
8267 if (!empty($_SERVER['HTTP_HOST'])) {
8268 $hostname = $_SERVER['HTTP_HOST'];
8269 } else if (!empty($_ENV['HTTP_HOST'])) {
8270 $hostname = $_ENV['HTTP_HOST'];
8271 } else if (!empty($_SERVER['SERVER_NAME'])) {
8272 $hostname = $_SERVER['SERVER_NAME'];
8273 } else if (!empty($_ENV['SERVER_NAME'])) {
8274 $hostname = $_ENV['SERVER_NAME'];
8277 $date = gmdate("ymdHis");
8279 $random = random_string(6);
8281 if ($extra) {
8282 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8283 } else {
8284 return $hostname .'+'. $date .'+'. $random;
8290 * Function to check the passed address is within the passed subnet
8292 * The parameter is a comma separated string of subnet definitions.
8293 * Subnet strings can be in one of three formats:
8294 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8295 * 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)
8296 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8297 * Code for type 1 modified from user posted comments by mediator at
8298 * {@link http://au.php.net/manual/en/function.ip2long.php}
8300 * @param string $addr The address you are checking
8301 * @param string $subnetstr The string of subnet addresses
8302 * @return bool
8304 function address_in_subnet($addr, $subnetstr) {
8306 if ($addr == '0.0.0.0') {
8307 return false;
8309 $subnets = explode(',', $subnetstr);
8310 $found = false;
8311 $addr = trim($addr);
8312 $addr = cleanremoteaddr($addr, false); // Normalise.
8313 if ($addr === null) {
8314 return false;
8316 $addrparts = explode(':', $addr);
8318 $ipv6 = strpos($addr, ':');
8320 foreach ($subnets as $subnet) {
8321 $subnet = trim($subnet);
8322 if ($subnet === '') {
8323 continue;
8326 if (strpos($subnet, '/') !== false) {
8327 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8328 list($ip, $mask) = explode('/', $subnet);
8329 $mask = trim($mask);
8330 if (!is_number($mask)) {
8331 continue; // Incorect mask number, eh?
8333 $ip = cleanremoteaddr($ip, false); // Normalise.
8334 if ($ip === null) {
8335 continue;
8337 if (strpos($ip, ':') !== false) {
8338 // IPv6.
8339 if (!$ipv6) {
8340 continue;
8342 if ($mask > 128 or $mask < 0) {
8343 continue; // Nonsense.
8345 if ($mask == 0) {
8346 return true; // Any address.
8348 if ($mask == 128) {
8349 if ($ip === $addr) {
8350 return true;
8352 continue;
8354 $ipparts = explode(':', $ip);
8355 $modulo = $mask % 16;
8356 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8357 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8358 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8359 if ($modulo == 0) {
8360 return true;
8362 $pos = ($mask-$modulo)/16;
8363 $ipnet = hexdec($ipparts[$pos]);
8364 $addrnet = hexdec($addrparts[$pos]);
8365 $mask = 0xffff << (16 - $modulo);
8366 if (($addrnet & $mask) == ($ipnet & $mask)) {
8367 return true;
8371 } else {
8372 // IPv4.
8373 if ($ipv6) {
8374 continue;
8376 if ($mask > 32 or $mask < 0) {
8377 continue; // Nonsense.
8379 if ($mask == 0) {
8380 return true;
8382 if ($mask == 32) {
8383 if ($ip === $addr) {
8384 return true;
8386 continue;
8388 $mask = 0xffffffff << (32 - $mask);
8389 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8390 return true;
8394 } else if (strpos($subnet, '-') !== false) {
8395 // 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.
8396 $parts = explode('-', $subnet);
8397 if (count($parts) != 2) {
8398 continue;
8401 if (strpos($subnet, ':') !== false) {
8402 // IPv6.
8403 if (!$ipv6) {
8404 continue;
8406 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8407 if ($ipstart === null) {
8408 continue;
8410 $ipparts = explode(':', $ipstart);
8411 $start = hexdec(array_pop($ipparts));
8412 $ipparts[] = trim($parts[1]);
8413 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8414 if ($ipend === null) {
8415 continue;
8417 $ipparts[7] = '';
8418 $ipnet = implode(':', $ipparts);
8419 if (strpos($addr, $ipnet) !== 0) {
8420 continue;
8422 $ipparts = explode(':', $ipend);
8423 $end = hexdec($ipparts[7]);
8425 $addrend = hexdec($addrparts[7]);
8427 if (($addrend >= $start) and ($addrend <= $end)) {
8428 return true;
8431 } else {
8432 // IPv4.
8433 if ($ipv6) {
8434 continue;
8436 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8437 if ($ipstart === null) {
8438 continue;
8440 $ipparts = explode('.', $ipstart);
8441 $ipparts[3] = trim($parts[1]);
8442 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8443 if ($ipend === null) {
8444 continue;
8447 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8448 return true;
8452 } else {
8453 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8454 if (strpos($subnet, ':') !== false) {
8455 // IPv6.
8456 if (!$ipv6) {
8457 continue;
8459 $parts = explode(':', $subnet);
8460 $count = count($parts);
8461 if ($parts[$count-1] === '') {
8462 unset($parts[$count-1]); // Trim trailing :'s.
8463 $count--;
8464 $subnet = implode('.', $parts);
8466 $isip = cleanremoteaddr($subnet, false); // Normalise.
8467 if ($isip !== null) {
8468 if ($isip === $addr) {
8469 return true;
8471 continue;
8472 } else if ($count > 8) {
8473 continue;
8475 $zeros = array_fill(0, 8-$count, '0');
8476 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8477 if (address_in_subnet($addr, $subnet)) {
8478 return true;
8481 } else {
8482 // IPv4.
8483 if ($ipv6) {
8484 continue;
8486 $parts = explode('.', $subnet);
8487 $count = count($parts);
8488 if ($parts[$count-1] === '') {
8489 unset($parts[$count-1]); // Trim trailing .
8490 $count--;
8491 $subnet = implode('.', $parts);
8493 if ($count == 4) {
8494 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8495 if ($subnet === $addr) {
8496 return true;
8498 continue;
8499 } else if ($count > 4) {
8500 continue;
8502 $zeros = array_fill(0, 4-$count, '0');
8503 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8504 if (address_in_subnet($addr, $subnet)) {
8505 return true;
8511 return false;
8515 * For outputting debugging info
8517 * @param string $string The string to write
8518 * @param string $eol The end of line char(s) to use
8519 * @param string $sleep Period to make the application sleep
8520 * This ensures any messages have time to display before redirect
8522 function mtrace($string, $eol="\n", $sleep=0) {
8524 if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
8525 fwrite(STDOUT, $string.$eol);
8526 } else {
8527 echo $string . $eol;
8530 flush();
8532 // Delay to keep message on user's screen in case of subsequent redirect.
8533 if ($sleep) {
8534 sleep($sleep);
8539 * Replace 1 or more slashes or backslashes to 1 slash
8541 * @param string $path The path to strip
8542 * @return string the path with double slashes removed
8544 function cleardoubleslashes ($path) {
8545 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8549 * Is current ip in give list?
8551 * @param string $list
8552 * @return bool
8554 function remoteip_in_list($list) {
8555 $inlist = false;
8556 $clientip = getremoteaddr(null);
8558 if (!$clientip) {
8559 // Ensure access on cli.
8560 return true;
8563 $list = explode("\n", $list);
8564 foreach ($list as $subnet) {
8565 $subnet = trim($subnet);
8566 if (address_in_subnet($clientip, $subnet)) {
8567 $inlist = true;
8568 break;
8571 return $inlist;
8575 * Returns most reliable client address
8577 * @param string $default If an address can't be determined, then return this
8578 * @return string The remote IP address
8580 function getremoteaddr($default='0.0.0.0') {
8581 global $CFG;
8583 if (empty($CFG->getremoteaddrconf)) {
8584 // This will happen, for example, before just after the upgrade, as the
8585 // user is redirected to the admin screen.
8586 $variablestoskip = 0;
8587 } else {
8588 $variablestoskip = $CFG->getremoteaddrconf;
8590 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8591 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8592 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8593 return $address ? $address : $default;
8596 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8597 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8598 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8599 $address = $forwardedaddresses[0];
8601 if (substr_count($address, ":") > 1) {
8602 // Remove port and brackets from IPv6.
8603 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8604 $address = $matches[1];
8606 } else {
8607 // Remove port from IPv4.
8608 if (substr_count($address, ":") == 1) {
8609 $parts = explode(":", $address);
8610 $address = $parts[0];
8614 $address = cleanremoteaddr($address);
8615 return $address ? $address : $default;
8618 if (!empty($_SERVER['REMOTE_ADDR'])) {
8619 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8620 return $address ? $address : $default;
8621 } else {
8622 return $default;
8627 * Cleans an ip address. Internal addresses are now allowed.
8628 * (Originally local addresses were not allowed.)
8630 * @param string $addr IPv4 or IPv6 address
8631 * @param bool $compress use IPv6 address compression
8632 * @return string normalised ip address string, null if error
8634 function cleanremoteaddr($addr, $compress=false) {
8635 $addr = trim($addr);
8637 // TODO: maybe add a separate function is_addr_public() or something like this.
8639 if (strpos($addr, ':') !== false) {
8640 // Can be only IPv6.
8641 $parts = explode(':', $addr);
8642 $count = count($parts);
8644 if (strpos($parts[$count-1], '.') !== false) {
8645 // Legacy ipv4 notation.
8646 $last = array_pop($parts);
8647 $ipv4 = cleanremoteaddr($last, true);
8648 if ($ipv4 === null) {
8649 return null;
8651 $bits = explode('.', $ipv4);
8652 $parts[] = dechex($bits[0]).dechex($bits[1]);
8653 $parts[] = dechex($bits[2]).dechex($bits[3]);
8654 $count = count($parts);
8655 $addr = implode(':', $parts);
8658 if ($count < 3 or $count > 8) {
8659 return null; // Severly malformed.
8662 if ($count != 8) {
8663 if (strpos($addr, '::') === false) {
8664 return null; // Malformed.
8666 // Uncompress.
8667 $insertat = array_search('', $parts, true);
8668 $missing = array_fill(0, 1 + 8 - $count, '0');
8669 array_splice($parts, $insertat, 1, $missing);
8670 foreach ($parts as $key => $part) {
8671 if ($part === '') {
8672 $parts[$key] = '0';
8677 $adr = implode(':', $parts);
8678 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8679 return null; // Incorrect format - sorry.
8682 // Normalise 0s and case.
8683 $parts = array_map('hexdec', $parts);
8684 $parts = array_map('dechex', $parts);
8686 $result = implode(':', $parts);
8688 if (!$compress) {
8689 return $result;
8692 if ($result === '0:0:0:0:0:0:0:0') {
8693 return '::'; // All addresses.
8696 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8697 if ($compressed !== $result) {
8698 return $compressed;
8701 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8702 if ($compressed !== $result) {
8703 return $compressed;
8706 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8707 if ($compressed !== $result) {
8708 return $compressed;
8711 return $result;
8714 // First get all things that look like IPv4 addresses.
8715 $parts = array();
8716 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8717 return null;
8719 unset($parts[0]);
8721 foreach ($parts as $key => $match) {
8722 if ($match > 255) {
8723 return null;
8725 $parts[$key] = (int)$match; // Normalise 0s.
8728 return implode('.', $parts);
8732 * This function will make a complete copy of anything it's given,
8733 * regardless of whether it's an object or not.
8735 * @param mixed $thing Something you want cloned
8736 * @return mixed What ever it is you passed it
8738 function fullclone($thing) {
8739 return unserialize(serialize($thing));
8743 * If new messages are waiting for the current user, then insert
8744 * JavaScript to pop up the messaging window into the page
8746 * @return void
8748 function message_popup_window() {
8749 global $USER, $DB, $PAGE, $CFG;
8751 if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
8752 return;
8755 if (!isloggedin() || isguestuser()) {
8756 return;
8759 if (!isset($USER->message_lastpopup)) {
8760 $USER->message_lastpopup = 0;
8761 } else if ($USER->message_lastpopup > (time()-120)) {
8762 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8763 return;
8766 // A quick query to check whether the user has new messages.
8767 $messagecount = $DB->count_records('message', array('useridto' => $USER->id));
8768 if ($messagecount < 1) {
8769 return;
8772 // There are unread messages so now do a more complex but slower query.
8773 $messagesql = "SELECT m.id, c.blocked
8774 FROM {message} m
8775 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8776 JOIN {message_processors} p ON mw.processorid=p.id
8777 LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
8778 AND c.userid = m.useridto
8779 WHERE m.useridto = :userid
8780 AND p.name='popup'";
8782 // If the user was last notified over an hour ago we can re-notify them of old messages
8783 // so don't worry about when the new message was sent.
8784 $lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
8785 if (!$lastnotifiedlongago) {
8786 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8789 $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id, 'lastpopuptime' => $USER->message_lastpopup));
8791 $validmessages = 0;
8792 foreach ($waitingmessages as $messageinfo) {
8793 if ($messageinfo->blocked) {
8794 // Message is from a user who has since been blocked so just mark it read.
8795 // Get the full message to mark as read.
8796 $messageobject = $DB->get_record('message', array('id' => $messageinfo->id));
8797 message_mark_message_read($messageobject, time());
8798 } else {
8799 $validmessages++;
8803 if ($validmessages > 0) {
8804 $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
8805 $strgomessage = get_string('gotomessages', 'message');
8806 $strstaymessage = get_string('ignore', 'admin');
8808 $notificationsound = null;
8809 $beep = get_user_preferences('message_beepnewmessage', '');
8810 if (!empty($beep)) {
8811 // Browsers will work down this list until they find something they support.
8812 $sourcetags = html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.wav', 'type' => 'audio/wav'));
8813 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.ogg', 'type' => 'audio/ogg'));
8814 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8815 $sourcetags .= html_writer::empty_tag('embed', array('src' => $CFG->wwwroot.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8817 $notificationsound = html_writer::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8820 $url = $CFG->wwwroot.'/message/index.php';
8821 $content = html_writer::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8822 html_writer::start_tag('div', array('id' => 'newmessagetext')).
8823 $strmessages.
8824 html_writer::end_tag('div').
8826 $notificationsound.
8827 html_writer::start_tag('div', array('id' => 'newmessagelinks')).
8828 html_writer::link($url, $strgomessage, array('id' => 'notificationyes')).'&nbsp;&nbsp;&nbsp;'.
8829 html_writer::link('', $strstaymessage, array('id' => 'notificationno')).
8830 html_writer::end_tag('div');
8831 html_writer::end_tag('div');
8833 $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
8835 $USER->message_lastpopup = time();
8840 * Used to make sure that $min <= $value <= $max
8842 * Make sure that value is between min, and max
8844 * @param int $min The minimum value
8845 * @param int $value The value to check
8846 * @param int $max The maximum value
8847 * @return int
8849 function bounded_number($min, $value, $max) {
8850 if ($value < $min) {
8851 return $min;
8853 if ($value > $max) {
8854 return $max;
8856 return $value;
8860 * Check if there is a nested array within the passed array
8862 * @param array $array
8863 * @return bool true if there is a nested array false otherwise
8865 function array_is_nested($array) {
8866 foreach ($array as $value) {
8867 if (is_array($value)) {
8868 return true;
8871 return false;
8875 * get_performance_info() pairs up with init_performance_info()
8876 * loaded in setup.php. Returns an array with 'html' and 'txt'
8877 * values ready for use, and each of the individual stats provided
8878 * separately as well.
8880 * @return array
8882 function get_performance_info() {
8883 global $CFG, $PERF, $DB, $PAGE;
8885 $info = array();
8886 $info['html'] = ''; // Holds userfriendly HTML representation.
8887 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8889 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
8891 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8892 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8894 if (function_exists('memory_get_usage')) {
8895 $info['memory_total'] = memory_get_usage();
8896 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
8897 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8898 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8899 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8902 if (function_exists('memory_get_peak_usage')) {
8903 $info['memory_peak'] = memory_get_peak_usage();
8904 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8905 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8908 $inc = get_included_files();
8909 $info['includecount'] = count($inc);
8910 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8911 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8913 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
8914 // We can not track more performance before installation or before PAGE init, sorry.
8915 return $info;
8918 $filtermanager = filter_manager::instance();
8919 if (method_exists($filtermanager, 'get_performance_summary')) {
8920 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8921 $info = array_merge($filterinfo, $info);
8922 foreach ($filterinfo as $key => $value) {
8923 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8924 $info['txt'] .= "$key: $value ";
8928 $stringmanager = get_string_manager();
8929 if (method_exists($stringmanager, 'get_performance_summary')) {
8930 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
8931 $info = array_merge($filterinfo, $info);
8932 foreach ($filterinfo as $key => $value) {
8933 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8934 $info['txt'] .= "$key: $value ";
8938 if (!empty($PERF->logwrites)) {
8939 $info['logwrites'] = $PERF->logwrites;
8940 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
8941 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
8944 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
8945 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
8946 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
8948 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
8949 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
8950 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
8952 if (function_exists('posix_times')) {
8953 $ptimes = posix_times();
8954 if (is_array($ptimes)) {
8955 foreach ($ptimes as $key => $val) {
8956 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
8958 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
8959 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
8963 // Grab the load average for the last minute.
8964 // /proc will only work under some linux configurations
8965 // while uptime is there under MacOSX/Darwin and other unices.
8966 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
8967 list($serverload) = explode(' ', $loadavg[0]);
8968 unset($loadavg);
8969 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
8970 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
8971 $serverload = $matches[1];
8972 } else {
8973 trigger_error('Could not parse uptime output!');
8976 if (!empty($serverload)) {
8977 $info['serverload'] = $serverload;
8978 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
8979 $info['txt'] .= "serverload: {$info['serverload']} ";
8982 // Display size of session if session started.
8983 if ($si = \core\session\manager::get_performance_info()) {
8984 $info['sessionsize'] = $si['size'];
8985 $info['html'] .= $si['html'];
8986 $info['txt'] .= $si['txt'];
8989 if ($stats = cache_helper::get_stats()) {
8990 $html = '<span class="cachesused">';
8991 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
8992 $text = 'Caches used (hits/misses/sets): ';
8993 $hits = 0;
8994 $misses = 0;
8995 $sets = 0;
8996 foreach ($stats as $definition => $details) {
8997 switch ($details['mode']) {
8998 case cache_store::MODE_APPLICATION:
8999 $modeclass = 'application';
9000 $mode = ' <span title="application cache">[a]</span>';
9001 break;
9002 case cache_store::MODE_SESSION:
9003 $modeclass = 'session';
9004 $mode = ' <span title="session cache">[s]</span>';
9005 break;
9006 case cache_store::MODE_REQUEST:
9007 $modeclass = 'request';
9008 $mode = ' <span title="request cache">[r]</span>';
9009 break;
9011 $html .= '<span class="cache-definition-stats cache-mode-'.$modeclass.'">';
9012 $html .= '<span class="cache-definition-stats-heading">'.$definition.$mode.'</span>';
9013 $text .= "$definition {";
9014 foreach ($details['stores'] as $store => $data) {
9015 $hits += $data['hits'];
9016 $misses += $data['misses'];
9017 $sets += $data['sets'];
9018 if ($data['hits'] == 0 and $data['misses'] > 0) {
9019 $cachestoreclass = 'nohits';
9020 } else if ($data['hits'] < $data['misses']) {
9021 $cachestoreclass = 'lowhits';
9022 } else {
9023 $cachestoreclass = 'hihits';
9025 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9026 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
9028 $html .= '</span>';
9029 $text .= '} ';
9031 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
9032 $html .= '</span> ';
9033 $info['cachesused'] = "$hits / $misses / $sets";
9034 $info['html'] .= $html;
9035 $info['txt'] .= $text.'. ';
9036 } else {
9037 $info['cachesused'] = '0 / 0 / 0';
9038 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
9039 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9042 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
9043 return $info;
9047 * Delete directory or only its content
9049 * @param string $dir directory path
9050 * @param bool $contentonly
9051 * @return bool success, true also if dir does not exist
9053 function remove_dir($dir, $contentonly=false) {
9054 if (!file_exists($dir)) {
9055 // Nothing to do.
9056 return true;
9058 if (!$handle = opendir($dir)) {
9059 return false;
9061 $result = true;
9062 while (false!==($item = readdir($handle))) {
9063 if ($item != '.' && $item != '..') {
9064 if (is_dir($dir.'/'.$item)) {
9065 $result = remove_dir($dir.'/'.$item) && $result;
9066 } else {
9067 $result = unlink($dir.'/'.$item) && $result;
9071 closedir($handle);
9072 if ($contentonly) {
9073 clearstatcache(); // Make sure file stat cache is properly invalidated.
9074 return $result;
9076 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9077 clearstatcache(); // Make sure file stat cache is properly invalidated.
9078 return $result;
9082 * Detect if an object or a class contains a given property
9083 * will take an actual object or the name of a class
9085 * @param mix $obj Name of class or real object to test
9086 * @param string $property name of property to find
9087 * @return bool true if property exists
9089 function object_property_exists( $obj, $property ) {
9090 if (is_string( $obj )) {
9091 $properties = get_class_vars( $obj );
9092 } else {
9093 $properties = get_object_vars( $obj );
9095 return array_key_exists( $property, $properties );
9099 * Converts an object into an associative array
9101 * This function converts an object into an associative array by iterating
9102 * over its public properties. Because this function uses the foreach
9103 * construct, Iterators are respected. It works recursively on arrays of objects.
9104 * Arrays and simple values are returned as is.
9106 * If class has magic properties, it can implement IteratorAggregate
9107 * and return all available properties in getIterator()
9109 * @param mixed $var
9110 * @return array
9112 function convert_to_array($var) {
9113 $result = array();
9115 // Loop over elements/properties.
9116 foreach ($var as $key => $value) {
9117 // Recursively convert objects.
9118 if (is_object($value) || is_array($value)) {
9119 $result[$key] = convert_to_array($value);
9120 } else {
9121 // Simple values are untouched.
9122 $result[$key] = $value;
9125 return $result;
9129 * Detect a custom script replacement in the data directory that will
9130 * replace an existing moodle script
9132 * @return string|bool full path name if a custom script exists, false if no custom script exists
9134 function custom_script_path() {
9135 global $CFG, $SCRIPT;
9137 if ($SCRIPT === null) {
9138 // Probably some weird external script.
9139 return false;
9142 $scriptpath = $CFG->customscripts . $SCRIPT;
9144 // Check the custom script exists.
9145 if (file_exists($scriptpath) and is_file($scriptpath)) {
9146 return $scriptpath;
9147 } else {
9148 return false;
9153 * Returns whether or not the user object is a remote MNET user. This function
9154 * is in moodlelib because it does not rely on loading any of the MNET code.
9156 * @param object $user A valid user object
9157 * @return bool True if the user is from a remote Moodle.
9159 function is_mnet_remote_user($user) {
9160 global $CFG;
9162 if (!isset($CFG->mnet_localhost_id)) {
9163 include_once($CFG->dirroot . '/mnet/lib.php');
9164 $env = new mnet_environment();
9165 $env->init();
9166 unset($env);
9169 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9173 * This function will search for browser prefereed languages, setting Moodle
9174 * to use the best one available if $SESSION->lang is undefined
9176 function setup_lang_from_browser() {
9177 global $CFG, $SESSION, $USER;
9179 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9180 // Lang is defined in session or user profile, nothing to do.
9181 return;
9184 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9185 return;
9188 // Extract and clean langs from headers.
9189 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9190 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9191 $rawlangs = explode(',', $rawlangs); // Convert to array.
9192 $langs = array();
9194 $order = 1.0;
9195 foreach ($rawlangs as $lang) {
9196 if (strpos($lang, ';') === false) {
9197 $langs[(string)$order] = $lang;
9198 $order = $order-0.01;
9199 } else {
9200 $parts = explode(';', $lang);
9201 $pos = strpos($parts[1], '=');
9202 $langs[substr($parts[1], $pos+1)] = $parts[0];
9205 krsort($langs, SORT_NUMERIC);
9207 // Look for such langs under standard locations.
9208 foreach ($langs as $lang) {
9209 // Clean it properly for include.
9210 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9211 if (get_string_manager()->translation_exists($lang, false)) {
9212 // Lang exists, set it in session.
9213 $SESSION->lang = $lang;
9214 // We have finished. Go out.
9215 break;
9218 return;
9222 * Check if $url matches anything in proxybypass list
9224 * Any errors just result in the proxy being used (least bad)
9226 * @param string $url url to check
9227 * @return boolean true if we should bypass the proxy
9229 function is_proxybypass( $url ) {
9230 global $CFG;
9232 // Sanity check.
9233 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9234 return false;
9237 // Get the host part out of the url.
9238 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9239 return false;
9242 // Get the possible bypass hosts into an array.
9243 $matches = explode( ',', $CFG->proxybypass );
9245 // Check for a match.
9246 // (IPs need to match the left hand side and hosts the right of the url,
9247 // but we can recklessly check both as there can't be a false +ve).
9248 foreach ($matches as $match) {
9249 $match = trim($match);
9251 // Try for IP match (Left side).
9252 $lhs = substr($host, 0, strlen($match));
9253 if (strcasecmp($match, $lhs)==0) {
9254 return true;
9257 // Try for host match (Right side).
9258 $rhs = substr($host, -strlen($match));
9259 if (strcasecmp($match, $rhs)==0) {
9260 return true;
9264 // Nothing matched.
9265 return false;
9269 * Check if the passed navigation is of the new style
9271 * @param mixed $navigation
9272 * @return bool true for yes false for no
9274 function is_newnav($navigation) {
9275 if (is_array($navigation) && !empty($navigation['newnav'])) {
9276 return true;
9277 } else {
9278 return false;
9283 * Checks whether the given variable name is defined as a variable within the given object.
9285 * This will NOT work with stdClass objects, which have no class variables.
9287 * @param string $var The variable name
9288 * @param object $object The object to check
9289 * @return boolean
9291 function in_object_vars($var, $object) {
9292 $classvars = get_class_vars(get_class($object));
9293 $classvars = array_keys($classvars);
9294 return in_array($var, $classvars);
9298 * Returns an array without repeated objects.
9299 * This function is similar to array_unique, but for arrays that have objects as values
9301 * @param array $array
9302 * @param bool $keepkeyassoc
9303 * @return array
9305 function object_array_unique($array, $keepkeyassoc = true) {
9306 $duplicatekeys = array();
9307 $tmp = array();
9309 foreach ($array as $key => $val) {
9310 // Convert objects to arrays, in_array() does not support objects.
9311 if (is_object($val)) {
9312 $val = (array)$val;
9315 if (!in_array($val, $tmp)) {
9316 $tmp[] = $val;
9317 } else {
9318 $duplicatekeys[] = $key;
9322 foreach ($duplicatekeys as $key) {
9323 unset($array[$key]);
9326 return $keepkeyassoc ? $array : array_values($array);
9330 * Is a userid the primary administrator?
9332 * @param int $userid int id of user to check
9333 * @return boolean
9335 function is_primary_admin($userid) {
9336 $primaryadmin = get_admin();
9338 if ($userid == $primaryadmin->id) {
9339 return true;
9340 } else {
9341 return false;
9346 * Returns the site identifier
9348 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9350 function get_site_identifier() {
9351 global $CFG;
9352 // Check to see if it is missing. If so, initialise it.
9353 if (empty($CFG->siteidentifier)) {
9354 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9356 // Return it.
9357 return $CFG->siteidentifier;
9361 * Check whether the given password has no more than the specified
9362 * number of consecutive identical characters.
9364 * @param string $password password to be checked against the password policy
9365 * @param integer $maxchars maximum number of consecutive identical characters
9366 * @return bool
9368 function check_consecutive_identical_characters($password, $maxchars) {
9370 if ($maxchars < 1) {
9371 return true; // Zero 0 is to disable this check.
9373 if (strlen($password) <= $maxchars) {
9374 return true; // Too short to fail this test.
9377 $previouschar = '';
9378 $consecutivecount = 1;
9379 foreach (str_split($password) as $char) {
9380 if ($char != $previouschar) {
9381 $consecutivecount = 1;
9382 } else {
9383 $consecutivecount++;
9384 if ($consecutivecount > $maxchars) {
9385 return false; // Check failed already.
9389 $previouschar = $char;
9392 return true;
9396 * Helper function to do partial function binding.
9397 * so we can use it for preg_replace_callback, for example
9398 * this works with php functions, user functions, static methods and class methods
9399 * it returns you a callback that you can pass on like so:
9401 * $callback = partial('somefunction', $arg1, $arg2);
9402 * or
9403 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9404 * or even
9405 * $obj = new someclass();
9406 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9408 * and then the arguments that are passed through at calltime are appended to the argument list.
9410 * @param mixed $function a php callback
9411 * @param mixed $arg1,... $argv arguments to partially bind with
9412 * @return array Array callback
9414 function partial() {
9415 if (!class_exists('partial')) {
9417 * Used to manage function binding.
9418 * @copyright 2009 Penny Leach
9419 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9421 class partial{
9422 /** @var array */
9423 public $values = array();
9424 /** @var string The function to call as a callback. */
9425 public $func;
9427 * Constructor
9428 * @param string $func
9429 * @param array $args
9431 public function __construct($func, $args) {
9432 $this->values = $args;
9433 $this->func = $func;
9436 * Calls the callback function.
9437 * @return mixed
9439 public function method() {
9440 $args = func_get_args();
9441 return call_user_func_array($this->func, array_merge($this->values, $args));
9445 $args = func_get_args();
9446 $func = array_shift($args);
9447 $p = new partial($func, $args);
9448 return array($p, 'method');
9452 * helper function to load up and initialise the mnet environment
9453 * this must be called before you use mnet functions.
9455 * @return mnet_environment the equivalent of old $MNET global
9457 function get_mnet_environment() {
9458 global $CFG;
9459 require_once($CFG->dirroot . '/mnet/lib.php');
9460 static $instance = null;
9461 if (empty($instance)) {
9462 $instance = new mnet_environment();
9463 $instance->init();
9465 return $instance;
9469 * during xmlrpc server code execution, any code wishing to access
9470 * information about the remote peer must use this to get it.
9472 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9474 function get_mnet_remote_client() {
9475 if (!defined('MNET_SERVER')) {
9476 debugging(get_string('notinxmlrpcserver', 'mnet'));
9477 return false;
9479 global $MNET_REMOTE_CLIENT;
9480 if (isset($MNET_REMOTE_CLIENT)) {
9481 return $MNET_REMOTE_CLIENT;
9483 return false;
9487 * during the xmlrpc server code execution, this will be called
9488 * to setup the object returned by {@link get_mnet_remote_client}
9490 * @param mnet_remote_client $client the client to set up
9491 * @throws moodle_exception
9493 function set_mnet_remote_client($client) {
9494 if (!defined('MNET_SERVER')) {
9495 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9497 global $MNET_REMOTE_CLIENT;
9498 $MNET_REMOTE_CLIENT = $client;
9502 * return the jump url for a given remote user
9503 * this is used for rewriting forum post links in emails, etc
9505 * @param stdclass $user the user to get the idp url for
9507 function mnet_get_idp_jump_url($user) {
9508 global $CFG;
9510 static $mnetjumps = array();
9511 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9512 $idp = mnet_get_peer_host($user->mnethostid);
9513 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9514 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9516 return $mnetjumps[$user->mnethostid];
9520 * Gets the homepage to use for the current user
9522 * @return int One of HOMEPAGE_*
9524 function get_home_page() {
9525 global $CFG;
9527 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9528 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9529 return HOMEPAGE_MY;
9530 } else {
9531 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9534 return HOMEPAGE_SITE;
9538 * Gets the name of a course to be displayed when showing a list of courses.
9539 * By default this is just $course->fullname but user can configure it. The
9540 * result of this function should be passed through print_string.
9541 * @param stdClass|course_in_list $course Moodle course object
9542 * @return string Display name of course (either fullname or short + fullname)
9544 function get_course_display_name_for_list($course) {
9545 global $CFG;
9546 if (!empty($CFG->courselistshortnames)) {
9547 if (!($course instanceof stdClass)) {
9548 $course = (object)convert_to_array($course);
9550 return get_string('courseextendednamedisplay', '', $course);
9551 } else {
9552 return $course->fullname;
9557 * The lang_string class
9559 * This special class is used to create an object representation of a string request.
9560 * It is special because processing doesn't occur until the object is first used.
9561 * The class was created especially to aid performance in areas where strings were
9562 * required to be generated but were not necessarily used.
9563 * As an example the admin tree when generated uses over 1500 strings, of which
9564 * normally only 1/3 are ever actually printed at any time.
9565 * The performance advantage is achieved by not actually processing strings that
9566 * arn't being used, as such reducing the processing required for the page.
9568 * How to use the lang_string class?
9569 * There are two methods of using the lang_string class, first through the
9570 * forth argument of the get_string function, and secondly directly.
9571 * The following are examples of both.
9572 * 1. Through get_string calls e.g.
9573 * $string = get_string($identifier, $component, $a, true);
9574 * $string = get_string('yes', 'moodle', null, true);
9575 * 2. Direct instantiation
9576 * $string = new lang_string($identifier, $component, $a, $lang);
9577 * $string = new lang_string('yes');
9579 * How do I use a lang_string object?
9580 * The lang_string object makes use of a magic __toString method so that you
9581 * are able to use the object exactly as you would use a string in most cases.
9582 * This means you are able to collect it into a variable and then directly
9583 * echo it, or concatenate it into another string, or similar.
9584 * The other thing you can do is manually get the string by calling the
9585 * lang_strings out method e.g.
9586 * $string = new lang_string('yes');
9587 * $string->out();
9588 * Also worth noting is that the out method can take one argument, $lang which
9589 * allows the developer to change the language on the fly.
9591 * When should I use a lang_string object?
9592 * The lang_string object is designed to be used in any situation where a
9593 * string may not be needed, but needs to be generated.
9594 * The admin tree is a good example of where lang_string objects should be
9595 * used.
9596 * A more practical example would be any class that requries strings that may
9597 * not be printed (after all classes get renderer by renderers and who knows
9598 * what they will do ;))
9600 * When should I not use a lang_string object?
9601 * Don't use lang_strings when you are going to use a string immediately.
9602 * There is no need as it will be processed immediately and there will be no
9603 * advantage, and in fact perhaps a negative hit as a class has to be
9604 * instantiated for a lang_string object, however get_string won't require
9605 * that.
9607 * Limitations:
9608 * 1. You cannot use a lang_string object as an array offset. Doing so will
9609 * result in PHP throwing an error. (You can use it as an object property!)
9611 * @package core
9612 * @category string
9613 * @copyright 2011 Sam Hemelryk
9614 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9616 class lang_string {
9618 /** @var string The strings identifier */
9619 protected $identifier;
9620 /** @var string The strings component. Default '' */
9621 protected $component = '';
9622 /** @var array|stdClass Any arguments required for the string. Default null */
9623 protected $a = null;
9624 /** @var string The language to use when processing the string. Default null */
9625 protected $lang = null;
9627 /** @var string The processed string (once processed) */
9628 protected $string = null;
9631 * A special boolean. If set to true then the object has been woken up and
9632 * cannot be regenerated. If this is set then $this->string MUST be used.
9633 * @var bool
9635 protected $forcedstring = false;
9638 * Constructs a lang_string object
9640 * This function should do as little processing as possible to ensure the best
9641 * performance for strings that won't be used.
9643 * @param string $identifier The strings identifier
9644 * @param string $component The strings component
9645 * @param stdClass|array $a Any arguments the string requires
9646 * @param string $lang The language to use when processing the string.
9647 * @throws coding_exception
9649 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9650 if (empty($component)) {
9651 $component = 'moodle';
9654 $this->identifier = $identifier;
9655 $this->component = $component;
9656 $this->lang = $lang;
9658 // We MUST duplicate $a to ensure that it if it changes by reference those
9659 // changes are not carried across.
9660 // To do this we always ensure $a or its properties/values are strings
9661 // and that any properties/values that arn't convertable are forgotten.
9662 if (!empty($a)) {
9663 if (is_scalar($a)) {
9664 $this->a = $a;
9665 } else if ($a instanceof lang_string) {
9666 $this->a = $a->out();
9667 } else if (is_object($a) or is_array($a)) {
9668 $a = (array)$a;
9669 $this->a = array();
9670 foreach ($a as $key => $value) {
9671 // Make sure conversion errors don't get displayed (results in '').
9672 if (is_array($value)) {
9673 $this->a[$key] = '';
9674 } else if (is_object($value)) {
9675 if (method_exists($value, '__toString')) {
9676 $this->a[$key] = $value->__toString();
9677 } else {
9678 $this->a[$key] = '';
9680 } else {
9681 $this->a[$key] = (string)$value;
9687 if (debugging(false, DEBUG_DEVELOPER)) {
9688 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9689 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9691 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9692 throw new coding_exception('Invalid string compontent. Please check your string definition');
9694 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9695 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9701 * Processes the string.
9703 * This function actually processes the string, stores it in the string property
9704 * and then returns it.
9705 * You will notice that this function is VERY similar to the get_string method.
9706 * That is because it is pretty much doing the same thing.
9707 * However as this function is an upgrade it isn't as tolerant to backwards
9708 * compatibility.
9710 * @return string
9711 * @throws coding_exception
9713 protected function get_string() {
9714 global $CFG;
9716 // Check if we need to process the string.
9717 if ($this->string === null) {
9718 // Check the quality of the identifier.
9719 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9720 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);
9723 // Process the string.
9724 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9725 // Debugging feature lets you display string identifier and component.
9726 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9727 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9730 // Return the string.
9731 return $this->string;
9735 * Returns the string
9737 * @param string $lang The langauge to use when processing the string
9738 * @return string
9740 public function out($lang = null) {
9741 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9742 if ($this->forcedstring) {
9743 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9744 return $this->get_string();
9746 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9747 return $translatedstring->out();
9749 return $this->get_string();
9753 * Magic __toString method for printing a string
9755 * @return string
9757 public function __toString() {
9758 return $this->get_string();
9762 * Magic __set_state method used for var_export
9764 * @return string
9766 public function __set_state() {
9767 return $this->get_string();
9771 * Prepares the lang_string for sleep and stores only the forcedstring and
9772 * string properties... the string cannot be regenerated so we need to ensure
9773 * it is generated for this.
9775 * @return string
9777 public function __sleep() {
9778 $this->get_string();
9779 $this->forcedstring = true;
9780 return array('forcedstring', 'string', 'lang');