Automatically generated installer lang files
[moodle.git] / lib / moodlelib.php
blob6b8b4a3ecb80b419d53c335865a70be8c27c088b
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 clearstatcache();
1625 remove_dir($CFG->cachedir.'', true);
1627 // Make sure cache dir is writable, throws exception if not.
1628 make_cache_directory('');
1630 // This is the only place where we purge local caches, we are only adding files there.
1631 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1632 remove_dir($CFG->localcachedir, true);
1633 set_config('localcachedirpurged', time());
1634 make_localcache_directory('', true);
1635 \core\task\manager::clear_static_caches();
1639 * Get volatile flags
1641 * @param string $type
1642 * @param int $changedsince default null
1643 * @return array records array
1645 function get_cache_flags($type, $changedsince = null) {
1646 global $DB;
1648 $params = array('type' => $type, 'expiry' => time());
1649 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1650 if ($changedsince !== null) {
1651 $params['changedsince'] = $changedsince;
1652 $sqlwhere .= " AND timemodified > :changedsince";
1654 $cf = array();
1655 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1656 foreach ($flags as $flag) {
1657 $cf[$flag->name] = $flag->value;
1660 return $cf;
1664 * Get volatile flags
1666 * @param string $type
1667 * @param string $name
1668 * @param int $changedsince default null
1669 * @return string|false The cache flag value or false
1671 function get_cache_flag($type, $name, $changedsince=null) {
1672 global $DB;
1674 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1676 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1677 if ($changedsince !== null) {
1678 $params['changedsince'] = $changedsince;
1679 $sqlwhere .= " AND timemodified > :changedsince";
1682 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1686 * Set a volatile flag
1688 * @param string $type the "type" namespace for the key
1689 * @param string $name the key to set
1690 * @param string $value the value to set (without magic quotes) - null will remove the flag
1691 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1692 * @return bool Always returns true
1694 function set_cache_flag($type, $name, $value, $expiry = null) {
1695 global $DB;
1697 $timemodified = time();
1698 if ($expiry === null || $expiry < $timemodified) {
1699 $expiry = $timemodified + 24 * 60 * 60;
1700 } else {
1701 $expiry = (int)$expiry;
1704 if ($value === null) {
1705 unset_cache_flag($type, $name);
1706 return true;
1709 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1710 // This is a potential problem in DEBUG_DEVELOPER.
1711 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1712 return true; // No need to update.
1714 $f->value = $value;
1715 $f->expiry = $expiry;
1716 $f->timemodified = $timemodified;
1717 $DB->update_record('cache_flags', $f);
1718 } else {
1719 $f = new stdClass();
1720 $f->flagtype = $type;
1721 $f->name = $name;
1722 $f->value = $value;
1723 $f->expiry = $expiry;
1724 $f->timemodified = $timemodified;
1725 $DB->insert_record('cache_flags', $f);
1727 return true;
1731 * Removes a single volatile flag
1733 * @param string $type the "type" namespace for the key
1734 * @param string $name the key to set
1735 * @return bool
1737 function unset_cache_flag($type, $name) {
1738 global $DB;
1739 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1740 return true;
1744 * Garbage-collect volatile flags
1746 * @return bool Always returns true
1748 function gc_cache_flags() {
1749 global $DB;
1750 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1751 return true;
1754 // USER PREFERENCE API.
1757 * Refresh user preference cache. This is used most often for $USER
1758 * object that is stored in session, but it also helps with performance in cron script.
1760 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1762 * @package core
1763 * @category preference
1764 * @access public
1765 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1766 * @param int $cachelifetime Cache life time on the current page (in seconds)
1767 * @throws coding_exception
1768 * @return null
1770 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1771 global $DB;
1772 // Static cache, we need to check on each page load, not only every 2 minutes.
1773 static $loadedusers = array();
1775 if (!isset($user->id)) {
1776 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1779 if (empty($user->id) or isguestuser($user->id)) {
1780 // No permanent storage for not-logged-in users and guest.
1781 if (!isset($user->preference)) {
1782 $user->preference = array();
1784 return;
1787 $timenow = time();
1789 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1790 // Already loaded at least once on this page. Are we up to date?
1791 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1792 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1793 return;
1795 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1796 // No change since the lastcheck on this page.
1797 $user->preference['_lastloaded'] = $timenow;
1798 return;
1802 // OK, so we have to reload all preferences.
1803 $loadedusers[$user->id] = true;
1804 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1805 $user->preference['_lastloaded'] = $timenow;
1809 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1811 * NOTE: internal function, do not call from other code.
1813 * @package core
1814 * @access private
1815 * @param integer $userid the user whose prefs were changed.
1817 function mark_user_preferences_changed($userid) {
1818 global $CFG;
1820 if (empty($userid) or isguestuser($userid)) {
1821 // No cache flags for guest and not-logged-in users.
1822 return;
1825 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1829 * Sets a preference for the specified user.
1831 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1833 * @package core
1834 * @category preference
1835 * @access public
1836 * @param string $name The key to set as preference for the specified user
1837 * @param string $value The value to set for the $name key in the specified user's
1838 * record, null means delete current value.
1839 * @param stdClass|int|null $user A moodle user object or id, null means current user
1840 * @throws coding_exception
1841 * @return bool Always true or exception
1843 function set_user_preference($name, $value, $user = null) {
1844 global $USER, $DB;
1846 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1847 throw new coding_exception('Invalid preference name in set_user_preference() call');
1850 if (is_null($value)) {
1851 // Null means delete current.
1852 return unset_user_preference($name, $user);
1853 } else if (is_object($value)) {
1854 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1855 } else if (is_array($value)) {
1856 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1858 // Value column maximum length is 1333 characters.
1859 $value = (string)$value;
1860 if (core_text::strlen($value) > 1333) {
1861 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1864 if (is_null($user)) {
1865 $user = $USER;
1866 } else if (isset($user->id)) {
1867 // It is a valid object.
1868 } else if (is_numeric($user)) {
1869 $user = (object)array('id' => (int)$user);
1870 } else {
1871 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1874 check_user_preferences_loaded($user);
1876 if (empty($user->id) or isguestuser($user->id)) {
1877 // No permanent storage for not-logged-in users and guest.
1878 $user->preference[$name] = $value;
1879 return true;
1882 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1883 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1884 // Preference already set to this value.
1885 return true;
1887 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1889 } else {
1890 $preference = new stdClass();
1891 $preference->userid = $user->id;
1892 $preference->name = $name;
1893 $preference->value = $value;
1894 $DB->insert_record('user_preferences', $preference);
1897 // Update value in cache.
1898 $user->preference[$name] = $value;
1899 // Update the $USER in case where we've not a direct reference to $USER.
1900 if ($user !== $USER && $user->id == $USER->id) {
1901 $USER->preference[$name] = $value;
1904 // Set reload flag for other sessions.
1905 mark_user_preferences_changed($user->id);
1907 return true;
1911 * Sets a whole array of preferences for the current user
1913 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1915 * @package core
1916 * @category preference
1917 * @access public
1918 * @param array $prefarray An array of key/value pairs to be set
1919 * @param stdClass|int|null $user A moodle user object or id, null means current user
1920 * @return bool Always true or exception
1922 function set_user_preferences(array $prefarray, $user = null) {
1923 foreach ($prefarray as $name => $value) {
1924 set_user_preference($name, $value, $user);
1926 return true;
1930 * Unsets a preference completely by deleting it from the database
1932 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1934 * @package core
1935 * @category preference
1936 * @access public
1937 * @param string $name The key to unset as preference for the specified user
1938 * @param stdClass|int|null $user A moodle user object or id, null means current user
1939 * @throws coding_exception
1940 * @return bool Always true or exception
1942 function unset_user_preference($name, $user = null) {
1943 global $USER, $DB;
1945 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1946 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1949 if (is_null($user)) {
1950 $user = $USER;
1951 } else if (isset($user->id)) {
1952 // It is a valid object.
1953 } else if (is_numeric($user)) {
1954 $user = (object)array('id' => (int)$user);
1955 } else {
1956 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1959 check_user_preferences_loaded($user);
1961 if (empty($user->id) or isguestuser($user->id)) {
1962 // No permanent storage for not-logged-in user and guest.
1963 unset($user->preference[$name]);
1964 return true;
1967 // Delete from DB.
1968 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1970 // Delete the preference from cache.
1971 unset($user->preference[$name]);
1972 // Update the $USER in case where we've not a direct reference to $USER.
1973 if ($user !== $USER && $user->id == $USER->id) {
1974 unset($USER->preference[$name]);
1977 // Set reload flag for other sessions.
1978 mark_user_preferences_changed($user->id);
1980 return true;
1984 * Used to fetch user preference(s)
1986 * If no arguments are supplied this function will return
1987 * all of the current user preferences as an array.
1989 * If a name is specified then this function
1990 * attempts to return that particular preference value. If
1991 * none is found, then the optional value $default is returned,
1992 * otherwise null.
1994 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1996 * @package core
1997 * @category preference
1998 * @access public
1999 * @param string $name Name of the key to use in finding a preference value
2000 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2001 * @param stdClass|int|null $user A moodle user object or id, null means current user
2002 * @throws coding_exception
2003 * @return string|mixed|null A string containing the value of a single preference. An
2004 * array with all of the preferences or null
2006 function get_user_preferences($name = null, $default = null, $user = null) {
2007 global $USER;
2009 if (is_null($name)) {
2010 // All prefs.
2011 } else if (is_numeric($name) or $name === '_lastloaded') {
2012 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2015 if (is_null($user)) {
2016 $user = $USER;
2017 } else if (isset($user->id)) {
2018 // Is a valid object.
2019 } else if (is_numeric($user)) {
2020 $user = (object)array('id' => (int)$user);
2021 } else {
2022 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2025 check_user_preferences_loaded($user);
2027 if (empty($name)) {
2028 // All values.
2029 return $user->preference;
2030 } else if (isset($user->preference[$name])) {
2031 // The single string value.
2032 return $user->preference[$name];
2033 } else {
2034 // Default value (null if not specified).
2035 return $default;
2039 // FUNCTIONS FOR HANDLING TIME.
2042 * Given Gregorian date parts in user time produce a GMT timestamp.
2044 * @package core
2045 * @category time
2046 * @param int $year The year part to create timestamp of
2047 * @param int $month The month part to create timestamp of
2048 * @param int $day The day part to create timestamp of
2049 * @param int $hour The hour part to create timestamp of
2050 * @param int $minute The minute part to create timestamp of
2051 * @param int $second The second part to create timestamp of
2052 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2053 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2054 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2055 * applied only if timezone is 99 or string.
2056 * @return int GMT timestamp
2058 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2059 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2060 $date->setDate((int)$year, (int)$month, (int)$day);
2061 $date->setTime((int)$hour, (int)$minute, (int)$second);
2063 $time = $date->getTimestamp();
2065 // Moodle BC DST stuff.
2066 if (!$applydst) {
2067 $time += dst_offset_on($time, $timezone);
2070 return $time;
2075 * Format a date/time (seconds) as weeks, days, hours etc as needed
2077 * Given an amount of time in seconds, returns string
2078 * formatted nicely as weeks, days, hours etc as needed
2080 * @package core
2081 * @category time
2082 * @uses MINSECS
2083 * @uses HOURSECS
2084 * @uses DAYSECS
2085 * @uses YEARSECS
2086 * @param int $totalsecs Time in seconds
2087 * @param stdClass $str Should be a time object
2088 * @return string A nicely formatted date/time string
2090 function format_time($totalsecs, $str = null) {
2092 $totalsecs = abs($totalsecs);
2094 if (!$str) {
2095 // Create the str structure the slow way.
2096 $str = new stdClass();
2097 $str->day = get_string('day');
2098 $str->days = get_string('days');
2099 $str->hour = get_string('hour');
2100 $str->hours = get_string('hours');
2101 $str->min = get_string('min');
2102 $str->mins = get_string('mins');
2103 $str->sec = get_string('sec');
2104 $str->secs = get_string('secs');
2105 $str->year = get_string('year');
2106 $str->years = get_string('years');
2109 $years = floor($totalsecs/YEARSECS);
2110 $remainder = $totalsecs - ($years*YEARSECS);
2111 $days = floor($remainder/DAYSECS);
2112 $remainder = $totalsecs - ($days*DAYSECS);
2113 $hours = floor($remainder/HOURSECS);
2114 $remainder = $remainder - ($hours*HOURSECS);
2115 $mins = floor($remainder/MINSECS);
2116 $secs = $remainder - ($mins*MINSECS);
2118 $ss = ($secs == 1) ? $str->sec : $str->secs;
2119 $sm = ($mins == 1) ? $str->min : $str->mins;
2120 $sh = ($hours == 1) ? $str->hour : $str->hours;
2121 $sd = ($days == 1) ? $str->day : $str->days;
2122 $sy = ($years == 1) ? $str->year : $str->years;
2124 $oyears = '';
2125 $odays = '';
2126 $ohours = '';
2127 $omins = '';
2128 $osecs = '';
2130 if ($years) {
2131 $oyears = $years .' '. $sy;
2133 if ($days) {
2134 $odays = $days .' '. $sd;
2136 if ($hours) {
2137 $ohours = $hours .' '. $sh;
2139 if ($mins) {
2140 $omins = $mins .' '. $sm;
2142 if ($secs) {
2143 $osecs = $secs .' '. $ss;
2146 if ($years) {
2147 return trim($oyears .' '. $odays);
2149 if ($days) {
2150 return trim($odays .' '. $ohours);
2152 if ($hours) {
2153 return trim($ohours .' '. $omins);
2155 if ($mins) {
2156 return trim($omins .' '. $osecs);
2158 if ($secs) {
2159 return $osecs;
2161 return get_string('now');
2165 * Returns a formatted string that represents a date in user time.
2167 * @package core
2168 * @category time
2169 * @param int $date the timestamp in UTC, as obtained from the database.
2170 * @param string $format strftime format. You should probably get this using
2171 * get_string('strftime...', 'langconfig');
2172 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2173 * not 99 then daylight saving will not be added.
2174 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2175 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2176 * If false then the leading zero is maintained.
2177 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2178 * @return string the formatted date/time.
2180 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2181 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2182 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2186 * Returns a formatted date ensuring it is UTF-8.
2188 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2189 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2191 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2192 * @param string $format strftime format.
2193 * @param int|float|string $tz the user timezone
2194 * @return string the formatted date/time.
2195 * @since Moodle 2.3.3
2197 function date_format_string($date, $format, $tz = 99) {
2198 global $CFG;
2200 $localewincharset = null;
2201 // Get the calendar type user is using.
2202 if ($CFG->ostype == 'WINDOWS') {
2203 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2204 $localewincharset = $calendartype->locale_win_charset();
2207 if ($localewincharset) {
2208 $format = core_text::convert($format, 'utf-8', $localewincharset);
2211 date_default_timezone_set(core_date::get_user_timezone($tz));
2212 $datestring = strftime($format, $date);
2213 core_date::set_default_server_timezone();
2215 if ($localewincharset) {
2216 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2219 return $datestring;
2223 * Given a $time timestamp in GMT (seconds since epoch),
2224 * returns an array that represents the Gregorian date in user time
2226 * @package core
2227 * @category time
2228 * @param int $time Timestamp in GMT
2229 * @param float|int|string $timezone user timezone
2230 * @return array An array that represents the date in user time
2232 function usergetdate($time, $timezone=99) {
2233 date_default_timezone_set(core_date::get_user_timezone($timezone));
2234 $result = getdate($time);
2235 core_date::set_default_server_timezone();
2237 return $result;
2241 * Given a GMT timestamp (seconds since epoch), offsets it by
2242 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2244 * NOTE: this function does not include DST properly,
2245 * you should use the PHP date stuff instead!
2247 * @package core
2248 * @category time
2249 * @param int $date Timestamp in GMT
2250 * @param float|int|string $timezone user timezone
2251 * @return int
2253 function usertime($date, $timezone=99) {
2254 $userdate = new DateTime('@' . $date);
2255 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2256 $dst = dst_offset_on($date, $timezone);
2258 return $date - $userdate->getOffset() + $dst;
2262 * Given a time, return the GMT timestamp of the most recent midnight
2263 * for the current user.
2265 * @package core
2266 * @category time
2267 * @param int $date Timestamp in GMT
2268 * @param float|int|string $timezone user timezone
2269 * @return int Returns a GMT timestamp
2271 function usergetmidnight($date, $timezone=99) {
2273 $userdate = usergetdate($date, $timezone);
2275 // Time of midnight of this user's day, in GMT.
2276 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2281 * Returns a string that prints the user's timezone
2283 * @package core
2284 * @category time
2285 * @param float|int|string $timezone user timezone
2286 * @return string
2288 function usertimezone($timezone=99) {
2289 $tz = core_date::get_user_timezone($timezone);
2290 return core_date::get_localised_timezone($tz);
2294 * Returns a float or a string which denotes the user's timezone
2295 * 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)
2296 * means that for this timezone there are also DST rules to be taken into account
2297 * Checks various settings and picks the most dominant of those which have a value
2299 * @package core
2300 * @category time
2301 * @param float|int|string $tz timezone to calculate GMT time offset before
2302 * calculating user timezone, 99 is default user timezone
2303 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2304 * @return float|string
2306 function get_user_timezone($tz = 99) {
2307 global $USER, $CFG;
2309 $timezones = array(
2310 $tz,
2311 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2312 isset($USER->timezone) ? $USER->timezone : 99,
2313 isset($CFG->timezone) ? $CFG->timezone : 99,
2316 $tz = 99;
2318 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2319 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2320 $tz = $next['value'];
2322 return is_numeric($tz) ? (float) $tz : $tz;
2326 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2327 * - Note: Daylight saving only works for string timezones and not for float.
2329 * @package core
2330 * @category time
2331 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2332 * @param int|float|string $strtimezone user timezone
2333 * @return int
2335 function dst_offset_on($time, $strtimezone = null) {
2336 $tz = core_date::get_user_timezone($strtimezone);
2337 $date = new DateTime('@' . $time);
2338 $date->setTimezone(new DateTimeZone($tz));
2339 if ($date->format('I') == '1') {
2340 if ($tz === 'Australia/Lord_Howe') {
2341 return 1800;
2343 return 3600;
2345 return 0;
2349 * Calculates when the day appears in specific month
2351 * @package core
2352 * @category time
2353 * @param int $startday starting day of the month
2354 * @param int $weekday The day when week starts (normally taken from user preferences)
2355 * @param int $month The month whose day is sought
2356 * @param int $year The year of the month whose day is sought
2357 * @return int
2359 function find_day_in_month($startday, $weekday, $month, $year) {
2360 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2362 $daysinmonth = days_in_month($month, $year);
2363 $daysinweek = count($calendartype->get_weekdays());
2365 if ($weekday == -1) {
2366 // Don't care about weekday, so return:
2367 // abs($startday) if $startday != -1
2368 // $daysinmonth otherwise.
2369 return ($startday == -1) ? $daysinmonth : abs($startday);
2372 // From now on we 're looking for a specific weekday.
2373 // Give "end of month" its actual value, since we know it.
2374 if ($startday == -1) {
2375 $startday = -1 * $daysinmonth;
2378 // Starting from day $startday, the sign is the direction.
2379 if ($startday < 1) {
2380 $startday = abs($startday);
2381 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2383 // This is the last such weekday of the month.
2384 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2385 if ($lastinmonth > $daysinmonth) {
2386 $lastinmonth -= $daysinweek;
2389 // Find the first such weekday <= $startday.
2390 while ($lastinmonth > $startday) {
2391 $lastinmonth -= $daysinweek;
2394 return $lastinmonth;
2395 } else {
2396 $indexweekday = dayofweek($startday, $month, $year);
2398 $diff = $weekday - $indexweekday;
2399 if ($diff < 0) {
2400 $diff += $daysinweek;
2403 // This is the first such weekday of the month equal to or after $startday.
2404 $firstfromindex = $startday + $diff;
2406 return $firstfromindex;
2411 * Calculate the number of days in a given month
2413 * @package core
2414 * @category time
2415 * @param int $month The month whose day count is sought
2416 * @param int $year The year of the month whose day count is sought
2417 * @return int
2419 function days_in_month($month, $year) {
2420 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2421 return $calendartype->get_num_days_in_month($year, $month);
2425 * Calculate the position in the week of a specific calendar day
2427 * @package core
2428 * @category time
2429 * @param int $day The day of the date whose position in the week is sought
2430 * @param int $month The month of the date whose position in the week is sought
2431 * @param int $year The year of the date whose position in the week is sought
2432 * @return int
2434 function dayofweek($day, $month, $year) {
2435 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2436 return $calendartype->get_weekday($year, $month, $day);
2439 // USER AUTHENTICATION AND LOGIN.
2442 * Returns full login url.
2444 * @return string login url
2446 function get_login_url() {
2447 global $CFG;
2449 $url = "$CFG->wwwroot/login/index.php";
2451 if (!empty($CFG->loginhttps)) {
2452 $url = str_replace('http:', 'https:', $url);
2455 return $url;
2459 * This function checks that the current user is logged in and has the
2460 * required privileges
2462 * This function checks that the current user is logged in, and optionally
2463 * whether they are allowed to be in a particular course and view a particular
2464 * course module.
2465 * If they are not logged in, then it redirects them to the site login unless
2466 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2467 * case they are automatically logged in as guests.
2468 * If $courseid is given and the user is not enrolled in that course then the
2469 * user is redirected to the course enrolment page.
2470 * If $cm is given and the course module is hidden and the user is not a teacher
2471 * in the course then the user is redirected to the course home page.
2473 * When $cm parameter specified, this function sets page layout to 'module'.
2474 * You need to change it manually later if some other layout needed.
2476 * @package core_access
2477 * @category access
2479 * @param mixed $courseorid id of the course or course object
2480 * @param bool $autologinguest default true
2481 * @param object $cm course module object
2482 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2483 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2484 * in order to keep redirects working properly. MDL-14495
2485 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2486 * @return mixed Void, exit, and die depending on path
2487 * @throws coding_exception
2488 * @throws require_login_exception
2490 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2491 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2493 // Must not redirect when byteserving already started.
2494 if (!empty($_SERVER['HTTP_RANGE'])) {
2495 $preventredirect = true;
2498 if (AJAX_SCRIPT) {
2499 // We cannot redirect for AJAX scripts either.
2500 $preventredirect = true;
2503 // Setup global $COURSE, themes, language and locale.
2504 if (!empty($courseorid)) {
2505 if (is_object($courseorid)) {
2506 $course = $courseorid;
2507 } else if ($courseorid == SITEID) {
2508 $course = clone($SITE);
2509 } else {
2510 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2512 if ($cm) {
2513 if ($cm->course != $course->id) {
2514 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2516 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2517 if (!($cm instanceof cm_info)) {
2518 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2519 // db queries so this is not really a performance concern, however it is obviously
2520 // better if you use get_fast_modinfo to get the cm before calling this.
2521 $modinfo = get_fast_modinfo($course);
2522 $cm = $modinfo->get_cm($cm->id);
2525 } else {
2526 // Do not touch global $COURSE via $PAGE->set_course(),
2527 // the reasons is we need to be able to call require_login() at any time!!
2528 $course = $SITE;
2529 if ($cm) {
2530 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2534 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2535 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2536 // risk leading the user back to the AJAX request URL.
2537 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2538 $setwantsurltome = false;
2541 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2542 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2543 if ($preventredirect) {
2544 throw new require_login_session_timeout_exception();
2545 } else {
2546 if ($setwantsurltome) {
2547 $SESSION->wantsurl = qualified_me();
2549 redirect(get_login_url());
2553 // If the user is not even logged in yet then make sure they are.
2554 if (!isloggedin()) {
2555 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2556 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2557 // Misconfigured site guest, just redirect to login page.
2558 redirect(get_login_url());
2559 exit; // Never reached.
2561 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2562 complete_user_login($guest);
2563 $USER->autologinguest = true;
2564 $SESSION->lang = $lang;
2565 } else {
2566 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2567 if ($preventredirect) {
2568 throw new require_login_exception('You are not logged in');
2571 if ($setwantsurltome) {
2572 $SESSION->wantsurl = qualified_me();
2575 $referer = get_local_referer(false);
2576 if (!empty($referer)) {
2577 $SESSION->fromurl = $referer;
2580 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2581 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2582 foreach($authsequence as $authname) {
2583 $authplugin = get_auth_plugin($authname);
2584 $authplugin->pre_loginpage_hook();
2585 if (isloggedin()) {
2586 break;
2590 // If we're still not logged in then go to the login page
2591 if (!isloggedin()) {
2592 redirect(get_login_url());
2593 exit; // Never reached.
2598 // Loginas as redirection if needed.
2599 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2600 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2601 if ($USER->loginascontext->instanceid != $course->id) {
2602 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2607 // Check whether the user should be changing password (but only if it is REALLY them).
2608 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2609 $userauth = get_auth_plugin($USER->auth);
2610 if ($userauth->can_change_password() and !$preventredirect) {
2611 if ($setwantsurltome) {
2612 $SESSION->wantsurl = qualified_me();
2614 if ($changeurl = $userauth->change_password_url()) {
2615 // Use plugin custom url.
2616 redirect($changeurl);
2617 } else {
2618 // Use moodle internal method.
2619 if (empty($CFG->loginhttps)) {
2620 redirect($CFG->wwwroot .'/login/change_password.php');
2621 } else {
2622 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2623 redirect($wwwroot .'/login/change_password.php');
2626 } else {
2627 print_error('nopasswordchangeforced', 'auth');
2631 // Check that the user account is properly set up. If we can't redirect to
2632 // edit their profile and this is not a WS request, perform just the lax check.
2633 // It will allow them to use filepicker on the profile edit page.
2635 if ($preventredirect && !WS_SERVER) {
2636 $usernotfullysetup = user_not_fully_set_up($USER, false);
2637 } else {
2638 $usernotfullysetup = user_not_fully_set_up($USER, true);
2641 if ($usernotfullysetup) {
2642 if ($preventredirect) {
2643 throw new require_login_exception('User not fully set-up');
2645 if ($setwantsurltome) {
2646 $SESSION->wantsurl = qualified_me();
2648 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2651 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2652 sesskey();
2654 // Do not bother admins with any formalities.
2655 if (is_siteadmin()) {
2656 // Set the global $COURSE.
2657 if ($cm) {
2658 $PAGE->set_cm($cm, $course);
2659 $PAGE->set_pagelayout('incourse');
2660 } else if (!empty($courseorid)) {
2661 $PAGE->set_course($course);
2663 // Set accesstime or the user will appear offline which messes up messaging.
2664 user_accesstime_log($course->id);
2665 return;
2668 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2669 if (!$USER->policyagreed and !is_siteadmin()) {
2670 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2671 if ($preventredirect) {
2672 throw new require_login_exception('Policy not agreed');
2674 if ($setwantsurltome) {
2675 $SESSION->wantsurl = qualified_me();
2677 redirect($CFG->wwwroot .'/user/policy.php');
2678 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2679 if ($preventredirect) {
2680 throw new require_login_exception('Policy not agreed');
2682 if ($setwantsurltome) {
2683 $SESSION->wantsurl = qualified_me();
2685 redirect($CFG->wwwroot .'/user/policy.php');
2689 // Fetch the system context, the course context, and prefetch its child contexts.
2690 $sysctx = context_system::instance();
2691 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2692 if ($cm) {
2693 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2694 } else {
2695 $cmcontext = null;
2698 // If the site is currently under maintenance, then print a message.
2699 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2700 if ($preventredirect) {
2701 throw new require_login_exception('Maintenance in progress');
2703 $PAGE->set_context(null);
2704 print_maintenance_message();
2707 // Make sure the course itself is not hidden.
2708 if ($course->id == SITEID) {
2709 // Frontpage can not be hidden.
2710 } else {
2711 if (is_role_switched($course->id)) {
2712 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2713 } else {
2714 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2715 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2716 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2717 if ($preventredirect) {
2718 throw new require_login_exception('Course is hidden');
2720 $PAGE->set_context(null);
2721 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2722 // the navigation will mess up when trying to find it.
2723 navigation_node::override_active_url(new moodle_url('/'));
2724 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2729 // Is the user enrolled?
2730 if ($course->id == SITEID) {
2731 // Everybody is enrolled on the frontpage.
2732 } else {
2733 if (\core\session\manager::is_loggedinas()) {
2734 // Make sure the REAL person can access this course first.
2735 $realuser = \core\session\manager::get_realuser();
2736 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2737 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2738 if ($preventredirect) {
2739 throw new require_login_exception('Invalid course login-as access');
2741 $PAGE->set_context(null);
2742 echo $OUTPUT->header();
2743 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2747 $access = false;
2749 if (is_role_switched($course->id)) {
2750 // Ok, user had to be inside this course before the switch.
2751 $access = true;
2753 } else if (is_viewing($coursecontext, $USER)) {
2754 // Ok, no need to mess with enrol.
2755 $access = true;
2757 } else {
2758 if (isset($USER->enrol['enrolled'][$course->id])) {
2759 if ($USER->enrol['enrolled'][$course->id] > time()) {
2760 $access = true;
2761 if (isset($USER->enrol['tempguest'][$course->id])) {
2762 unset($USER->enrol['tempguest'][$course->id]);
2763 remove_temp_course_roles($coursecontext);
2765 } else {
2766 // Expired.
2767 unset($USER->enrol['enrolled'][$course->id]);
2770 if (isset($USER->enrol['tempguest'][$course->id])) {
2771 if ($USER->enrol['tempguest'][$course->id] == 0) {
2772 $access = true;
2773 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2774 $access = true;
2775 } else {
2776 // Expired.
2777 unset($USER->enrol['tempguest'][$course->id]);
2778 remove_temp_course_roles($coursecontext);
2782 if (!$access) {
2783 // Cache not ok.
2784 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2785 if ($until !== false) {
2786 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2787 if ($until == 0) {
2788 $until = ENROL_MAX_TIMESTAMP;
2790 $USER->enrol['enrolled'][$course->id] = $until;
2791 $access = true;
2793 } else {
2794 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2795 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2796 $enrols = enrol_get_plugins(true);
2797 // First ask all enabled enrol instances in course if they want to auto enrol user.
2798 foreach ($instances as $instance) {
2799 if (!isset($enrols[$instance->enrol])) {
2800 continue;
2802 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2803 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2804 if ($until !== false) {
2805 if ($until == 0) {
2806 $until = ENROL_MAX_TIMESTAMP;
2808 $USER->enrol['enrolled'][$course->id] = $until;
2809 $access = true;
2810 break;
2813 // If not enrolled yet try to gain temporary guest access.
2814 if (!$access) {
2815 foreach ($instances as $instance) {
2816 if (!isset($enrols[$instance->enrol])) {
2817 continue;
2819 // Get a duration for the guest access, a timestamp in the future or false.
2820 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2821 if ($until !== false and $until > time()) {
2822 $USER->enrol['tempguest'][$course->id] = $until;
2823 $access = true;
2824 break;
2832 if (!$access) {
2833 if ($preventredirect) {
2834 throw new require_login_exception('Not enrolled');
2836 if ($setwantsurltome) {
2837 $SESSION->wantsurl = qualified_me();
2839 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2843 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2844 if ($cm && !$cm->uservisible) {
2845 if ($preventredirect) {
2846 throw new require_login_exception('Activity is hidden');
2848 if ($course->id != SITEID) {
2849 $url = new moodle_url('/course/view.php', array('id' => $course->id));
2850 } else {
2851 $url = new moodle_url('/');
2853 redirect($url, get_string('activityiscurrentlyhidden'));
2856 // Set the global $COURSE.
2857 if ($cm) {
2858 $PAGE->set_cm($cm, $course);
2859 $PAGE->set_pagelayout('incourse');
2860 } else if (!empty($courseorid)) {
2861 $PAGE->set_course($course);
2864 // Finally access granted, update lastaccess times.
2865 user_accesstime_log($course->id);
2870 * This function just makes sure a user is logged out.
2872 * @package core_access
2873 * @category access
2875 function require_logout() {
2876 global $USER, $DB;
2878 if (!isloggedin()) {
2879 // This should not happen often, no need for hooks or events here.
2880 \core\session\manager::terminate_current();
2881 return;
2884 // Execute hooks before action.
2885 $authplugins = array();
2886 $authsequence = get_enabled_auth_plugins();
2887 foreach ($authsequence as $authname) {
2888 $authplugins[$authname] = get_auth_plugin($authname);
2889 $authplugins[$authname]->prelogout_hook();
2892 // Store info that gets removed during logout.
2893 $sid = session_id();
2894 $event = \core\event\user_loggedout::create(
2895 array(
2896 'userid' => $USER->id,
2897 'objectid' => $USER->id,
2898 'other' => array('sessionid' => $sid),
2901 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2902 $event->add_record_snapshot('sessions', $session);
2905 // Clone of $USER object to be used by auth plugins.
2906 $user = fullclone($USER);
2908 // Delete session record and drop $_SESSION content.
2909 \core\session\manager::terminate_current();
2911 // Trigger event AFTER action.
2912 $event->trigger();
2914 // Hook to execute auth plugins redirection after event trigger.
2915 foreach ($authplugins as $authplugin) {
2916 $authplugin->postlogout_hook($user);
2921 * Weaker version of require_login()
2923 * This is a weaker version of {@link require_login()} which only requires login
2924 * when called from within a course rather than the site page, unless
2925 * the forcelogin option is turned on.
2926 * @see require_login()
2928 * @package core_access
2929 * @category access
2931 * @param mixed $courseorid The course object or id in question
2932 * @param bool $autologinguest Allow autologin guests if that is wanted
2933 * @param object $cm Course activity module if known
2934 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2935 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2936 * in order to keep redirects working properly. MDL-14495
2937 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2938 * @return void
2939 * @throws coding_exception
2941 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2942 global $CFG, $PAGE, $SITE;
2943 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
2944 or (!is_object($courseorid) and $courseorid == SITEID));
2945 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2946 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2947 // db queries so this is not really a performance concern, however it is obviously
2948 // better if you use get_fast_modinfo to get the cm before calling this.
2949 if (is_object($courseorid)) {
2950 $course = $courseorid;
2951 } else {
2952 $course = clone($SITE);
2954 $modinfo = get_fast_modinfo($course);
2955 $cm = $modinfo->get_cm($cm->id);
2957 if (!empty($CFG->forcelogin)) {
2958 // Login required for both SITE and courses.
2959 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2961 } else if ($issite && !empty($cm) and !$cm->uservisible) {
2962 // Always login for hidden activities.
2963 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2965 } else if ($issite) {
2966 // Login for SITE not required.
2967 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
2968 if (!empty($courseorid)) {
2969 if (is_object($courseorid)) {
2970 $course = $courseorid;
2971 } else {
2972 $course = clone $SITE;
2974 if ($cm) {
2975 if ($cm->course != $course->id) {
2976 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2978 $PAGE->set_cm($cm, $course);
2979 $PAGE->set_pagelayout('incourse');
2980 } else {
2981 $PAGE->set_course($course);
2983 } else {
2984 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
2985 $PAGE->set_course($PAGE->course);
2987 user_accesstime_log(SITEID);
2988 return;
2990 } else {
2991 // Course login always required.
2992 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2997 * Require key login. Function terminates with error if key not found or incorrect.
2999 * @uses NO_MOODLE_COOKIES
3000 * @uses PARAM_ALPHANUM
3001 * @param string $script unique script identifier
3002 * @param int $instance optional instance id
3003 * @return int Instance ID
3005 function require_user_key_login($script, $instance=null) {
3006 global $DB;
3008 if (!NO_MOODLE_COOKIES) {
3009 print_error('sessioncookiesdisable');
3012 // Extra safety.
3013 \core\session\manager::write_close();
3015 $keyvalue = required_param('key', PARAM_ALPHANUM);
3017 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3018 print_error('invalidkey');
3021 if (!empty($key->validuntil) and $key->validuntil < time()) {
3022 print_error('expiredkey');
3025 if ($key->iprestriction) {
3026 $remoteaddr = getremoteaddr(null);
3027 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3028 print_error('ipmismatch');
3032 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3033 print_error('invaliduserid');
3036 // Emulate normal session.
3037 enrol_check_plugins($user);
3038 \core\session\manager::set_user($user);
3040 // Note we are not using normal login.
3041 if (!defined('USER_KEY_LOGIN')) {
3042 define('USER_KEY_LOGIN', true);
3045 // Return instance id - it might be empty.
3046 return $key->instance;
3050 * Creates a new private user access key.
3052 * @param string $script unique target identifier
3053 * @param int $userid
3054 * @param int $instance optional instance id
3055 * @param string $iprestriction optional ip restricted access
3056 * @param timestamp $validuntil key valid only until given data
3057 * @return string access key value
3059 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3060 global $DB;
3062 $key = new stdClass();
3063 $key->script = $script;
3064 $key->userid = $userid;
3065 $key->instance = $instance;
3066 $key->iprestriction = $iprestriction;
3067 $key->validuntil = $validuntil;
3068 $key->timecreated = time();
3070 // Something long and unique.
3071 $key->value = md5($userid.'_'.time().random_string(40));
3072 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3073 // Must be unique.
3074 $key->value = md5($userid.'_'.time().random_string(40));
3076 $DB->insert_record('user_private_key', $key);
3077 return $key->value;
3081 * Delete the user's new private user access keys for a particular script.
3083 * @param string $script unique target identifier
3084 * @param int $userid
3085 * @return void
3087 function delete_user_key($script, $userid) {
3088 global $DB;
3089 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3093 * Gets a private user access key (and creates one if one doesn't exist).
3095 * @param string $script unique target identifier
3096 * @param int $userid
3097 * @param int $instance optional instance id
3098 * @param string $iprestriction optional ip restricted access
3099 * @param timestamp $validuntil key valid only until given data
3100 * @return string access key value
3102 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3103 global $DB;
3105 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3106 'instance' => $instance, 'iprestriction' => $iprestriction,
3107 'validuntil' => $validuntil))) {
3108 return $key->value;
3109 } else {
3110 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3116 * Modify the user table by setting the currently logged in user's last login to now.
3118 * @return bool Always returns true
3120 function update_user_login_times() {
3121 global $USER, $DB;
3123 if (isguestuser()) {
3124 // Do not update guest access times/ips for performance.
3125 return true;
3128 $now = time();
3130 $user = new stdClass();
3131 $user->id = $USER->id;
3133 // Make sure all users that logged in have some firstaccess.
3134 if ($USER->firstaccess == 0) {
3135 $USER->firstaccess = $user->firstaccess = $now;
3138 // Store the previous current as lastlogin.
3139 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3141 $USER->currentlogin = $user->currentlogin = $now;
3143 // Function user_accesstime_log() may not update immediately, better do it here.
3144 $USER->lastaccess = $user->lastaccess = $now;
3145 $USER->lastip = $user->lastip = getremoteaddr();
3147 // Note: do not call user_update_user() here because this is part of the login process,
3148 // the login event means that these fields were updated.
3149 $DB->update_record('user', $user);
3150 return true;
3154 * Determines if a user has completed setting up their account.
3156 * The lax mode (with $strict = false) has been introduced for special cases
3157 * only where we want to skip certain checks intentionally. This is valid in
3158 * certain mnet or ajax scenarios when the user cannot / should not be
3159 * redirected to edit their profile. In most cases, you should perform the
3160 * strict check.
3162 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3163 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3164 * @return bool
3166 function user_not_fully_set_up($user, $strict = true) {
3167 global $CFG;
3168 require_once($CFG->dirroot.'/user/profile/lib.php');
3170 if (isguestuser($user)) {
3171 return false;
3174 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3175 return true;
3178 if ($strict) {
3179 if (empty($user->id)) {
3180 // Strict mode can be used with existing accounts only.
3181 return true;
3183 if (!profile_has_required_custom_fields_set($user->id)) {
3184 return true;
3188 return false;
3192 * Check whether the user has exceeded the bounce threshold
3194 * @param stdClass $user A {@link $USER} object
3195 * @return bool true => User has exceeded bounce threshold
3197 function over_bounce_threshold($user) {
3198 global $CFG, $DB;
3200 if (empty($CFG->handlebounces)) {
3201 return false;
3204 if (empty($user->id)) {
3205 // No real (DB) user, nothing to do here.
3206 return false;
3209 // Set sensible defaults.
3210 if (empty($CFG->minbounces)) {
3211 $CFG->minbounces = 10;
3213 if (empty($CFG->bounceratio)) {
3214 $CFG->bounceratio = .20;
3216 $bouncecount = 0;
3217 $sendcount = 0;
3218 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3219 $bouncecount = $bounce->value;
3221 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3222 $sendcount = $send->value;
3224 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3228 * Used to increment or reset email sent count
3230 * @param stdClass $user object containing an id
3231 * @param bool $reset will reset the count to 0
3232 * @return void
3234 function set_send_count($user, $reset=false) {
3235 global $DB;
3237 if (empty($user->id)) {
3238 // No real (DB) user, nothing to do here.
3239 return;
3242 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3243 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3244 $DB->update_record('user_preferences', $pref);
3245 } else if (!empty($reset)) {
3246 // If it's not there and we're resetting, don't bother. Make a new one.
3247 $pref = new stdClass();
3248 $pref->name = 'email_send_count';
3249 $pref->value = 1;
3250 $pref->userid = $user->id;
3251 $DB->insert_record('user_preferences', $pref, false);
3256 * Increment or reset user's email bounce count
3258 * @param stdClass $user object containing an id
3259 * @param bool $reset will reset the count to 0
3261 function set_bounce_count($user, $reset=false) {
3262 global $DB;
3264 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3265 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3266 $DB->update_record('user_preferences', $pref);
3267 } else if (!empty($reset)) {
3268 // If it's not there and we're resetting, don't bother. Make a new one.
3269 $pref = new stdClass();
3270 $pref->name = 'email_bounce_count';
3271 $pref->value = 1;
3272 $pref->userid = $user->id;
3273 $DB->insert_record('user_preferences', $pref, false);
3278 * Determines if the logged in user is currently moving an activity
3280 * @param int $courseid The id of the course being tested
3281 * @return bool
3283 function ismoving($courseid) {
3284 global $USER;
3286 if (!empty($USER->activitycopy)) {
3287 return ($USER->activitycopycourse == $courseid);
3289 return false;
3293 * Returns a persons full name
3295 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3296 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3297 * specify one.
3299 * @param stdClass $user A {@link $USER} object to get full name of.
3300 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3301 * @return string
3303 function fullname($user, $override=false) {
3304 global $CFG, $SESSION;
3306 if (!isset($user->firstname) and !isset($user->lastname)) {
3307 return '';
3310 // Get all of the name fields.
3311 $allnames = get_all_user_name_fields();
3312 if ($CFG->debugdeveloper) {
3313 foreach ($allnames as $allname) {
3314 if (!property_exists($user, $allname)) {
3315 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3316 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3317 // Message has been sent, no point in sending the message multiple times.
3318 break;
3323 if (!$override) {
3324 if (!empty($CFG->forcefirstname)) {
3325 $user->firstname = $CFG->forcefirstname;
3327 if (!empty($CFG->forcelastname)) {
3328 $user->lastname = $CFG->forcelastname;
3332 if (!empty($SESSION->fullnamedisplay)) {
3333 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3336 $template = null;
3337 // If the fullnamedisplay setting is available, set the template to that.
3338 if (isset($CFG->fullnamedisplay)) {
3339 $template = $CFG->fullnamedisplay;
3341 // If the template is empty, or set to language, return the language string.
3342 if ((empty($template) || $template == 'language') && !$override) {
3343 return get_string('fullnamedisplay', null, $user);
3346 // Check to see if we are displaying according to the alternative full name format.
3347 if ($override) {
3348 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3349 // Default to show just the user names according to the fullnamedisplay string.
3350 return get_string('fullnamedisplay', null, $user);
3351 } else {
3352 // If the override is true, then change the template to use the complete name.
3353 $template = $CFG->alternativefullnameformat;
3357 $requirednames = array();
3358 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3359 foreach ($allnames as $allname) {
3360 if (strpos($template, $allname) !== false) {
3361 $requirednames[] = $allname;
3365 $displayname = $template;
3366 // Switch in the actual data into the template.
3367 foreach ($requirednames as $altname) {
3368 if (isset($user->$altname)) {
3369 // Using empty() on the below if statement causes breakages.
3370 if ((string)$user->$altname == '') {
3371 $displayname = str_replace($altname, 'EMPTY', $displayname);
3372 } else {
3373 $displayname = str_replace($altname, $user->$altname, $displayname);
3375 } else {
3376 $displayname = str_replace($altname, 'EMPTY', $displayname);
3379 // Tidy up any misc. characters (Not perfect, but gets most characters).
3380 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3381 // katakana and parenthesis.
3382 $patterns = array();
3383 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3384 // filled in by a user.
3385 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3386 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3387 // This regular expression is to remove any double spaces in the display name.
3388 $patterns[] = '/\s{2,}/u';
3389 foreach ($patterns as $pattern) {
3390 $displayname = preg_replace($pattern, ' ', $displayname);
3393 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3394 $displayname = trim($displayname);
3395 if (empty($displayname)) {
3396 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3397 // people in general feel is a good setting to fall back on.
3398 $displayname = $user->firstname;
3400 return $displayname;
3404 * A centralised location for the all name fields. Returns an array / sql string snippet.
3406 * @param bool $returnsql True for an sql select field snippet.
3407 * @param string $tableprefix table query prefix to use in front of each field.
3408 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3409 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3410 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3411 * @return array|string All name fields.
3413 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3414 // This array is provided in this order because when called by fullname() (above) if firstname is before
3415 // firstnamephonetic str_replace() will change the wrong placeholder.
3416 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3417 'lastnamephonetic' => 'lastnamephonetic',
3418 'middlename' => 'middlename',
3419 'alternatename' => 'alternatename',
3420 'firstname' => 'firstname',
3421 'lastname' => 'lastname');
3423 // Let's add a prefix to the array of user name fields if provided.
3424 if ($prefix) {
3425 foreach ($alternatenames as $key => $altname) {
3426 $alternatenames[$key] = $prefix . $altname;
3430 // If we want the end result to have firstname and lastname at the front / top of the result.
3431 if ($order) {
3432 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3433 for ($i = 0; $i < 2; $i++) {
3434 // Get the last element.
3435 $lastelement = end($alternatenames);
3436 // Remove it from the array.
3437 unset($alternatenames[$lastelement]);
3438 // Put the element back on the top of the array.
3439 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3443 // Create an sql field snippet if requested.
3444 if ($returnsql) {
3445 if ($tableprefix) {
3446 if ($fieldprefix) {
3447 foreach ($alternatenames as $key => $altname) {
3448 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3450 } else {
3451 foreach ($alternatenames as $key => $altname) {
3452 $alternatenames[$key] = $tableprefix . '.' . $altname;
3456 $alternatenames = implode(',', $alternatenames);
3458 return $alternatenames;
3462 * Reduces lines of duplicated code for getting user name fields.
3464 * See also {@link user_picture::unalias()}
3466 * @param object $addtoobject Object to add user name fields to.
3467 * @param object $secondobject Object that contains user name field information.
3468 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3469 * @param array $additionalfields Additional fields to be matched with data in the second object.
3470 * The key can be set to the user table field name.
3471 * @return object User name fields.
3473 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3474 $fields = get_all_user_name_fields(false, null, $prefix);
3475 if ($additionalfields) {
3476 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3477 // the key is a number and then sets the key to the array value.
3478 foreach ($additionalfields as $key => $value) {
3479 if (is_numeric($key)) {
3480 $additionalfields[$value] = $prefix . $value;
3481 unset($additionalfields[$key]);
3482 } else {
3483 $additionalfields[$key] = $prefix . $value;
3486 $fields = array_merge($fields, $additionalfields);
3488 foreach ($fields as $key => $field) {
3489 // Important that we have all of the user name fields present in the object that we are sending back.
3490 $addtoobject->$key = '';
3491 if (isset($secondobject->$field)) {
3492 $addtoobject->$key = $secondobject->$field;
3495 return $addtoobject;
3499 * Returns an array of values in order of occurance in a provided string.
3500 * The key in the result is the character postion in the string.
3502 * @param array $values Values to be found in the string format
3503 * @param string $stringformat The string which may contain values being searched for.
3504 * @return array An array of values in order according to placement in the string format.
3506 function order_in_string($values, $stringformat) {
3507 $valuearray = array();
3508 foreach ($values as $value) {
3509 $pattern = "/$value\b/";
3510 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3511 if (preg_match($pattern, $stringformat)) {
3512 $replacement = "thing";
3513 // Replace the value with something more unique to ensure we get the right position when using strpos().
3514 $newformat = preg_replace($pattern, $replacement, $stringformat);
3515 $position = strpos($newformat, $replacement);
3516 $valuearray[$position] = $value;
3519 ksort($valuearray);
3520 return $valuearray;
3524 * Checks if current user is shown any extra fields when listing users.
3526 * @param object $context Context
3527 * @param array $already Array of fields that we're going to show anyway
3528 * so don't bother listing them
3529 * @return array Array of field names from user table, not including anything
3530 * listed in $already
3532 function get_extra_user_fields($context, $already = array()) {
3533 global $CFG;
3535 // Only users with permission get the extra fields.
3536 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3537 return array();
3540 // Split showuseridentity on comma.
3541 if (empty($CFG->showuseridentity)) {
3542 // Explode gives wrong result with empty string.
3543 $extra = array();
3544 } else {
3545 $extra = explode(',', $CFG->showuseridentity);
3547 $renumber = false;
3548 foreach ($extra as $key => $field) {
3549 if (in_array($field, $already)) {
3550 unset($extra[$key]);
3551 $renumber = true;
3554 if ($renumber) {
3555 // For consistency, if entries are removed from array, renumber it
3556 // so they are numbered as you would expect.
3557 $extra = array_merge($extra);
3559 return $extra;
3563 * If the current user is to be shown extra user fields when listing or
3564 * selecting users, returns a string suitable for including in an SQL select
3565 * clause to retrieve those fields.
3567 * @param context $context Context
3568 * @param string $alias Alias of user table, e.g. 'u' (default none)
3569 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3570 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3571 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3573 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3574 $fields = get_extra_user_fields($context, $already);
3575 $result = '';
3576 // Add punctuation for alias.
3577 if ($alias !== '') {
3578 $alias .= '.';
3580 foreach ($fields as $field) {
3581 $result .= ', ' . $alias . $field;
3582 if ($prefix) {
3583 $result .= ' AS ' . $prefix . $field;
3586 return $result;
3590 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3591 * @param string $field Field name, e.g. 'phone1'
3592 * @return string Text description taken from language file, e.g. 'Phone number'
3594 function get_user_field_name($field) {
3595 // Some fields have language strings which are not the same as field name.
3596 switch ($field) {
3597 case 'url' : {
3598 return get_string('webpage');
3600 case 'icq' : {
3601 return get_string('icqnumber');
3603 case 'skype' : {
3604 return get_string('skypeid');
3606 case 'aim' : {
3607 return get_string('aimid');
3609 case 'yahoo' : {
3610 return get_string('yahooid');
3612 case 'msn' : {
3613 return get_string('msnid');
3616 // Otherwise just use the same lang string.
3617 return get_string($field);
3621 * Returns whether a given authentication plugin exists.
3623 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3624 * @return boolean Whether the plugin is available.
3626 function exists_auth_plugin($auth) {
3627 global $CFG;
3629 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3630 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3632 return false;
3636 * Checks if a given plugin is in the list of enabled authentication plugins.
3638 * @param string $auth Authentication plugin.
3639 * @return boolean Whether the plugin is enabled.
3641 function is_enabled_auth($auth) {
3642 if (empty($auth)) {
3643 return false;
3646 $enabled = get_enabled_auth_plugins();
3648 return in_array($auth, $enabled);
3652 * Returns an authentication plugin instance.
3654 * @param string $auth name of authentication plugin
3655 * @return auth_plugin_base An instance of the required authentication plugin.
3657 function get_auth_plugin($auth) {
3658 global $CFG;
3660 // Check the plugin exists first.
3661 if (! exists_auth_plugin($auth)) {
3662 print_error('authpluginnotfound', 'debug', '', $auth);
3665 // Return auth plugin instance.
3666 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3667 $class = "auth_plugin_$auth";
3668 return new $class;
3672 * Returns array of active auth plugins.
3674 * @param bool $fix fix $CFG->auth if needed
3675 * @return array
3677 function get_enabled_auth_plugins($fix=false) {
3678 global $CFG;
3680 $default = array('manual', 'nologin');
3682 if (empty($CFG->auth)) {
3683 $auths = array();
3684 } else {
3685 $auths = explode(',', $CFG->auth);
3688 if ($fix) {
3689 $auths = array_unique($auths);
3690 foreach ($auths as $k => $authname) {
3691 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3692 unset($auths[$k]);
3695 $newconfig = implode(',', $auths);
3696 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3697 set_config('auth', $newconfig);
3701 return (array_merge($default, $auths));
3705 * Returns true if an internal authentication method is being used.
3706 * if method not specified then, global default is assumed
3708 * @param string $auth Form of authentication required
3709 * @return bool
3711 function is_internal_auth($auth) {
3712 // Throws error if bad $auth.
3713 $authplugin = get_auth_plugin($auth);
3714 return $authplugin->is_internal();
3718 * Returns true if the user is a 'restored' one.
3720 * Used in the login process to inform the user and allow him/her to reset the password
3722 * @param string $username username to be checked
3723 * @return bool
3725 function is_restored_user($username) {
3726 global $CFG, $DB;
3728 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3732 * Returns an array of user fields
3734 * @return array User field/column names
3736 function get_user_fieldnames() {
3737 global $DB;
3739 $fieldarray = $DB->get_columns('user');
3740 unset($fieldarray['id']);
3741 $fieldarray = array_keys($fieldarray);
3743 return $fieldarray;
3747 * Creates a bare-bones user record
3749 * @todo Outline auth types and provide code example
3751 * @param string $username New user's username to add to record
3752 * @param string $password New user's password to add to record
3753 * @param string $auth Form of authentication required
3754 * @return stdClass A complete user object
3756 function create_user_record($username, $password, $auth = 'manual') {
3757 global $CFG, $DB;
3758 require_once($CFG->dirroot.'/user/profile/lib.php');
3759 require_once($CFG->dirroot.'/user/lib.php');
3761 // Just in case check text case.
3762 $username = trim(core_text::strtolower($username));
3764 $authplugin = get_auth_plugin($auth);
3765 $customfields = $authplugin->get_custom_user_profile_fields();
3766 $newuser = new stdClass();
3767 if ($newinfo = $authplugin->get_userinfo($username)) {
3768 $newinfo = truncate_userinfo($newinfo);
3769 foreach ($newinfo as $key => $value) {
3770 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3771 $newuser->$key = $value;
3776 if (!empty($newuser->email)) {
3777 if (email_is_not_allowed($newuser->email)) {
3778 unset($newuser->email);
3782 if (!isset($newuser->city)) {
3783 $newuser->city = '';
3786 $newuser->auth = $auth;
3787 $newuser->username = $username;
3789 // Fix for MDL-8480
3790 // user CFG lang for user if $newuser->lang is empty
3791 // or $user->lang is not an installed language.
3792 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3793 $newuser->lang = $CFG->lang;
3795 $newuser->confirmed = 1;
3796 $newuser->lastip = getremoteaddr();
3797 $newuser->timecreated = time();
3798 $newuser->timemodified = $newuser->timecreated;
3799 $newuser->mnethostid = $CFG->mnet_localhost_id;
3801 $newuser->id = user_create_user($newuser, false, false);
3803 // Save user profile data.
3804 profile_save_data($newuser);
3806 $user = get_complete_user_data('id', $newuser->id);
3807 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3808 set_user_preference('auth_forcepasswordchange', 1, $user);
3810 // Set the password.
3811 update_internal_user_password($user, $password);
3813 // Trigger event.
3814 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3816 return $user;
3820 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3822 * @param string $username user's username to update the record
3823 * @return stdClass A complete user object
3825 function update_user_record($username) {
3826 global $DB, $CFG;
3827 // Just in case check text case.
3828 $username = trim(core_text::strtolower($username));
3830 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3831 return update_user_record_by_id($oldinfo->id);
3835 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3837 * @param int $id user id
3838 * @return stdClass A complete user object
3840 function update_user_record_by_id($id) {
3841 global $DB, $CFG;
3842 require_once($CFG->dirroot."/user/profile/lib.php");
3843 require_once($CFG->dirroot.'/user/lib.php');
3845 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3846 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3848 $newuser = array();
3849 $userauth = get_auth_plugin($oldinfo->auth);
3851 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3852 $newinfo = truncate_userinfo($newinfo);
3853 $customfields = $userauth->get_custom_user_profile_fields();
3855 foreach ($newinfo as $key => $value) {
3856 $iscustom = in_array($key, $customfields);
3857 if (!$iscustom) {
3858 $key = strtolower($key);
3860 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3861 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3862 // Unknown or must not be changed.
3863 continue;
3865 $confval = $userauth->config->{'field_updatelocal_' . $key};
3866 $lockval = $userauth->config->{'field_lock_' . $key};
3867 if (empty($confval) || empty($lockval)) {
3868 continue;
3870 if ($confval === 'onlogin') {
3871 // MDL-4207 Don't overwrite modified user profile values with
3872 // empty LDAP values when 'unlocked if empty' is set. The purpose
3873 // of the setting 'unlocked if empty' is to allow the user to fill
3874 // in a value for the selected field _if LDAP is giving
3875 // nothing_ for this field. Thus it makes sense to let this value
3876 // stand in until LDAP is giving a value for this field.
3877 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3878 if ($iscustom || (in_array($key, $userauth->userfields) &&
3879 ((string)$oldinfo->$key !== (string)$value))) {
3880 $newuser[$key] = (string)$value;
3885 if ($newuser) {
3886 $newuser['id'] = $oldinfo->id;
3887 $newuser['timemodified'] = time();
3888 user_update_user((object) $newuser, false, false);
3890 // Save user profile data.
3891 profile_save_data((object) $newuser);
3893 // Trigger event.
3894 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
3898 return get_complete_user_data('id', $oldinfo->id);
3902 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
3904 * @param array $info Array of user properties to truncate if needed
3905 * @return array The now truncated information that was passed in
3907 function truncate_userinfo(array $info) {
3908 // Define the limits.
3909 $limit = array(
3910 'username' => 100,
3911 'idnumber' => 255,
3912 'firstname' => 100,
3913 'lastname' => 100,
3914 'email' => 100,
3915 'icq' => 15,
3916 'phone1' => 20,
3917 'phone2' => 20,
3918 'institution' => 255,
3919 'department' => 255,
3920 'address' => 255,
3921 'city' => 120,
3922 'country' => 2,
3923 'url' => 255,
3926 // Apply where needed.
3927 foreach (array_keys($info) as $key) {
3928 if (!empty($limit[$key])) {
3929 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
3933 return $info;
3937 * Marks user deleted in internal user database and notifies the auth plugin.
3938 * Also unenrols user from all roles and does other cleanup.
3940 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3942 * @param stdClass $user full user object before delete
3943 * @return boolean success
3944 * @throws coding_exception if invalid $user parameter detected
3946 function delete_user(stdClass $user) {
3947 global $CFG, $DB;
3948 require_once($CFG->libdir.'/grouplib.php');
3949 require_once($CFG->libdir.'/gradelib.php');
3950 require_once($CFG->dirroot.'/message/lib.php');
3951 require_once($CFG->dirroot.'/user/lib.php');
3953 // Make sure nobody sends bogus record type as parameter.
3954 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
3955 throw new coding_exception('Invalid $user parameter in delete_user() detected');
3958 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
3959 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
3960 debugging('Attempt to delete unknown user account.');
3961 return false;
3964 // There must be always exactly one guest record, originally the guest account was identified by username only,
3965 // now we use $CFG->siteguest for performance reasons.
3966 if ($user->username === 'guest' or isguestuser($user)) {
3967 debugging('Guest user account can not be deleted.');
3968 return false;
3971 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
3972 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
3973 if ($user->auth === 'manual' and is_siteadmin($user)) {
3974 debugging('Local administrator accounts can not be deleted.');
3975 return false;
3978 // Allow plugins to use this user object before we completely delete it.
3979 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
3980 foreach ($pluginsfunction as $plugintype => $plugins) {
3981 foreach ($plugins as $pluginfunction) {
3982 $pluginfunction($user);
3987 // Keep user record before updating it, as we have to pass this to user_deleted event.
3988 $olduser = clone $user;
3990 // Keep a copy of user context, we need it for event.
3991 $usercontext = context_user::instance($user->id);
3993 // Delete all grades - backup is kept in grade_grades_history table.
3994 grade_user_delete($user->id);
3996 // Move unread messages from this user to read.
3997 message_move_userfrom_unread2read($user->id);
3999 // TODO: remove from cohorts using standard API here.
4001 // Remove user tags.
4002 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4004 // Unconditionally unenrol from all courses.
4005 enrol_user_delete($user);
4007 // Unenrol from all roles in all contexts.
4008 // This might be slow but it is really needed - modules might do some extra cleanup!
4009 role_unassign_all(array('userid' => $user->id));
4011 // Now do a brute force cleanup.
4013 // Remove from all cohorts.
4014 $DB->delete_records('cohort_members', array('userid' => $user->id));
4016 // Remove from all groups.
4017 $DB->delete_records('groups_members', array('userid' => $user->id));
4019 // Brute force unenrol from all courses.
4020 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4022 // Purge user preferences.
4023 $DB->delete_records('user_preferences', array('userid' => $user->id));
4025 // Purge user extra profile info.
4026 $DB->delete_records('user_info_data', array('userid' => $user->id));
4028 // Purge log of previous password hashes.
4029 $DB->delete_records('user_password_history', array('userid' => $user->id));
4031 // Last course access not necessary either.
4032 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4033 // Remove all user tokens.
4034 $DB->delete_records('external_tokens', array('userid' => $user->id));
4036 // Unauthorise the user for all services.
4037 $DB->delete_records('external_services_users', array('userid' => $user->id));
4039 // Remove users private keys.
4040 $DB->delete_records('user_private_key', array('userid' => $user->id));
4042 // Remove users customised pages.
4043 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4045 // Force logout - may fail if file based sessions used, sorry.
4046 \core\session\manager::kill_user_sessions($user->id);
4048 // Generate username from email address, or a fake email.
4049 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4050 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
4052 // Workaround for bulk deletes of users with the same email address.
4053 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4054 $delname++;
4057 // Mark internal user record as "deleted".
4058 $updateuser = new stdClass();
4059 $updateuser->id = $user->id;
4060 $updateuser->deleted = 1;
4061 $updateuser->username = $delname; // Remember it just in case.
4062 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4063 $updateuser->idnumber = ''; // Clear this field to free it up.
4064 $updateuser->picture = 0;
4065 $updateuser->timemodified = time();
4067 // Don't trigger update event, as user is being deleted.
4068 user_update_user($updateuser, false, false);
4070 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4071 context_helper::delete_instance(CONTEXT_USER, $user->id);
4073 // Any plugin that needs to cleanup should register this event.
4074 // Trigger event.
4075 $event = \core\event\user_deleted::create(
4076 array(
4077 'objectid' => $user->id,
4078 'relateduserid' => $user->id,
4079 'context' => $usercontext,
4080 'other' => array(
4081 'username' => $user->username,
4082 'email' => $user->email,
4083 'idnumber' => $user->idnumber,
4084 'picture' => $user->picture,
4085 'mnethostid' => $user->mnethostid
4089 $event->add_record_snapshot('user', $olduser);
4090 $event->trigger();
4092 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4093 // should know about this updated property persisted to the user's table.
4094 $user->timemodified = $updateuser->timemodified;
4096 // Notify auth plugin - do not block the delete even when plugin fails.
4097 $authplugin = get_auth_plugin($user->auth);
4098 $authplugin->user_delete($user);
4100 return true;
4104 * Retrieve the guest user object.
4106 * @return stdClass A {@link $USER} object
4108 function guest_user() {
4109 global $CFG, $DB;
4111 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4112 $newuser->confirmed = 1;
4113 $newuser->lang = $CFG->lang;
4114 $newuser->lastip = getremoteaddr();
4117 return $newuser;
4121 * Authenticates a user against the chosen authentication mechanism
4123 * Given a username and password, this function looks them
4124 * up using the currently selected authentication mechanism,
4125 * and if the authentication is successful, it returns a
4126 * valid $user object from the 'user' table.
4128 * Uses auth_ functions from the currently active auth module
4130 * After authenticate_user_login() returns success, you will need to
4131 * log that the user has logged in, and call complete_user_login() to set
4132 * the session up.
4134 * Note: this function works only with non-mnet accounts!
4136 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4137 * @param string $password User's password
4138 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4139 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4140 * @return stdClass|false A {@link $USER} object or false if error
4142 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4143 global $CFG, $DB;
4144 require_once("$CFG->libdir/authlib.php");
4146 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4147 // we have found the user
4149 } else if (!empty($CFG->authloginviaemail)) {
4150 if ($email = clean_param($username, PARAM_EMAIL)) {
4151 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4152 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4153 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4154 if (count($users) === 1) {
4155 // Use email for login only if unique.
4156 $user = reset($users);
4157 $user = get_complete_user_data('id', $user->id);
4158 $username = $user->username;
4160 unset($users);
4164 $authsenabled = get_enabled_auth_plugins();
4166 if ($user) {
4167 // Use manual if auth not set.
4168 $auth = empty($user->auth) ? 'manual' : $user->auth;
4169 if (!empty($user->suspended)) {
4170 $failurereason = AUTH_LOGIN_SUSPENDED;
4172 // Trigger login failed event.
4173 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4174 'other' => array('username' => $username, 'reason' => $failurereason)));
4175 $event->trigger();
4176 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4177 return false;
4179 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4180 // Legacy way to suspend user.
4181 $failurereason = AUTH_LOGIN_SUSPENDED;
4183 // Trigger login failed event.
4184 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4185 'other' => array('username' => $username, 'reason' => $failurereason)));
4186 $event->trigger();
4187 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4188 return false;
4190 $auths = array($auth);
4192 } else {
4193 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4194 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4195 $failurereason = AUTH_LOGIN_NOUSER;
4197 // Trigger login failed event.
4198 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4199 'reason' => $failurereason)));
4200 $event->trigger();
4201 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4202 return false;
4205 // User does not exist.
4206 $auths = $authsenabled;
4207 $user = new stdClass();
4208 $user->id = 0;
4211 if ($ignorelockout) {
4212 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4213 // or this function is called from a SSO script.
4214 } else if ($user->id) {
4215 // Verify login lockout after other ways that may prevent user login.
4216 if (login_is_lockedout($user)) {
4217 $failurereason = AUTH_LOGIN_LOCKOUT;
4219 // Trigger login failed event.
4220 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4221 'other' => array('username' => $username, 'reason' => $failurereason)));
4222 $event->trigger();
4224 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4225 return false;
4227 } else {
4228 // We can not lockout non-existing accounts.
4231 foreach ($auths as $auth) {
4232 $authplugin = get_auth_plugin($auth);
4234 // On auth fail fall through to the next plugin.
4235 if (!$authplugin->user_login($username, $password)) {
4236 continue;
4239 // Successful authentication.
4240 if ($user->id) {
4241 // User already exists in database.
4242 if (empty($user->auth)) {
4243 // For some reason auth isn't set yet.
4244 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4245 $user->auth = $auth;
4248 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4249 // the current hash algorithm while we have access to the user's password.
4250 update_internal_user_password($user, $password);
4252 if ($authplugin->is_synchronised_with_external()) {
4253 // Update user record from external DB.
4254 $user = update_user_record_by_id($user->id);
4256 } else {
4257 // The user is authenticated but user creation may be disabled.
4258 if (!empty($CFG->authpreventaccountcreation)) {
4259 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4261 // Trigger login failed event.
4262 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4263 'reason' => $failurereason)));
4264 $event->trigger();
4266 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4267 $_SERVER['HTTP_USER_AGENT']);
4268 return false;
4269 } else {
4270 $user = create_user_record($username, $password, $auth);
4274 $authplugin->sync_roles($user);
4276 foreach ($authsenabled as $hau) {
4277 $hauth = get_auth_plugin($hau);
4278 $hauth->user_authenticated_hook($user, $username, $password);
4281 if (empty($user->id)) {
4282 $failurereason = AUTH_LOGIN_NOUSER;
4283 // Trigger login failed event.
4284 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4285 'reason' => $failurereason)));
4286 $event->trigger();
4287 return false;
4290 if (!empty($user->suspended)) {
4291 // Just in case some auth plugin suspended account.
4292 $failurereason = AUTH_LOGIN_SUSPENDED;
4293 // Trigger login failed event.
4294 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4295 'other' => array('username' => $username, 'reason' => $failurereason)));
4296 $event->trigger();
4297 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4298 return false;
4301 login_attempt_valid($user);
4302 $failurereason = AUTH_LOGIN_OK;
4303 return $user;
4306 // Failed if all the plugins have failed.
4307 if (debugging('', DEBUG_ALL)) {
4308 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4311 if ($user->id) {
4312 login_attempt_failed($user);
4313 $failurereason = AUTH_LOGIN_FAILED;
4314 // Trigger login failed event.
4315 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4316 'other' => array('username' => $username, 'reason' => $failurereason)));
4317 $event->trigger();
4318 } else {
4319 $failurereason = AUTH_LOGIN_NOUSER;
4320 // Trigger login failed event.
4321 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4322 'reason' => $failurereason)));
4323 $event->trigger();
4326 return false;
4330 * Call to complete the user login process after authenticate_user_login()
4331 * has succeeded. It will setup the $USER variable and other required bits
4332 * and pieces.
4334 * NOTE:
4335 * - It will NOT log anything -- up to the caller to decide what to log.
4336 * - this function does not set any cookies any more!
4338 * @param stdClass $user
4339 * @return stdClass A {@link $USER} object - BC only, do not use
4341 function complete_user_login($user) {
4342 global $CFG, $USER, $SESSION;
4344 \core\session\manager::login_user($user);
4346 // Reload preferences from DB.
4347 unset($USER->preference);
4348 check_user_preferences_loaded($USER);
4350 // Update login times.
4351 update_user_login_times();
4353 // Extra session prefs init.
4354 set_login_session_preferences();
4356 // Trigger login event.
4357 $event = \core\event\user_loggedin::create(
4358 array(
4359 'userid' => $USER->id,
4360 'objectid' => $USER->id,
4361 'other' => array('username' => $USER->username),
4364 $event->trigger();
4366 if (isguestuser()) {
4367 // No need to continue when user is THE guest.
4368 return $USER;
4371 if (CLI_SCRIPT) {
4372 // We can redirect to password change URL only in browser.
4373 return $USER;
4376 // Select password change url.
4377 $userauth = get_auth_plugin($USER->auth);
4379 // Check whether the user should be changing password.
4380 if (get_user_preferences('auth_forcepasswordchange', false)) {
4381 if ($userauth->can_change_password()) {
4382 if ($changeurl = $userauth->change_password_url()) {
4383 redirect($changeurl);
4384 } else {
4385 require_once($CFG->dirroot . '/login/lib.php');
4386 $SESSION->wantsurl = core_login_get_return_url();
4387 redirect($CFG->httpswwwroot.'/login/change_password.php');
4389 } else {
4390 print_error('nopasswordchangeforced', 'auth');
4393 return $USER;
4397 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4399 * @param string $password String to check.
4400 * @return boolean True if the $password matches the format of an md5 sum.
4402 function password_is_legacy_hash($password) {
4403 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4407 * Compare password against hash stored in user object to determine if it is valid.
4409 * If necessary it also updates the stored hash to the current format.
4411 * @param stdClass $user (Password property may be updated).
4412 * @param string $password Plain text password.
4413 * @return bool True if password is valid.
4415 function validate_internal_user_password($user, $password) {
4416 global $CFG;
4417 require_once($CFG->libdir.'/password_compat/lib/password.php');
4419 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4420 // Internal password is not used at all, it can not validate.
4421 return false;
4424 // If hash isn't a legacy (md5) hash, validate using the library function.
4425 if (!password_is_legacy_hash($user->password)) {
4426 return password_verify($password, $user->password);
4429 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4430 // is valid we can then update it to the new algorithm.
4432 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4433 $validated = false;
4435 if ($user->password === md5($password.$sitesalt)
4436 or $user->password === md5($password)
4437 or $user->password === md5(addslashes($password).$sitesalt)
4438 or $user->password === md5(addslashes($password))) {
4439 // Note: we are intentionally using the addslashes() here because we
4440 // need to accept old password hashes of passwords with magic quotes.
4441 $validated = true;
4443 } else {
4444 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4445 $alt = 'passwordsaltalt'.$i;
4446 if (!empty($CFG->$alt)) {
4447 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4448 $validated = true;
4449 break;
4455 if ($validated) {
4456 // If the password matches the existing md5 hash, update to the
4457 // current hash algorithm while we have access to the user's password.
4458 update_internal_user_password($user, $password);
4461 return $validated;
4465 * Calculate hash for a plain text password.
4467 * @param string $password Plain text password to be hashed.
4468 * @param bool $fasthash If true, use a low cost factor when generating the hash
4469 * This is much faster to generate but makes the hash
4470 * less secure. It is used when lots of hashes need to
4471 * be generated quickly.
4472 * @return string The hashed password.
4474 * @throws moodle_exception If a problem occurs while generating the hash.
4476 function hash_internal_user_password($password, $fasthash = false) {
4477 global $CFG;
4478 require_once($CFG->libdir.'/password_compat/lib/password.php');
4480 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4481 $options = ($fasthash) ? array('cost' => 4) : array();
4483 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4485 if ($generatedhash === false || $generatedhash === null) {
4486 throw new moodle_exception('Failed to generate password hash.');
4489 return $generatedhash;
4493 * Update password hash in user object (if necessary).
4495 * The password is updated if:
4496 * 1. The password has changed (the hash of $user->password is different
4497 * to the hash of $password).
4498 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4499 * md5 algorithm).
4501 * Updating the password will modify the $user object and the database
4502 * record to use the current hashing algorithm.
4503 * It will remove Web Services user tokens too.
4505 * @param stdClass $user User object (password property may be updated).
4506 * @param string $password Plain text password.
4507 * @param bool $fasthash If true, use a low cost factor when generating the hash
4508 * This is much faster to generate but makes the hash
4509 * less secure. It is used when lots of hashes need to
4510 * be generated quickly.
4511 * @return bool Always returns true.
4513 function update_internal_user_password($user, $password, $fasthash = false) {
4514 global $CFG, $DB;
4515 require_once($CFG->libdir.'/password_compat/lib/password.php');
4517 // Figure out what the hashed password should be.
4518 if (!isset($user->auth)) {
4519 debugging('User record in update_internal_user_password() must include field auth',
4520 DEBUG_DEVELOPER);
4521 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4523 $authplugin = get_auth_plugin($user->auth);
4524 if ($authplugin->prevent_local_passwords()) {
4525 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4526 } else {
4527 $hashedpassword = hash_internal_user_password($password, $fasthash);
4530 $algorithmchanged = false;
4532 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4533 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4534 $passwordchanged = ($user->password !== $hashedpassword);
4536 } else if (isset($user->password)) {
4537 // If verification fails then it means the password has changed.
4538 $passwordchanged = !password_verify($password, $user->password);
4539 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4540 } else {
4541 // While creating new user, password in unset in $user object, to avoid
4542 // saving it with user_create()
4543 $passwordchanged = true;
4546 if ($passwordchanged || $algorithmchanged) {
4547 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4548 $user->password = $hashedpassword;
4550 // Trigger event.
4551 $user = $DB->get_record('user', array('id' => $user->id));
4552 \core\event\user_password_updated::create_from_user($user)->trigger();
4554 // Remove WS user tokens.
4555 require_once($CFG->dirroot.'/webservice/lib.php');
4556 webservice::delete_user_ws_tokens($user->id);
4559 return true;
4563 * Get a complete user record, which includes all the info in the user record.
4565 * Intended for setting as $USER session variable
4567 * @param string $field The user field to be checked for a given value.
4568 * @param string $value The value to match for $field.
4569 * @param int $mnethostid
4570 * @return mixed False, or A {@link $USER} object.
4572 function get_complete_user_data($field, $value, $mnethostid = null) {
4573 global $CFG, $DB;
4575 if (!$field || !$value) {
4576 return false;
4579 // Build the WHERE clause for an SQL query.
4580 $params = array('fieldval' => $value);
4581 $constraints = "$field = :fieldval AND deleted <> 1";
4583 // If we are loading user data based on anything other than id,
4584 // we must also restrict our search based on mnet host.
4585 if ($field != 'id') {
4586 if (empty($mnethostid)) {
4587 // If empty, we restrict to local users.
4588 $mnethostid = $CFG->mnet_localhost_id;
4591 if (!empty($mnethostid)) {
4592 $params['mnethostid'] = $mnethostid;
4593 $constraints .= " AND mnethostid = :mnethostid";
4596 // Get all the basic user data.
4597 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4598 return false;
4601 // Get various settings and preferences.
4603 // Preload preference cache.
4604 check_user_preferences_loaded($user);
4606 // Load course enrolment related stuff.
4607 $user->lastcourseaccess = array(); // During last session.
4608 $user->currentcourseaccess = array(); // During current session.
4609 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4610 foreach ($lastaccesses as $lastaccess) {
4611 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4615 $sql = "SELECT g.id, g.courseid
4616 FROM {groups} g, {groups_members} gm
4617 WHERE gm.groupid=g.id AND gm.userid=?";
4619 // This is a special hack to speedup calendar display.
4620 $user->groupmember = array();
4621 if (!isguestuser($user)) {
4622 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4623 foreach ($groups as $group) {
4624 if (!array_key_exists($group->courseid, $user->groupmember)) {
4625 $user->groupmember[$group->courseid] = array();
4627 $user->groupmember[$group->courseid][$group->id] = $group->id;
4632 // Add the custom profile fields to the user record.
4633 $user->profile = array();
4634 if (!isguestuser($user)) {
4635 require_once($CFG->dirroot.'/user/profile/lib.php');
4636 profile_load_custom_fields($user);
4639 // Rewrite some variables if necessary.
4640 if (!empty($user->description)) {
4641 // No need to cart all of it around.
4642 $user->description = true;
4644 if (isguestuser($user)) {
4645 // Guest language always same as site.
4646 $user->lang = $CFG->lang;
4647 // Name always in current language.
4648 $user->firstname = get_string('guestuser');
4649 $user->lastname = ' ';
4652 return $user;
4656 * Validate a password against the configured password policy
4658 * @param string $password the password to be checked against the password policy
4659 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4660 * @return bool true if the password is valid according to the policy. false otherwise.
4662 function check_password_policy($password, &$errmsg) {
4663 global $CFG;
4665 if (empty($CFG->passwordpolicy)) {
4666 return true;
4669 $errmsg = '';
4670 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4671 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4674 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4675 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4678 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4679 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4682 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4683 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4686 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4687 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4689 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4690 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4693 if ($errmsg == '') {
4694 return true;
4695 } else {
4696 return false;
4702 * When logging in, this function is run to set certain preferences for the current SESSION.
4704 function set_login_session_preferences() {
4705 global $SESSION;
4707 $SESSION->justloggedin = true;
4709 unset($SESSION->lang);
4710 unset($SESSION->forcelang);
4711 unset($SESSION->load_navigation_admin);
4716 * Delete a course, including all related data from the database, and any associated files.
4718 * @param mixed $courseorid The id of the course or course object to delete.
4719 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4720 * @return bool true if all the removals succeeded. false if there were any failures. If this
4721 * method returns false, some of the removals will probably have succeeded, and others
4722 * failed, but you have no way of knowing which.
4724 function delete_course($courseorid, $showfeedback = true) {
4725 global $DB;
4727 if (is_object($courseorid)) {
4728 $courseid = $courseorid->id;
4729 $course = $courseorid;
4730 } else {
4731 $courseid = $courseorid;
4732 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4733 return false;
4736 $context = context_course::instance($courseid);
4738 // Frontpage course can not be deleted!!
4739 if ($courseid == SITEID) {
4740 return false;
4743 // Allow plugins to use this course before we completely delete it.
4744 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
4745 foreach ($pluginsfunction as $plugintype => $plugins) {
4746 foreach ($plugins as $pluginfunction) {
4747 $pluginfunction($course);
4752 // Make the course completely empty.
4753 remove_course_contents($courseid, $showfeedback);
4755 // Delete the course and related context instance.
4756 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4758 $DB->delete_records("course", array("id" => $courseid));
4759 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4761 // Reset all course related caches here.
4762 if (class_exists('format_base', false)) {
4763 format_base::reset_course_cache($courseid);
4766 // Trigger a course deleted event.
4767 $event = \core\event\course_deleted::create(array(
4768 'objectid' => $course->id,
4769 'context' => $context,
4770 'other' => array(
4771 'shortname' => $course->shortname,
4772 'fullname' => $course->fullname,
4773 'idnumber' => $course->idnumber
4776 $event->add_record_snapshot('course', $course);
4777 $event->trigger();
4779 return true;
4783 * Clear a course out completely, deleting all content but don't delete the course itself.
4785 * This function does not verify any permissions.
4787 * Please note this function also deletes all user enrolments,
4788 * enrolment instances and role assignments by default.
4790 * $options:
4791 * - 'keep_roles_and_enrolments' - false by default
4792 * - 'keep_groups_and_groupings' - false by default
4794 * @param int $courseid The id of the course that is being deleted
4795 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4796 * @param array $options extra options
4797 * @return bool true if all the removals succeeded. false if there were any failures. If this
4798 * method returns false, some of the removals will probably have succeeded, and others
4799 * failed, but you have no way of knowing which.
4801 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4802 global $CFG, $DB, $OUTPUT;
4804 require_once($CFG->libdir.'/badgeslib.php');
4805 require_once($CFG->libdir.'/completionlib.php');
4806 require_once($CFG->libdir.'/questionlib.php');
4807 require_once($CFG->libdir.'/gradelib.php');
4808 require_once($CFG->dirroot.'/group/lib.php');
4809 require_once($CFG->dirroot.'/comment/lib.php');
4810 require_once($CFG->dirroot.'/rating/lib.php');
4811 require_once($CFG->dirroot.'/notes/lib.php');
4813 // Handle course badges.
4814 badges_handle_course_deletion($courseid);
4816 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4817 $strdeleted = get_string('deleted').' - ';
4819 // Some crazy wishlist of stuff we should skip during purging of course content.
4820 $options = (array)$options;
4822 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
4823 $coursecontext = context_course::instance($courseid);
4824 $fs = get_file_storage();
4826 // Delete course completion information, this has to be done before grades and enrols.
4827 $cc = new completion_info($course);
4828 $cc->clear_criteria();
4829 if ($showfeedback) {
4830 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4833 // Remove all data from gradebook - this needs to be done before course modules
4834 // because while deleting this information, the system may need to reference
4835 // the course modules that own the grades.
4836 remove_course_grades($courseid, $showfeedback);
4837 remove_grade_letters($coursecontext, $showfeedback);
4839 // Delete course blocks in any all child contexts,
4840 // they may depend on modules so delete them first.
4841 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4842 foreach ($childcontexts as $childcontext) {
4843 blocks_delete_all_for_context($childcontext->id);
4845 unset($childcontexts);
4846 blocks_delete_all_for_context($coursecontext->id);
4847 if ($showfeedback) {
4848 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4851 // Delete every instance of every module,
4852 // this has to be done before deleting of course level stuff.
4853 $locations = core_component::get_plugin_list('mod');
4854 foreach ($locations as $modname => $moddir) {
4855 if ($modname === 'NEWMODULE') {
4856 continue;
4858 if ($module = $DB->get_record('modules', array('name' => $modname))) {
4859 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
4860 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
4861 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
4863 if ($instances = $DB->get_records($modname, array('course' => $course->id))) {
4864 foreach ($instances as $instance) {
4865 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
4866 // Delete activity context questions and question categories.
4867 question_delete_activity($cm, $showfeedback);
4869 // Notify the competency subsystem.
4870 \core_competency\api::hook_course_module_deleted($cm);
4872 if (function_exists($moddelete)) {
4873 // This purges all module data in related tables, extra user prefs, settings, etc.
4874 $moddelete($instance->id);
4875 } else {
4876 // NOTE: we should not allow installation of modules with missing delete support!
4877 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
4878 $DB->delete_records($modname, array('id' => $instance->id));
4881 if ($cm) {
4882 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
4883 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4884 $DB->delete_records('course_modules', array('id' => $cm->id));
4888 if (function_exists($moddeletecourse)) {
4889 // Execute ptional course cleanup callback.
4890 $moddeletecourse($course, $showfeedback);
4892 if ($instances and $showfeedback) {
4893 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
4895 } else {
4896 // Ooops, this module is not properly installed, force-delete it in the next block.
4900 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
4902 // Remove all data from availability and completion tables that is associated
4903 // with course-modules belonging to this course. Note this is done even if the
4904 // features are not enabled now, in case they were enabled previously.
4905 $DB->delete_records_select('course_modules_completion',
4906 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4907 array($courseid));
4909 // Remove course-module data.
4910 $cms = $DB->get_records('course_modules', array('course' => $course->id));
4911 foreach ($cms as $cm) {
4912 if ($module = $DB->get_record('modules', array('id' => $cm->module))) {
4913 try {
4914 $DB->delete_records($module->name, array('id' => $cm->instance));
4915 } catch (Exception $e) {
4916 // Ignore weird or missing table problems.
4919 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4920 $DB->delete_records('course_modules', array('id' => $cm->id));
4923 if ($showfeedback) {
4924 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
4927 // Cleanup the rest of plugins.
4928 $cleanuplugintypes = array('report', 'coursereport', 'format');
4929 $callbacks = get_plugins_with_function('delete_course', 'lib.php');
4930 foreach ($cleanuplugintypes as $type) {
4931 if (!empty($callbacks[$type])) {
4932 foreach ($callbacks[$type] as $pluginfunction) {
4933 $pluginfunction($course->id, $showfeedback);
4936 if ($showfeedback) {
4937 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
4941 // Delete questions and question categories.
4942 question_delete_course($course, $showfeedback);
4943 if ($showfeedback) {
4944 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
4947 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
4948 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4949 foreach ($childcontexts as $childcontext) {
4950 $childcontext->delete();
4952 unset($childcontexts);
4954 // Remove all roles and enrolments by default.
4955 if (empty($options['keep_roles_and_enrolments'])) {
4956 // This hack is used in restore when deleting contents of existing course.
4957 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
4958 enrol_course_delete($course);
4959 if ($showfeedback) {
4960 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
4964 // Delete any groups, removing members and grouping/course links first.
4965 if (empty($options['keep_groups_and_groupings'])) {
4966 groups_delete_groupings($course->id, $showfeedback);
4967 groups_delete_groups($course->id, $showfeedback);
4970 // Filters be gone!
4971 filter_delete_all_for_context($coursecontext->id);
4973 // Notes, you shall not pass!
4974 note_delete_all($course->id);
4976 // Die comments!
4977 comment::delete_comments($coursecontext->id);
4979 // Ratings are history too.
4980 $delopt = new stdclass();
4981 $delopt->contextid = $coursecontext->id;
4982 $rm = new rating_manager();
4983 $rm->delete_ratings($delopt);
4985 // Delete course tags.
4986 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
4988 // Notify the competency subsystem.
4989 \core_competency\api::hook_course_deleted($course);
4991 // Delete calendar events.
4992 $DB->delete_records('event', array('courseid' => $course->id));
4993 $fs->delete_area_files($coursecontext->id, 'calendar');
4995 // Delete all related records in other core tables that may have a courseid
4996 // This array stores the tables that need to be cleared, as
4997 // table_name => column_name that contains the course id.
4998 $tablestoclear = array(
4999 'backup_courses' => 'courseid', // Scheduled backup stuff.
5000 'user_lastaccess' => 'courseid', // User access info.
5002 foreach ($tablestoclear as $table => $col) {
5003 $DB->delete_records($table, array($col => $course->id));
5006 // Delete all course backup files.
5007 $fs->delete_area_files($coursecontext->id, 'backup');
5009 // Cleanup course record - remove links to deleted stuff.
5010 $oldcourse = new stdClass();
5011 $oldcourse->id = $course->id;
5012 $oldcourse->summary = '';
5013 $oldcourse->cacherev = 0;
5014 $oldcourse->legacyfiles = 0;
5015 if (!empty($options['keep_groups_and_groupings'])) {
5016 $oldcourse->defaultgroupingid = 0;
5018 $DB->update_record('course', $oldcourse);
5020 // Delete course sections.
5021 $DB->delete_records('course_sections', array('course' => $course->id));
5023 // Delete legacy, section and any other course files.
5024 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5026 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5027 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5028 // Easy, do not delete the context itself...
5029 $coursecontext->delete_content();
5030 } else {
5031 // Hack alert!!!!
5032 // We can not drop all context stuff because it would bork enrolments and roles,
5033 // there might be also files used by enrol plugins...
5036 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5037 // also some non-standard unsupported plugins may try to store something there.
5038 fulldelete($CFG->dataroot.'/'.$course->id);
5040 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5041 $cachemodinfo = cache::make('core', 'coursemodinfo');
5042 $cachemodinfo->delete($courseid);
5044 // Trigger a course content deleted event.
5045 $event = \core\event\course_content_deleted::create(array(
5046 'objectid' => $course->id,
5047 'context' => $coursecontext,
5048 'other' => array('shortname' => $course->shortname,
5049 'fullname' => $course->fullname,
5050 'options' => $options) // Passing this for legacy reasons.
5052 $event->add_record_snapshot('course', $course);
5053 $event->trigger();
5055 return true;
5059 * Change dates in module - used from course reset.
5061 * @param string $modname forum, assignment, etc
5062 * @param array $fields array of date fields from mod table
5063 * @param int $timeshift time difference
5064 * @param int $courseid
5065 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5066 * @return bool success
5068 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5069 global $CFG, $DB;
5070 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5072 $return = true;
5073 $params = array($timeshift, $courseid);
5074 foreach ($fields as $field) {
5075 $updatesql = "UPDATE {".$modname."}
5076 SET $field = $field + ?
5077 WHERE course=? AND $field<>0";
5078 if ($modid) {
5079 $updatesql .= ' AND id=?';
5080 $params[] = $modid;
5082 $return = $DB->execute($updatesql, $params) && $return;
5085 $refreshfunction = $modname.'_refresh_events';
5086 if (function_exists($refreshfunction)) {
5087 $refreshfunction($courseid);
5090 return $return;
5094 * This function will empty a course of user data.
5095 * It will retain the activities and the structure of the course.
5097 * @param object $data an object containing all the settings including courseid (without magic quotes)
5098 * @return array status array of array component, item, error
5100 function reset_course_userdata($data) {
5101 global $CFG, $DB;
5102 require_once($CFG->libdir.'/gradelib.php');
5103 require_once($CFG->libdir.'/completionlib.php');
5104 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5105 require_once($CFG->dirroot.'/group/lib.php');
5107 $data->courseid = $data->id;
5108 $context = context_course::instance($data->courseid);
5110 $eventparams = array(
5111 'context' => $context,
5112 'courseid' => $data->id,
5113 'other' => array(
5114 'reset_options' => (array) $data
5117 $event = \core\event\course_reset_started::create($eventparams);
5118 $event->trigger();
5120 // Calculate the time shift of dates.
5121 if (!empty($data->reset_start_date)) {
5122 // Time part of course startdate should be zero.
5123 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5124 } else {
5125 $data->timeshift = 0;
5128 // Result array: component, item, error.
5129 $status = array();
5131 // Start the resetting.
5132 $componentstr = get_string('general');
5134 // Move the course start time.
5135 if (!empty($data->reset_start_date) and $data->timeshift) {
5136 // Change course start data.
5137 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5138 // Update all course and group events - do not move activity events.
5139 $updatesql = "UPDATE {event}
5140 SET timestart = timestart + ?
5141 WHERE courseid=? AND instance=0";
5142 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5144 // Update any date activity restrictions.
5145 if ($CFG->enableavailability) {
5146 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5149 // Update completion expected dates.
5150 if ($CFG->enablecompletion) {
5151 $modinfo = get_fast_modinfo($data->courseid);
5152 $changed = false;
5153 foreach ($modinfo->get_cms() as $cm) {
5154 if ($cm->completion && !empty($cm->completionexpected)) {
5155 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5156 array('id' => $cm->id));
5157 $changed = true;
5161 // Clear course cache if changes made.
5162 if ($changed) {
5163 rebuild_course_cache($data->courseid, true);
5166 // Update course date completion criteria.
5167 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5170 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5173 if (!empty($data->reset_events)) {
5174 $DB->delete_records('event', array('courseid' => $data->courseid));
5175 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5178 if (!empty($data->reset_notes)) {
5179 require_once($CFG->dirroot.'/notes/lib.php');
5180 note_delete_all($data->courseid);
5181 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5184 if (!empty($data->delete_blog_associations)) {
5185 require_once($CFG->dirroot.'/blog/lib.php');
5186 blog_remove_associations_for_course($data->courseid);
5187 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5190 if (!empty($data->reset_completion)) {
5191 // Delete course and activity completion information.
5192 $course = $DB->get_record('course', array('id' => $data->courseid));
5193 $cc = new completion_info($course);
5194 $cc->delete_all_completion_data();
5195 $status[] = array('component' => $componentstr,
5196 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5199 if (!empty($data->reset_competency_ratings)) {
5200 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5201 $status[] = array('component' => $componentstr,
5202 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5205 $componentstr = get_string('roles');
5207 if (!empty($data->reset_roles_overrides)) {
5208 $children = $context->get_child_contexts();
5209 foreach ($children as $child) {
5210 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5212 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5213 // Force refresh for logged in users.
5214 $context->mark_dirty();
5215 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5218 if (!empty($data->reset_roles_local)) {
5219 $children = $context->get_child_contexts();
5220 foreach ($children as $child) {
5221 role_unassign_all(array('contextid' => $child->id));
5223 // Force refresh for logged in users.
5224 $context->mark_dirty();
5225 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5228 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5229 $data->unenrolled = array();
5230 if (!empty($data->unenrol_users)) {
5231 $plugins = enrol_get_plugins(true);
5232 $instances = enrol_get_instances($data->courseid, true);
5233 foreach ($instances as $key => $instance) {
5234 if (!isset($plugins[$instance->enrol])) {
5235 unset($instances[$key]);
5236 continue;
5240 foreach ($data->unenrol_users as $withroleid) {
5241 if ($withroleid) {
5242 $sql = "SELECT ue.*
5243 FROM {user_enrolments} ue
5244 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5245 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5246 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5247 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5249 } else {
5250 // Without any role assigned at course context.
5251 $sql = "SELECT ue.*
5252 FROM {user_enrolments} ue
5253 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5254 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5255 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5256 WHERE ra.id IS null";
5257 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5260 $rs = $DB->get_recordset_sql($sql, $params);
5261 foreach ($rs as $ue) {
5262 if (!isset($instances[$ue->enrolid])) {
5263 continue;
5265 $instance = $instances[$ue->enrolid];
5266 $plugin = $plugins[$instance->enrol];
5267 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5268 continue;
5271 $plugin->unenrol_user($instance, $ue->userid);
5272 $data->unenrolled[$ue->userid] = $ue->userid;
5274 $rs->close();
5277 if (!empty($data->unenrolled)) {
5278 $status[] = array(
5279 'component' => $componentstr,
5280 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5281 'error' => false
5285 $componentstr = get_string('groups');
5287 // Remove all group members.
5288 if (!empty($data->reset_groups_members)) {
5289 groups_delete_group_members($data->courseid);
5290 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5293 // Remove all groups.
5294 if (!empty($data->reset_groups_remove)) {
5295 groups_delete_groups($data->courseid, false);
5296 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5299 // Remove all grouping members.
5300 if (!empty($data->reset_groupings_members)) {
5301 groups_delete_groupings_groups($data->courseid, false);
5302 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5305 // Remove all groupings.
5306 if (!empty($data->reset_groupings_remove)) {
5307 groups_delete_groupings($data->courseid, false);
5308 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5311 // Look in every instance of every module for data to delete.
5312 $unsupportedmods = array();
5313 if ($allmods = $DB->get_records('modules') ) {
5314 foreach ($allmods as $mod) {
5315 $modname = $mod->name;
5316 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5317 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5318 if (file_exists($modfile)) {
5319 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5320 continue; // Skip mods with no instances.
5322 include_once($modfile);
5323 if (function_exists($moddeleteuserdata)) {
5324 $modstatus = $moddeleteuserdata($data);
5325 if (is_array($modstatus)) {
5326 $status = array_merge($status, $modstatus);
5327 } else {
5328 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5330 } else {
5331 $unsupportedmods[] = $mod;
5333 } else {
5334 debugging('Missing lib.php in '.$modname.' module!');
5339 // Mention unsupported mods.
5340 if (!empty($unsupportedmods)) {
5341 foreach ($unsupportedmods as $mod) {
5342 $status[] = array(
5343 'component' => get_string('modulenameplural', $mod->name),
5344 'item' => '',
5345 'error' => get_string('resetnotimplemented')
5350 $componentstr = get_string('gradebook', 'grades');
5351 // Reset gradebook,.
5352 if (!empty($data->reset_gradebook_items)) {
5353 remove_course_grades($data->courseid, false);
5354 grade_grab_course_grades($data->courseid);
5355 grade_regrade_final_grades($data->courseid);
5356 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5358 } else if (!empty($data->reset_gradebook_grades)) {
5359 grade_course_reset($data->courseid);
5360 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5362 // Reset comments.
5363 if (!empty($data->reset_comments)) {
5364 require_once($CFG->dirroot.'/comment/lib.php');
5365 comment::reset_course_page_comments($context);
5368 $event = \core\event\course_reset_ended::create($eventparams);
5369 $event->trigger();
5371 return $status;
5375 * Generate an email processing address.
5377 * @param int $modid
5378 * @param string $modargs
5379 * @return string Returns email processing address
5381 function generate_email_processing_address($modid, $modargs) {
5382 global $CFG;
5384 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5385 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5391 * @todo Finish documenting this function
5393 * @param string $modargs
5394 * @param string $body Currently unused
5396 function moodle_process_email($modargs, $body) {
5397 global $DB;
5399 // The first char should be an unencoded letter. We'll take this as an action.
5400 switch ($modargs{0}) {
5401 case 'B': { // Bounce.
5402 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5403 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5404 // Check the half md5 of their email.
5405 $md5check = substr(md5($user->email), 0, 16);
5406 if ($md5check == substr($modargs, -16)) {
5407 set_bounce_count($user);
5409 // Else maybe they've already changed it?
5412 break;
5413 // Maybe more later?
5417 // CORRESPONDENCE.
5420 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5422 * @param string $action 'get', 'buffer', 'close' or 'flush'
5423 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5425 function get_mailer($action='get') {
5426 global $CFG;
5428 /** @var moodle_phpmailer $mailer */
5429 static $mailer = null;
5430 static $counter = 0;
5432 if (!isset($CFG->smtpmaxbulk)) {
5433 $CFG->smtpmaxbulk = 1;
5436 if ($action == 'get') {
5437 $prevkeepalive = false;
5439 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5440 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5441 $counter++;
5442 // Reset the mailer.
5443 $mailer->Priority = 3;
5444 $mailer->CharSet = 'UTF-8'; // Our default.
5445 $mailer->ContentType = "text/plain";
5446 $mailer->Encoding = "8bit";
5447 $mailer->From = "root@localhost";
5448 $mailer->FromName = "Root User";
5449 $mailer->Sender = "";
5450 $mailer->Subject = "";
5451 $mailer->Body = "";
5452 $mailer->AltBody = "";
5453 $mailer->ConfirmReadingTo = "";
5455 $mailer->clearAllRecipients();
5456 $mailer->clearReplyTos();
5457 $mailer->clearAttachments();
5458 $mailer->clearCustomHeaders();
5459 return $mailer;
5462 $prevkeepalive = $mailer->SMTPKeepAlive;
5463 get_mailer('flush');
5466 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5467 $mailer = new moodle_phpmailer();
5469 $counter = 1;
5471 if ($CFG->smtphosts == 'qmail') {
5472 // Use Qmail system.
5473 $mailer->isQmail();
5475 } else if (empty($CFG->smtphosts)) {
5476 // Use PHP mail() = sendmail.
5477 $mailer->isMail();
5479 } else {
5480 // Use SMTP directly.
5481 $mailer->isSMTP();
5482 if (!empty($CFG->debugsmtp)) {
5483 $mailer->SMTPDebug = true;
5485 // Specify main and backup servers.
5486 $mailer->Host = $CFG->smtphosts;
5487 // Specify secure connection protocol.
5488 $mailer->SMTPSecure = $CFG->smtpsecure;
5489 // Use previous keepalive.
5490 $mailer->SMTPKeepAlive = $prevkeepalive;
5492 if ($CFG->smtpuser) {
5493 // Use SMTP authentication.
5494 $mailer->SMTPAuth = true;
5495 $mailer->Username = $CFG->smtpuser;
5496 $mailer->Password = $CFG->smtppass;
5500 return $mailer;
5503 $nothing = null;
5505 // Keep smtp session open after sending.
5506 if ($action == 'buffer') {
5507 if (!empty($CFG->smtpmaxbulk)) {
5508 get_mailer('flush');
5509 $m = get_mailer();
5510 if ($m->Mailer == 'smtp') {
5511 $m->SMTPKeepAlive = true;
5514 return $nothing;
5517 // Close smtp session, but continue buffering.
5518 if ($action == 'flush') {
5519 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5520 if (!empty($mailer->SMTPDebug)) {
5521 echo '<pre>'."\n";
5523 $mailer->SmtpClose();
5524 if (!empty($mailer->SMTPDebug)) {
5525 echo '</pre>';
5528 return $nothing;
5531 // Close smtp session, do not buffer anymore.
5532 if ($action == 'close') {
5533 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5534 get_mailer('flush');
5535 $mailer->SMTPKeepAlive = false;
5537 $mailer = null; // Better force new instance.
5538 return $nothing;
5543 * A helper function to test for email diversion
5545 * @param string $email
5546 * @return bool Returns true if the email should be diverted
5548 function email_should_be_diverted($email) {
5549 global $CFG;
5551 if (empty($CFG->divertallemailsto)) {
5552 return false;
5555 if (empty($CFG->divertallemailsexcept)) {
5556 return true;
5559 $patterns = array_map('trim', explode(',', $CFG->divertallemailsexcept));
5560 foreach ($patterns as $pattern) {
5561 if (preg_match("/$pattern/", $email)) {
5562 return false;
5566 return true;
5570 * Generate a unique email Message-ID using the moodle domain and install path
5572 * @param string $localpart An optional unique message id prefix.
5573 * @return string The formatted ID ready for appending to the email headers.
5575 function generate_email_messageid($localpart = null) {
5576 global $CFG;
5578 $urlinfo = parse_url($CFG->wwwroot);
5579 $base = '@' . $urlinfo['host'];
5581 // If multiple moodles are on the same domain we want to tell them
5582 // apart so we add the install path to the local part. This means
5583 // that the id local part should never contain a / character so
5584 // we can correctly parse the id to reassemble the wwwroot.
5585 if (isset($urlinfo['path'])) {
5586 $base = $urlinfo['path'] . $base;
5589 if (empty($localpart)) {
5590 $localpart = uniqid('', true);
5593 // Because we may have an option /installpath suffix to the local part
5594 // of the id we need to escape any / chars which are in the $localpart.
5595 $localpart = str_replace('/', '%2F', $localpart);
5597 return '<' . $localpart . $base . '>';
5601 * Send an email to a specified user
5603 * @param stdClass $user A {@link $USER} object
5604 * @param stdClass $from A {@link $USER} object
5605 * @param string $subject plain text subject line of the email
5606 * @param string $messagetext plain text version of the message
5607 * @param string $messagehtml complete html version of the message (optional)
5608 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5609 * @param string $attachname the name of the file (extension indicates MIME)
5610 * @param bool $usetrueaddress determines whether $from email address should
5611 * be sent out. Will be overruled by user profile setting for maildisplay
5612 * @param string $replyto Email address to reply to
5613 * @param string $replytoname Name of reply to recipient
5614 * @param int $wordwrapwidth custom word wrap width, default 79
5615 * @return bool Returns true if mail was sent OK and false if there was an error.
5617 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5618 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5620 global $CFG, $PAGE, $SITE;
5622 if (empty($user) or empty($user->id)) {
5623 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5624 return false;
5627 if (empty($user->email)) {
5628 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5629 return false;
5632 if (!empty($user->deleted)) {
5633 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5634 return false;
5637 if (defined('BEHAT_SITE_RUNNING')) {
5638 // Fake email sending in behat.
5639 return true;
5642 if (!empty($CFG->noemailever)) {
5643 // Hidden setting for development sites, set in config.php if needed.
5644 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5645 return true;
5648 if (email_should_be_diverted($user->email)) {
5649 $subject = "[DIVERTED {$user->email}] $subject";
5650 $user = clone($user);
5651 $user->email = $CFG->divertallemailsto;
5654 // Skip mail to suspended users.
5655 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5656 return true;
5659 if (!validate_email($user->email)) {
5660 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5661 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5662 return false;
5665 if (over_bounce_threshold($user)) {
5666 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5667 return false;
5670 // TLD .invalid is specifically reserved for invalid domain names.
5671 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5672 if (substr($user->email, -8) == '.invalid') {
5673 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5674 return true; // This is not an error.
5677 // If the user is a remote mnet user, parse the email text for URL to the
5678 // wwwroot and modify the url to direct the user's browser to login at their
5679 // home site (identity provider - idp) before hitting the link itself.
5680 if (is_mnet_remote_user($user)) {
5681 require_once($CFG->dirroot.'/mnet/lib.php');
5683 $jumpurl = mnet_get_idp_jump_url($user);
5684 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5686 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5687 $callback,
5688 $messagetext);
5689 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5690 $callback,
5691 $messagehtml);
5693 $mail = get_mailer();
5695 if (!empty($mail->SMTPDebug)) {
5696 echo '<pre>' . "\n";
5699 $temprecipients = array();
5700 $tempreplyto = array();
5702 $supportuser = core_user::get_support_user();
5703 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
5704 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
5706 if (!validate_email($noreplyaddress)) {
5707 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
5708 $noreplyaddress = $noreplyaddressdefault;
5711 if (!validate_email($supportuser->email)) {
5712 debugging('email_to_user: Invalid support-email '.s($supportuser->email));
5713 $supportuser->email = $noreplyaddress;
5716 // Make up an email address for handling bounces.
5717 if (!empty($CFG->handlebounces)) {
5718 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5719 $mail->Sender = generate_email_processing_address(0, $modargs);
5720 } else {
5721 $mail->Sender = $supportuser->email;
5724 if (!empty($CFG->emailonlyfromnoreplyaddress)) {
5725 $usetrueaddress = false;
5726 if (empty($replyto) && $from->maildisplay) {
5727 $replyto = $from->email;
5728 $replytoname = fullname($from);
5732 // Make sure that the explicit replyto is valid, fall back to the implicit one.
5733 if (!empty($replyto) && !validate_email($replyto)) {
5734 debugging('email_to_user: Invalid replyto-email '.s($replyto));
5735 $replyto = $noreplyaddress;
5738 if (is_string($from)) { // So we can pass whatever we want if there is need.
5739 $mail->From = $noreplyaddress;
5740 $mail->FromName = $from;
5741 } else if ($usetrueaddress and $from->maildisplay) {
5742 if (!validate_email($from->email)) {
5743 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
5744 // Better not to use $noreplyaddress in this case.
5745 return false;
5747 $mail->From = $from->email;
5748 $mail->FromName = fullname($from);
5749 } else {
5750 $mail->From = $noreplyaddress;
5751 $mail->FromName = fullname($from);
5752 if (empty($replyto)) {
5753 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
5757 if (!empty($replyto)) {
5758 $tempreplyto[] = array($replyto, $replytoname);
5761 $temprecipients[] = array($user->email, fullname($user));
5763 // Set word wrap.
5764 $mail->WordWrap = $wordwrapwidth;
5766 if (!empty($from->customheaders)) {
5767 // Add custom headers.
5768 if (is_array($from->customheaders)) {
5769 foreach ($from->customheaders as $customheader) {
5770 $mail->addCustomHeader($customheader);
5772 } else {
5773 $mail->addCustomHeader($from->customheaders);
5777 // If the X-PHP-Originating-Script email header is on then also add an additional
5778 // header with details of where exactly in moodle the email was triggered from,
5779 // either a call to message_send() or to email_to_user().
5780 if (ini_get('mail.add_x_header')) {
5782 $stack = debug_backtrace(false);
5783 $origin = $stack[0];
5785 foreach ($stack as $depth => $call) {
5786 if ($call['function'] == 'message_send') {
5787 $origin = $call;
5791 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
5792 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
5793 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
5796 if (!empty($from->priority)) {
5797 $mail->Priority = $from->priority;
5800 $renderer = $PAGE->get_renderer('core');
5801 $context = array(
5802 'sitefullname' => $SITE->fullname,
5803 'siteshortname' => $SITE->shortname,
5804 'sitewwwroot' => $CFG->wwwroot,
5805 'subject' => $subject,
5806 'to' => $user->email,
5807 'toname' => fullname($user),
5808 'from' => $mail->From,
5809 'fromname' => $mail->FromName,
5811 if (!empty($tempreplyto[0])) {
5812 $context['replyto'] = $tempreplyto[0][0];
5813 $context['replytoname'] = $tempreplyto[0][1];
5815 if ($user->id > 0) {
5816 $context['touserid'] = $user->id;
5817 $context['tousername'] = $user->username;
5820 if (!empty($user->mailformat) && $user->mailformat == 1) {
5821 // Only process html templates if the user preferences allow html email.
5823 if ($messagehtml) {
5824 // If html has been given then pass it through the template.
5825 $context['body'] = $messagehtml;
5826 $messagehtml = $renderer->render_from_template('core/email_html', $context);
5828 } else {
5829 // If no html has been given, BUT there is an html wrapping template then
5830 // auto convert the text to html and then wrap it.
5831 $autohtml = trim(text_to_html($messagetext));
5832 $context['body'] = $autohtml;
5833 $temphtml = $renderer->render_from_template('core/email_html', $context);
5834 if ($autohtml != $temphtml) {
5835 $messagehtml = $temphtml;
5840 $context['body'] = $messagetext;
5841 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
5842 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
5843 $messagetext = $renderer->render_from_template('core/email_text', $context);
5845 // Autogenerate a MessageID if it's missing.
5846 if (empty($mail->MessageID)) {
5847 $mail->MessageID = generate_email_messageid();
5850 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5851 // Don't ever send HTML to users who don't want it.
5852 $mail->isHTML(true);
5853 $mail->Encoding = 'quoted-printable';
5854 $mail->Body = $messagehtml;
5855 $mail->AltBody = "\n$messagetext\n";
5856 } else {
5857 $mail->IsHTML(false);
5858 $mail->Body = "\n$messagetext\n";
5861 if ($attachment && $attachname) {
5862 if (preg_match( "~\\.\\.~" , $attachment )) {
5863 // Security check for ".." in dir path.
5864 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5865 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5866 } else {
5867 require_once($CFG->libdir.'/filelib.php');
5868 $mimetype = mimeinfo('type', $attachname);
5870 $attachmentpath = $attachment;
5872 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5873 $attachpath = str_replace('\\', '/', $attachmentpath);
5874 // Make sure both variables are normalised before comparing.
5875 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
5877 // If the attachment is a full path to a file in the tempdir, use it as is,
5878 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5879 if (strpos($attachpath, $temppath) !== 0) {
5880 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
5883 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5887 // Check if the email should be sent in an other charset then the default UTF-8.
5888 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5890 // Use the defined site mail charset or eventually the one preferred by the recipient.
5891 $charset = $CFG->sitemailcharset;
5892 if (!empty($CFG->allowusermailcharset)) {
5893 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5894 $charset = $useremailcharset;
5898 // Convert all the necessary strings if the charset is supported.
5899 $charsets = get_list_of_charsets();
5900 unset($charsets['UTF-8']);
5901 if (in_array($charset, $charsets)) {
5902 $mail->CharSet = $charset;
5903 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
5904 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
5905 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
5906 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
5908 foreach ($temprecipients as $key => $values) {
5909 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5911 foreach ($tempreplyto as $key => $values) {
5912 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5917 foreach ($temprecipients as $values) {
5918 $mail->addAddress($values[0], $values[1]);
5920 foreach ($tempreplyto as $values) {
5921 $mail->addReplyTo($values[0], $values[1]);
5924 if ($mail->send()) {
5925 set_send_count($user);
5926 if (!empty($mail->SMTPDebug)) {
5927 echo '</pre>';
5929 return true;
5930 } else {
5931 // Trigger event for failing to send email.
5932 $event = \core\event\email_failed::create(array(
5933 'context' => context_system::instance(),
5934 'userid' => $from->id,
5935 'relateduserid' => $user->id,
5936 'other' => array(
5937 'subject' => $subject,
5938 'message' => $messagetext,
5939 'errorinfo' => $mail->ErrorInfo
5942 $event->trigger();
5943 if (CLI_SCRIPT) {
5944 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
5946 if (!empty($mail->SMTPDebug)) {
5947 echo '</pre>';
5949 return false;
5954 * Generate a signoff for emails based on support settings
5956 * @return string
5958 function generate_email_signoff() {
5959 global $CFG;
5961 $signoff = "\n";
5962 if (!empty($CFG->supportname)) {
5963 $signoff .= $CFG->supportname."\n";
5965 if (!empty($CFG->supportemail)) {
5966 $signoff .= $CFG->supportemail."\n";
5968 if (!empty($CFG->supportpage)) {
5969 $signoff .= $CFG->supportpage."\n";
5971 return $signoff;
5975 * Sets specified user's password and send the new password to the user via email.
5977 * @param stdClass $user A {@link $USER} object
5978 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
5979 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
5981 function setnew_password_and_mail($user, $fasthash = false) {
5982 global $CFG, $DB;
5984 // We try to send the mail in language the user understands,
5985 // unfortunately the filter_string() does not support alternative langs yet
5986 // so multilang will not work properly for site->fullname.
5987 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
5989 $site = get_site();
5991 $supportuser = core_user::get_support_user();
5993 $newpassword = generate_password();
5995 update_internal_user_password($user, $newpassword, $fasthash);
5997 $a = new stdClass();
5998 $a->firstname = fullname($user, true);
5999 $a->sitename = format_string($site->fullname);
6000 $a->username = $user->username;
6001 $a->newpassword = $newpassword;
6002 $a->link = $CFG->wwwroot .'/login/';
6003 $a->signoff = generate_email_signoff();
6005 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6007 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6009 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6010 return email_to_user($user, $supportuser, $subject, $message);
6015 * Resets specified user's password and send the new password to the user via email.
6017 * @param stdClass $user A {@link $USER} object
6018 * @return bool Returns true if mail was sent OK and false if there was an error.
6020 function reset_password_and_mail($user) {
6021 global $CFG;
6023 $site = get_site();
6024 $supportuser = core_user::get_support_user();
6026 $userauth = get_auth_plugin($user->auth);
6027 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6028 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6029 return false;
6032 $newpassword = generate_password();
6034 if (!$userauth->user_update_password($user, $newpassword)) {
6035 print_error("cannotsetpassword");
6038 $a = new stdClass();
6039 $a->firstname = $user->firstname;
6040 $a->lastname = $user->lastname;
6041 $a->sitename = format_string($site->fullname);
6042 $a->username = $user->username;
6043 $a->newpassword = $newpassword;
6044 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
6045 $a->signoff = generate_email_signoff();
6047 $message = get_string('newpasswordtext', '', $a);
6049 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6051 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6053 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6054 return email_to_user($user, $supportuser, $subject, $message);
6058 * Send email to specified user with confirmation text and activation link.
6060 * @param stdClass $user A {@link $USER} object
6061 * @return bool Returns true if mail was sent OK and false if there was an error.
6063 function send_confirmation_email($user) {
6064 global $CFG;
6066 $site = get_site();
6067 $supportuser = core_user::get_support_user();
6069 $data = new stdClass();
6070 $data->firstname = fullname($user);
6071 $data->sitename = format_string($site->fullname);
6072 $data->admin = generate_email_signoff();
6074 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6076 $username = urlencode($user->username);
6077 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
6078 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
6079 $message = get_string('emailconfirmation', '', $data);
6080 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6082 $user->mailformat = 1; // Always send HTML version as well.
6084 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6085 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6089 * Sends a password change confirmation email.
6091 * @param stdClass $user A {@link $USER} object
6092 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6093 * @return bool Returns true if mail was sent OK and false if there was an error.
6095 function send_password_change_confirmation_email($user, $resetrecord) {
6096 global $CFG;
6098 $site = get_site();
6099 $supportuser = core_user::get_support_user();
6100 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6102 $data = new stdClass();
6103 $data->firstname = $user->firstname;
6104 $data->lastname = $user->lastname;
6105 $data->username = $user->username;
6106 $data->sitename = format_string($site->fullname);
6107 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6108 $data->admin = generate_email_signoff();
6109 $data->resetminutes = $pwresetmins;
6111 $message = get_string('emailresetconfirmation', '', $data);
6112 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6114 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6115 return email_to_user($user, $supportuser, $subject, $message);
6120 * Sends an email containinginformation on how to change your password.
6122 * @param stdClass $user A {@link $USER} object
6123 * @return bool Returns true if mail was sent OK and false if there was an error.
6125 function send_password_change_info($user) {
6126 global $CFG;
6128 $site = get_site();
6129 $supportuser = core_user::get_support_user();
6130 $systemcontext = context_system::instance();
6132 $data = new stdClass();
6133 $data->firstname = $user->firstname;
6134 $data->lastname = $user->lastname;
6135 $data->sitename = format_string($site->fullname);
6136 $data->admin = generate_email_signoff();
6138 $userauth = get_auth_plugin($user->auth);
6140 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6141 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6142 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6143 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6144 return email_to_user($user, $supportuser, $subject, $message);
6147 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6148 // We have some external url for password changing.
6149 $data->link .= $userauth->change_password_url();
6151 } else {
6152 // No way to change password, sorry.
6153 $data->link = '';
6156 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6157 $message = get_string('emailpasswordchangeinfo', '', $data);
6158 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6159 } else {
6160 $message = get_string('emailpasswordchangeinfofail', '', $data);
6161 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6164 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6165 return email_to_user($user, $supportuser, $subject, $message);
6170 * Check that an email is allowed. It returns an error message if there was a problem.
6172 * @param string $email Content of email
6173 * @return string|false
6175 function email_is_not_allowed($email) {
6176 global $CFG;
6178 if (!empty($CFG->allowemailaddresses)) {
6179 $allowed = explode(' ', $CFG->allowemailaddresses);
6180 foreach ($allowed as $allowedpattern) {
6181 $allowedpattern = trim($allowedpattern);
6182 if (!$allowedpattern) {
6183 continue;
6185 if (strpos($allowedpattern, '.') === 0) {
6186 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6187 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6188 return false;
6191 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6192 return false;
6195 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6197 } else if (!empty($CFG->denyemailaddresses)) {
6198 $denied = explode(' ', $CFG->denyemailaddresses);
6199 foreach ($denied as $deniedpattern) {
6200 $deniedpattern = trim($deniedpattern);
6201 if (!$deniedpattern) {
6202 continue;
6204 if (strpos($deniedpattern, '.') === 0) {
6205 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6206 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6207 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6210 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6211 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6216 return false;
6219 // FILE HANDLING.
6222 * Returns local file storage instance
6224 * @return file_storage
6226 function get_file_storage() {
6227 global $CFG;
6229 static $fs = null;
6231 if ($fs) {
6232 return $fs;
6235 require_once("$CFG->libdir/filelib.php");
6237 if (isset($CFG->filedir)) {
6238 $filedir = $CFG->filedir;
6239 } else {
6240 $filedir = $CFG->dataroot.'/filedir';
6243 if (isset($CFG->trashdir)) {
6244 $trashdirdir = $CFG->trashdir;
6245 } else {
6246 $trashdirdir = $CFG->dataroot.'/trashdir';
6249 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
6251 return $fs;
6255 * Returns local file storage instance
6257 * @return file_browser
6259 function get_file_browser() {
6260 global $CFG;
6262 static $fb = null;
6264 if ($fb) {
6265 return $fb;
6268 require_once("$CFG->libdir/filelib.php");
6270 $fb = new file_browser();
6272 return $fb;
6276 * Returns file packer
6278 * @param string $mimetype default application/zip
6279 * @return file_packer
6281 function get_file_packer($mimetype='application/zip') {
6282 global $CFG;
6284 static $fp = array();
6286 if (isset($fp[$mimetype])) {
6287 return $fp[$mimetype];
6290 switch ($mimetype) {
6291 case 'application/zip':
6292 case 'application/vnd.moodle.profiling':
6293 $classname = 'zip_packer';
6294 break;
6296 case 'application/x-gzip' :
6297 $classname = 'tgz_packer';
6298 break;
6300 case 'application/vnd.moodle.backup':
6301 $classname = 'mbz_packer';
6302 break;
6304 default:
6305 return false;
6308 require_once("$CFG->libdir/filestorage/$classname.php");
6309 $fp[$mimetype] = new $classname();
6311 return $fp[$mimetype];
6315 * Returns current name of file on disk if it exists.
6317 * @param string $newfile File to be verified
6318 * @return string Current name of file on disk if true
6320 function valid_uploaded_file($newfile) {
6321 if (empty($newfile)) {
6322 return '';
6324 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6325 return $newfile['tmp_name'];
6326 } else {
6327 return '';
6332 * Returns the maximum size for uploading files.
6334 * There are seven possible upload limits:
6335 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6336 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6337 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6338 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6339 * 5. by the Moodle admin in $CFG->maxbytes
6340 * 6. by the teacher in the current course $course->maxbytes
6341 * 7. by the teacher for the current module, eg $assignment->maxbytes
6343 * These last two are passed to this function as arguments (in bytes).
6344 * Anything defined as 0 is ignored.
6345 * The smallest of all the non-zero numbers is returned.
6347 * @todo Finish documenting this function
6349 * @param int $sitebytes Set maximum size
6350 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6351 * @param int $modulebytes Current module ->maxbytes (in bytes)
6352 * @param bool $unused This parameter has been deprecated and is not used any more.
6353 * @return int The maximum size for uploading files.
6355 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6357 if (! $filesize = ini_get('upload_max_filesize')) {
6358 $filesize = '5M';
6360 $minimumsize = get_real_size($filesize);
6362 if ($postsize = ini_get('post_max_size')) {
6363 $postsize = get_real_size($postsize);
6364 if ($postsize < $minimumsize) {
6365 $minimumsize = $postsize;
6369 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6370 $minimumsize = $sitebytes;
6373 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6374 $minimumsize = $coursebytes;
6377 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6378 $minimumsize = $modulebytes;
6381 return $minimumsize;
6385 * Returns the maximum size for uploading files for the current user
6387 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6389 * @param context $context The context in which to check user capabilities
6390 * @param int $sitebytes Set maximum size
6391 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6392 * @param int $modulebytes Current module ->maxbytes (in bytes)
6393 * @param stdClass $user The user
6394 * @param bool $unused This parameter has been deprecated and is not used any more.
6395 * @return int The maximum size for uploading files.
6397 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6398 $unused = false) {
6399 global $USER;
6401 if (empty($user)) {
6402 $user = $USER;
6405 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6406 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6409 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6413 * Returns an array of possible sizes in local language
6415 * Related to {@link get_max_upload_file_size()} - this function returns an
6416 * array of possible sizes in an array, translated to the
6417 * local language.
6419 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6421 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6422 * with the value set to 0. This option will be the first in the list.
6424 * @uses SORT_NUMERIC
6425 * @param int $sitebytes Set maximum size
6426 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6427 * @param int $modulebytes Current module ->maxbytes (in bytes)
6428 * @param int|array $custombytes custom upload size/s which will be added to list,
6429 * Only value/s smaller then maxsize will be added to list.
6430 * @return array
6432 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6433 global $CFG;
6435 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6436 return array();
6439 if ($sitebytes == 0) {
6440 // Will get the minimum of upload_max_filesize or post_max_size.
6441 $sitebytes = get_max_upload_file_size();
6444 $filesize = array();
6445 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6446 5242880, 10485760, 20971520, 52428800, 104857600);
6448 // If custombytes is given and is valid then add it to the list.
6449 if (is_number($custombytes) and $custombytes > 0) {
6450 $custombytes = (int)$custombytes;
6451 if (!in_array($custombytes, $sizelist)) {
6452 $sizelist[] = $custombytes;
6454 } else if (is_array($custombytes)) {
6455 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6458 // Allow maxbytes to be selected if it falls outside the above boundaries.
6459 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6460 // Note: get_real_size() is used in order to prevent problems with invalid values.
6461 $sizelist[] = get_real_size($CFG->maxbytes);
6464 foreach ($sizelist as $sizebytes) {
6465 if ($sizebytes < $maxsize && $sizebytes > 0) {
6466 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6470 $limitlevel = '';
6471 $displaysize = '';
6472 if ($modulebytes &&
6473 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6474 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6475 $limitlevel = get_string('activity', 'core');
6476 $displaysize = display_size($modulebytes);
6477 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6479 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6480 $limitlevel = get_string('course', 'core');
6481 $displaysize = display_size($coursebytes);
6482 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6484 } else if ($sitebytes) {
6485 $limitlevel = get_string('site', 'core');
6486 $displaysize = display_size($sitebytes);
6487 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6490 krsort($filesize, SORT_NUMERIC);
6491 if ($limitlevel) {
6492 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6493 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6496 return $filesize;
6500 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6502 * If excludefiles is defined, then that file/directory is ignored
6503 * If getdirs is true, then (sub)directories are included in the output
6504 * If getfiles is true, then files are included in the output
6505 * (at least one of these must be true!)
6507 * @todo Finish documenting this function. Add examples of $excludefile usage.
6509 * @param string $rootdir A given root directory to start from
6510 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6511 * @param bool $descend If true then subdirectories are recursed as well
6512 * @param bool $getdirs If true then (sub)directories are included in the output
6513 * @param bool $getfiles If true then files are included in the output
6514 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6516 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6518 $dirs = array();
6520 if (!$getdirs and !$getfiles) { // Nothing to show.
6521 return $dirs;
6524 if (!is_dir($rootdir)) { // Must be a directory.
6525 return $dirs;
6528 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6529 return $dirs;
6532 if (!is_array($excludefiles)) {
6533 $excludefiles = array($excludefiles);
6536 while (false !== ($file = readdir($dir))) {
6537 $firstchar = substr($file, 0, 1);
6538 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6539 continue;
6541 $fullfile = $rootdir .'/'. $file;
6542 if (filetype($fullfile) == 'dir') {
6543 if ($getdirs) {
6544 $dirs[] = $file;
6546 if ($descend) {
6547 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6548 foreach ($subdirs as $subdir) {
6549 $dirs[] = $file .'/'. $subdir;
6552 } else if ($getfiles) {
6553 $dirs[] = $file;
6556 closedir($dir);
6558 asort($dirs);
6560 return $dirs;
6565 * Adds up all the files in a directory and works out the size.
6567 * @param string $rootdir The directory to start from
6568 * @param string $excludefile A file to exclude when summing directory size
6569 * @return int The summed size of all files and subfiles within the root directory
6571 function get_directory_size($rootdir, $excludefile='') {
6572 global $CFG;
6574 // Do it this way if we can, it's much faster.
6575 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6576 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6577 $output = null;
6578 $return = null;
6579 exec($command, $output, $return);
6580 if (is_array($output)) {
6581 // We told it to return k.
6582 return get_real_size(intval($output[0]).'k');
6586 if (!is_dir($rootdir)) {
6587 // Must be a directory.
6588 return 0;
6591 if (!$dir = @opendir($rootdir)) {
6592 // Can't open it for some reason.
6593 return 0;
6596 $size = 0;
6598 while (false !== ($file = readdir($dir))) {
6599 $firstchar = substr($file, 0, 1);
6600 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6601 continue;
6603 $fullfile = $rootdir .'/'. $file;
6604 if (filetype($fullfile) == 'dir') {
6605 $size += get_directory_size($fullfile, $excludefile);
6606 } else {
6607 $size += filesize($fullfile);
6610 closedir($dir);
6612 return $size;
6616 * Converts bytes into display form
6618 * @static string $gb Localized string for size in gigabytes
6619 * @static string $mb Localized string for size in megabytes
6620 * @static string $kb Localized string for size in kilobytes
6621 * @static string $b Localized string for size in bytes
6622 * @param int $size The size to convert to human readable form
6623 * @return string
6625 function display_size($size) {
6627 static $gb, $mb, $kb, $b;
6629 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6630 return get_string('unlimited');
6633 if (empty($gb)) {
6634 $gb = get_string('sizegb');
6635 $mb = get_string('sizemb');
6636 $kb = get_string('sizekb');
6637 $b = get_string('sizeb');
6640 if ($size >= 1073741824) {
6641 $size = round($size / 1073741824 * 10) / 10 . $gb;
6642 } else if ($size >= 1048576) {
6643 $size = round($size / 1048576 * 10) / 10 . $mb;
6644 } else if ($size >= 1024) {
6645 $size = round($size / 1024 * 10) / 10 . $kb;
6646 } else {
6647 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6649 return $size;
6653 * Cleans a given filename by removing suspicious or troublesome characters
6655 * @see clean_param()
6656 * @param string $string file name
6657 * @return string cleaned file name
6659 function clean_filename($string) {
6660 return clean_param($string, PARAM_FILE);
6664 // STRING TRANSLATION.
6667 * Returns the code for the current language
6669 * @category string
6670 * @return string
6672 function current_language() {
6673 global $CFG, $USER, $SESSION, $COURSE;
6675 if (!empty($SESSION->forcelang)) {
6676 // Allows overriding course-forced language (useful for admins to check
6677 // issues in courses whose language they don't understand).
6678 // Also used by some code to temporarily get language-related information in a
6679 // specific language (see force_current_language()).
6680 $return = $SESSION->forcelang;
6682 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6683 // Course language can override all other settings for this page.
6684 $return = $COURSE->lang;
6686 } else if (!empty($SESSION->lang)) {
6687 // Session language can override other settings.
6688 $return = $SESSION->lang;
6690 } else if (!empty($USER->lang)) {
6691 $return = $USER->lang;
6693 } else if (isset($CFG->lang)) {
6694 $return = $CFG->lang;
6696 } else {
6697 $return = 'en';
6700 // Just in case this slipped in from somewhere by accident.
6701 $return = str_replace('_utf8', '', $return);
6703 return $return;
6707 * Returns parent language of current active language if defined
6709 * @category string
6710 * @param string $lang null means current language
6711 * @return string
6713 function get_parent_language($lang=null) {
6715 // Let's hack around the current language.
6716 if (!empty($lang)) {
6717 $oldforcelang = force_current_language($lang);
6720 $parentlang = get_string('parentlanguage', 'langconfig');
6721 if ($parentlang === 'en') {
6722 $parentlang = '';
6725 // Let's hack around the current language.
6726 if (!empty($lang)) {
6727 force_current_language($oldforcelang);
6730 return $parentlang;
6734 * Force the current language to get strings and dates localised in the given language.
6736 * After calling this function, all strings will be provided in the given language
6737 * until this function is called again, or equivalent code is run.
6739 * @param string $language
6740 * @return string previous $SESSION->forcelang value
6742 function force_current_language($language) {
6743 global $SESSION;
6744 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6745 if ($language !== $sessionforcelang) {
6746 // Seting forcelang to null or an empty string disables it's effect.
6747 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6748 $SESSION->forcelang = $language;
6749 moodle_setlocale();
6752 return $sessionforcelang;
6756 * Returns current string_manager instance.
6758 * The param $forcereload is needed for CLI installer only where the string_manager instance
6759 * must be replaced during the install.php script life time.
6761 * @category string
6762 * @param bool $forcereload shall the singleton be released and new instance created instead?
6763 * @return core_string_manager
6765 function get_string_manager($forcereload=false) {
6766 global $CFG;
6768 static $singleton = null;
6770 if ($forcereload) {
6771 $singleton = null;
6773 if ($singleton === null) {
6774 if (empty($CFG->early_install_lang)) {
6776 if (empty($CFG->langlist)) {
6777 $translist = array();
6778 } else {
6779 $translist = explode(',', $CFG->langlist);
6782 if (!empty($CFG->config_php_settings['customstringmanager'])) {
6783 $classname = $CFG->config_php_settings['customstringmanager'];
6785 if (class_exists($classname)) {
6786 $implements = class_implements($classname);
6788 if (isset($implements['core_string_manager'])) {
6789 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist);
6790 return $singleton;
6792 } else {
6793 debugging('Unable to instantiate custom string manager: class '.$classname.
6794 ' does not implement the core_string_manager interface.');
6797 } else {
6798 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
6802 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6804 } else {
6805 $singleton = new core_string_manager_install();
6809 return $singleton;
6813 * Returns a localized string.
6815 * Returns the translated string specified by $identifier as
6816 * for $module. Uses the same format files as STphp.
6817 * $a is an object, string or number that can be used
6818 * within translation strings
6820 * eg 'hello {$a->firstname} {$a->lastname}'
6821 * or 'hello {$a}'
6823 * If you would like to directly echo the localized string use
6824 * the function {@link print_string()}
6826 * Example usage of this function involves finding the string you would
6827 * like a local equivalent of and using its identifier and module information
6828 * to retrieve it.<br/>
6829 * If you open moodle/lang/en/moodle.php and look near line 278
6830 * you will find a string to prompt a user for their word for 'course'
6831 * <code>
6832 * $string['course'] = 'Course';
6833 * </code>
6834 * So if you want to display the string 'Course'
6835 * in any language that supports it on your site
6836 * you just need to use the identifier 'course'
6837 * <code>
6838 * $mystring = '<strong>'. get_string('course') .'</strong>';
6839 * or
6840 * </code>
6841 * If the string you want is in another file you'd take a slightly
6842 * different approach. Looking in moodle/lang/en/calendar.php you find
6843 * around line 75:
6844 * <code>
6845 * $string['typecourse'] = 'Course event';
6846 * </code>
6847 * If you want to display the string "Course event" in any language
6848 * supported you would use the identifier 'typecourse' and the module 'calendar'
6849 * (because it is in the file calendar.php):
6850 * <code>
6851 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6852 * </code>
6854 * As a last resort, should the identifier fail to map to a string
6855 * the returned string will be [[ $identifier ]]
6857 * In Moodle 2.3 there is a new argument to this function $lazyload.
6858 * Setting $lazyload to true causes get_string to return a lang_string object
6859 * rather than the string itself. The fetching of the string is then put off until
6860 * the string object is first used. The object can be used by calling it's out
6861 * method or by casting the object to a string, either directly e.g.
6862 * (string)$stringobject
6863 * or indirectly by using the string within another string or echoing it out e.g.
6864 * echo $stringobject
6865 * return "<p>{$stringobject}</p>";
6866 * It is worth noting that using $lazyload and attempting to use the string as an
6867 * array key will cause a fatal error as objects cannot be used as array keys.
6868 * But you should never do that anyway!
6869 * For more information {@link lang_string}
6871 * @category string
6872 * @param string $identifier The key identifier for the localized string
6873 * @param string $component The module where the key identifier is stored,
6874 * usually expressed as the filename in the language pack without the
6875 * .php on the end but can also be written as mod/forum or grade/export/xls.
6876 * If none is specified then moodle.php is used.
6877 * @param string|object|array $a An object, string or number that can be used
6878 * within translation strings
6879 * @param bool $lazyload If set to true a string object is returned instead of
6880 * the string itself. The string then isn't calculated until it is first used.
6881 * @return string The localized string.
6882 * @throws coding_exception
6884 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6885 global $CFG;
6887 // If the lazy load argument has been supplied return a lang_string object
6888 // instead.
6889 // We need to make sure it is true (and a bool) as you will see below there
6890 // used to be a forth argument at one point.
6891 if ($lazyload === true) {
6892 return new lang_string($identifier, $component, $a);
6895 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
6896 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
6899 // There is now a forth argument again, this time it is a boolean however so
6900 // we can still check for the old extralocations parameter.
6901 if (!is_bool($lazyload) && !empty($lazyload)) {
6902 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6905 if (strpos($component, '/') !== false) {
6906 debugging('The module name you passed to get_string is the deprecated format ' .
6907 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
6908 $componentpath = explode('/', $component);
6910 switch ($componentpath[0]) {
6911 case 'mod':
6912 $component = $componentpath[1];
6913 break;
6914 case 'blocks':
6915 case 'block':
6916 $component = 'block_'.$componentpath[1];
6917 break;
6918 case 'enrol':
6919 $component = 'enrol_'.$componentpath[1];
6920 break;
6921 case 'format':
6922 $component = 'format_'.$componentpath[1];
6923 break;
6924 case 'grade':
6925 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6926 break;
6930 $result = get_string_manager()->get_string($identifier, $component, $a);
6932 // Debugging feature lets you display string identifier and component.
6933 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
6934 $result .= ' {' . $identifier . '/' . $component . '}';
6936 return $result;
6940 * Converts an array of strings to their localized value.
6942 * @param array $array An array of strings
6943 * @param string $component The language module that these strings can be found in.
6944 * @return stdClass translated strings.
6946 function get_strings($array, $component = '') {
6947 $string = new stdClass;
6948 foreach ($array as $item) {
6949 $string->$item = get_string($item, $component);
6951 return $string;
6955 * Prints out a translated string.
6957 * Prints out a translated string using the return value from the {@link get_string()} function.
6959 * Example usage of this function when the string is in the moodle.php file:<br/>
6960 * <code>
6961 * echo '<strong>';
6962 * print_string('course');
6963 * echo '</strong>';
6964 * </code>
6966 * Example usage of this function when the string is not in the moodle.php file:<br/>
6967 * <code>
6968 * echo '<h1>';
6969 * print_string('typecourse', 'calendar');
6970 * echo '</h1>';
6971 * </code>
6973 * @category string
6974 * @param string $identifier The key identifier for the localized string
6975 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
6976 * @param string|object|array $a An object, string or number that can be used within translation strings
6978 function print_string($identifier, $component = '', $a = null) {
6979 echo get_string($identifier, $component, $a);
6983 * Returns a list of charset codes
6985 * Returns a list of charset codes. It's hardcoded, so they should be added manually
6986 * (checking that such charset is supported by the texlib library!)
6988 * @return array And associative array with contents in the form of charset => charset
6990 function get_list_of_charsets() {
6992 $charsets = array(
6993 'EUC-JP' => 'EUC-JP',
6994 'ISO-2022-JP'=> 'ISO-2022-JP',
6995 'ISO-8859-1' => 'ISO-8859-1',
6996 'SHIFT-JIS' => 'SHIFT-JIS',
6997 'GB2312' => 'GB2312',
6998 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
6999 'UTF-8' => 'UTF-8');
7001 asort($charsets);
7003 return $charsets;
7007 * Returns a list of valid and compatible themes
7009 * @return array
7011 function get_list_of_themes() {
7012 global $CFG;
7014 $themes = array();
7016 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7017 $themelist = explode(',', $CFG->themelist);
7018 } else {
7019 $themelist = array_keys(core_component::get_plugin_list("theme"));
7022 foreach ($themelist as $key => $themename) {
7023 $theme = theme_config::load($themename);
7024 $themes[$themename] = $theme;
7027 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7029 return $themes;
7033 * Factory function for emoticon_manager
7035 * @return emoticon_manager singleton
7037 function get_emoticon_manager() {
7038 static $singleton = null;
7040 if (is_null($singleton)) {
7041 $singleton = new emoticon_manager();
7044 return $singleton;
7048 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7050 * Whenever this manager mentiones 'emoticon object', the following data
7051 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7052 * altidentifier and altcomponent
7054 * @see admin_setting_emoticons
7056 * @copyright 2010 David Mudrak
7057 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7059 class emoticon_manager {
7062 * Returns the currently enabled emoticons
7064 * @return array of emoticon objects
7066 public function get_emoticons() {
7067 global $CFG;
7069 if (empty($CFG->emoticons)) {
7070 return array();
7073 $emoticons = $this->decode_stored_config($CFG->emoticons);
7075 if (!is_array($emoticons)) {
7076 // Something is wrong with the format of stored setting.
7077 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7078 return array();
7081 return $emoticons;
7085 * Converts emoticon object into renderable pix_emoticon object
7087 * @param stdClass $emoticon emoticon object
7088 * @param array $attributes explicit HTML attributes to set
7089 * @return pix_emoticon
7091 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7092 $stringmanager = get_string_manager();
7093 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7094 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7095 } else {
7096 $alt = s($emoticon->text);
7098 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7102 * Encodes the array of emoticon objects into a string storable in config table
7104 * @see self::decode_stored_config()
7105 * @param array $emoticons array of emtocion objects
7106 * @return string
7108 public function encode_stored_config(array $emoticons) {
7109 return json_encode($emoticons);
7113 * Decodes the string into an array of emoticon objects
7115 * @see self::encode_stored_config()
7116 * @param string $encoded
7117 * @return string|null
7119 public function decode_stored_config($encoded) {
7120 $decoded = json_decode($encoded);
7121 if (!is_array($decoded)) {
7122 return null;
7124 return $decoded;
7128 * Returns default set of emoticons supported by Moodle
7130 * @return array of sdtClasses
7132 public function default_emoticons() {
7133 return array(
7134 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7135 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7136 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7137 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7138 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7139 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7140 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7141 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7142 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7143 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7144 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7145 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7146 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7147 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7148 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7149 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7150 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7151 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7152 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7153 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7154 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7155 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7156 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7157 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7158 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7159 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7160 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7161 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7162 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7163 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7168 * Helper method preparing the stdClass with the emoticon properties
7170 * @param string|array $text or array of strings
7171 * @param string $imagename to be used by {@link pix_emoticon}
7172 * @param string $altidentifier alternative string identifier, null for no alt
7173 * @param string $altcomponent where the alternative string is defined
7174 * @param string $imagecomponent to be used by {@link pix_emoticon}
7175 * @return stdClass
7177 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7178 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7179 return (object)array(
7180 'text' => $text,
7181 'imagename' => $imagename,
7182 'imagecomponent' => $imagecomponent,
7183 'altidentifier' => $altidentifier,
7184 'altcomponent' => $altcomponent,
7189 // ENCRYPTION.
7192 * rc4encrypt
7194 * @param string $data Data to encrypt.
7195 * @return string The now encrypted data.
7197 function rc4encrypt($data) {
7198 return endecrypt(get_site_identifier(), $data, '');
7202 * rc4decrypt
7204 * @param string $data Data to decrypt.
7205 * @return string The now decrypted data.
7207 function rc4decrypt($data) {
7208 return endecrypt(get_site_identifier(), $data, 'de');
7212 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7214 * @todo Finish documenting this function
7216 * @param string $pwd The password to use when encrypting or decrypting
7217 * @param string $data The data to be decrypted/encrypted
7218 * @param string $case Either 'de' for decrypt or '' for encrypt
7219 * @return string
7221 function endecrypt ($pwd, $data, $case) {
7223 if ($case == 'de') {
7224 $data = urldecode($data);
7227 $key[] = '';
7228 $box[] = '';
7229 $pwdlength = strlen($pwd);
7231 for ($i = 0; $i <= 255; $i++) {
7232 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7233 $box[$i] = $i;
7236 $x = 0;
7238 for ($i = 0; $i <= 255; $i++) {
7239 $x = ($x + $box[$i] + $key[$i]) % 256;
7240 $tempswap = $box[$i];
7241 $box[$i] = $box[$x];
7242 $box[$x] = $tempswap;
7245 $cipher = '';
7247 $a = 0;
7248 $j = 0;
7250 for ($i = 0; $i < strlen($data); $i++) {
7251 $a = ($a + 1) % 256;
7252 $j = ($j + $box[$a]) % 256;
7253 $temp = $box[$a];
7254 $box[$a] = $box[$j];
7255 $box[$j] = $temp;
7256 $k = $box[(($box[$a] + $box[$j]) % 256)];
7257 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7258 $cipher .= chr($cipherby);
7261 if ($case == 'de') {
7262 $cipher = urldecode(urlencode($cipher));
7263 } else {
7264 $cipher = urlencode($cipher);
7267 return $cipher;
7270 // ENVIRONMENT CHECKING.
7273 * This method validates a plug name. It is much faster than calling clean_param.
7275 * @param string $name a string that might be a plugin name.
7276 * @return bool if this string is a valid plugin name.
7278 function is_valid_plugin_name($name) {
7279 // This does not work for 'mod', bad luck, use any other type.
7280 return core_component::is_valid_plugin_name('tool', $name);
7284 * Get a list of all the plugins of a given type that define a certain API function
7285 * in a certain file. The plugin component names and function names are returned.
7287 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7288 * @param string $function the part of the name of the function after the
7289 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7290 * names like report_courselist_hook.
7291 * @param string $file the name of file within the plugin that defines the
7292 * function. Defaults to lib.php.
7293 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7294 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7296 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7297 global $CFG;
7299 // We don't include here as all plugin types files would be included.
7300 $plugins = get_plugins_with_function($function, $file, false);
7302 if (empty($plugins[$plugintype])) {
7303 return array();
7306 $allplugins = core_component::get_plugin_list($plugintype);
7308 // Reformat the array and include the files.
7309 $pluginfunctions = array();
7310 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7312 // Check that it has not been removed and the file is still available.
7313 if (!empty($allplugins[$pluginname])) {
7315 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7316 if (file_exists($filepath)) {
7317 include_once($filepath);
7318 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7323 return $pluginfunctions;
7327 * Get a list of all the plugins that define a certain API function in a certain file.
7329 * @param string $function the part of the name of the function after the
7330 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7331 * names like report_courselist_hook.
7332 * @param string $file the name of file within the plugin that defines the
7333 * function. Defaults to lib.php.
7334 * @param bool $include Whether to include the files that contain the functions or not.
7335 * @return array with [plugintype][plugin] = functionname
7337 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7338 global $CFG;
7340 $cache = \cache::make('core', 'plugin_functions');
7342 // Including both although I doubt that we will find two functions definitions with the same name.
7343 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7344 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7346 if ($pluginfunctions = $cache->get($key)) {
7348 // Checking that the files are still available.
7349 foreach ($pluginfunctions as $plugintype => $plugins) {
7351 $allplugins = \core_component::get_plugin_list($plugintype);
7352 foreach ($plugins as $plugin => $fullpath) {
7354 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7355 if (empty($allplugins[$plugin])) {
7356 unset($pluginfunctions[$plugintype][$plugin]);
7357 continue;
7360 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7361 if ($include && $fileexists) {
7362 // Include the files if it was requested.
7363 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7364 } else if (!$fileexists) {
7365 // If the file is not available any more it should not be returned.
7366 unset($pluginfunctions[$plugintype][$plugin]);
7370 return $pluginfunctions;
7373 $pluginfunctions = array();
7375 // To fill the cached. Also, everything should continue working with cache disabled.
7376 $plugintypes = \core_component::get_plugin_types();
7377 foreach ($plugintypes as $plugintype => $unused) {
7379 // We need to include files here.
7380 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7381 foreach ($pluginswithfile as $plugin => $notused) {
7383 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7385 $pluginfunction = false;
7386 if (function_exists($fullfunction)) {
7387 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7388 $pluginfunction = $fullfunction;
7390 } else if ($plugintype === 'mod') {
7391 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7392 $shortfunction = $plugin . '_' . $function;
7393 if (function_exists($shortfunction)) {
7394 $pluginfunction = $shortfunction;
7398 if ($pluginfunction) {
7399 if (empty($pluginfunctions[$plugintype])) {
7400 $pluginfunctions[$plugintype] = array();
7402 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7407 $cache->set($key, $pluginfunctions);
7409 return $pluginfunctions;
7414 * Lists plugin-like directories within specified directory
7416 * This function was originally used for standard Moodle plugins, please use
7417 * new core_component::get_plugin_list() now.
7419 * This function is used for general directory listing and backwards compatility.
7421 * @param string $directory relative directory from root
7422 * @param string $exclude dir name to exclude from the list (defaults to none)
7423 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7424 * @return array Sorted array of directory names found under the requested parameters
7426 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7427 global $CFG;
7429 $plugins = array();
7431 if (empty($basedir)) {
7432 $basedir = $CFG->dirroot .'/'. $directory;
7434 } else {
7435 $basedir = $basedir .'/'. $directory;
7438 if ($CFG->debugdeveloper and empty($exclude)) {
7439 // Make sure devs do not use this to list normal plugins,
7440 // this is intended for general directories that are not plugins!
7442 $subtypes = core_component::get_plugin_types();
7443 if (in_array($basedir, $subtypes)) {
7444 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7446 unset($subtypes);
7449 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7450 if (!$dirhandle = opendir($basedir)) {
7451 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7452 return array();
7454 while (false !== ($dir = readdir($dirhandle))) {
7455 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7456 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7457 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7458 continue;
7460 if (filetype($basedir .'/'. $dir) != 'dir') {
7461 continue;
7463 $plugins[] = $dir;
7465 closedir($dirhandle);
7467 if ($plugins) {
7468 asort($plugins);
7470 return $plugins;
7474 * Invoke plugin's callback functions
7476 * @param string $type plugin type e.g. 'mod'
7477 * @param string $name plugin name
7478 * @param string $feature feature name
7479 * @param string $action feature's action
7480 * @param array $params parameters of callback function, should be an array
7481 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7482 * @return mixed
7484 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7486 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7487 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7491 * Invoke component's callback functions
7493 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7494 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7495 * @param array $params parameters of callback function
7496 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7497 * @return mixed
7499 function component_callback($component, $function, array $params = array(), $default = null) {
7501 $functionname = component_callback_exists($component, $function);
7503 if ($functionname) {
7504 // Function exists, so just return function result.
7505 $ret = call_user_func_array($functionname, $params);
7506 if (is_null($ret)) {
7507 return $default;
7508 } else {
7509 return $ret;
7512 return $default;
7516 * Determine if a component callback exists and return the function name to call. Note that this
7517 * function will include the required library files so that the functioname returned can be
7518 * called directly.
7520 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7521 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7522 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7523 * @throws coding_exception if invalid component specfied
7525 function component_callback_exists($component, $function) {
7526 global $CFG; // This is needed for the inclusions.
7528 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7529 if (empty($cleancomponent)) {
7530 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7532 $component = $cleancomponent;
7534 list($type, $name) = core_component::normalize_component($component);
7535 $component = $type . '_' . $name;
7537 $oldfunction = $name.'_'.$function;
7538 $function = $component.'_'.$function;
7540 $dir = core_component::get_component_directory($component);
7541 if (empty($dir)) {
7542 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7545 // Load library and look for function.
7546 if (file_exists($dir.'/lib.php')) {
7547 require_once($dir.'/lib.php');
7550 if (!function_exists($function) and function_exists($oldfunction)) {
7551 if ($type !== 'mod' and $type !== 'core') {
7552 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7554 $function = $oldfunction;
7557 if (function_exists($function)) {
7558 return $function;
7560 return false;
7564 * Checks whether a plugin supports a specified feature.
7566 * @param string $type Plugin type e.g. 'mod'
7567 * @param string $name Plugin name e.g. 'forum'
7568 * @param string $feature Feature code (FEATURE_xx constant)
7569 * @param mixed $default default value if feature support unknown
7570 * @return mixed Feature result (false if not supported, null if feature is unknown,
7571 * otherwise usually true but may have other feature-specific value such as array)
7572 * @throws coding_exception
7574 function plugin_supports($type, $name, $feature, $default = null) {
7575 global $CFG;
7577 if ($type === 'mod' and $name === 'NEWMODULE') {
7578 // Somebody forgot to rename the module template.
7579 return false;
7582 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7583 if (empty($component)) {
7584 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7587 $function = null;
7589 if ($type === 'mod') {
7590 // We need this special case because we support subplugins in modules,
7591 // otherwise it would end up in infinite loop.
7592 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7593 include_once("$CFG->dirroot/mod/$name/lib.php");
7594 $function = $component.'_supports';
7595 if (!function_exists($function)) {
7596 // Legacy non-frankenstyle function name.
7597 $function = $name.'_supports';
7601 } else {
7602 if (!$path = core_component::get_plugin_directory($type, $name)) {
7603 // Non existent plugin type.
7604 return false;
7606 if (file_exists("$path/lib.php")) {
7607 include_once("$path/lib.php");
7608 $function = $component.'_supports';
7612 if ($function and function_exists($function)) {
7613 $supports = $function($feature);
7614 if (is_null($supports)) {
7615 // Plugin does not know - use default.
7616 return $default;
7617 } else {
7618 return $supports;
7622 // Plugin does not care, so use default.
7623 return $default;
7627 * Returns true if the current version of PHP is greater that the specified one.
7629 * @todo Check PHP version being required here is it too low?
7631 * @param string $version The version of php being tested.
7632 * @return bool
7634 function check_php_version($version='5.2.4') {
7635 return (version_compare(phpversion(), $version) >= 0);
7639 * Determine if moodle installation requires update.
7641 * Checks version numbers of main code and all plugins to see
7642 * if there are any mismatches.
7644 * @return bool
7646 function moodle_needs_upgrading() {
7647 global $CFG;
7649 if (empty($CFG->version)) {
7650 return true;
7653 // There is no need to purge plugininfo caches here because
7654 // these caches are not used during upgrade and they are purged after
7655 // every upgrade.
7657 if (empty($CFG->allversionshash)) {
7658 return true;
7661 $hash = core_component::get_all_versions_hash();
7663 return ($hash !== $CFG->allversionshash);
7667 * Returns the major version of this site
7669 * Moodle version numbers consist of three numbers separated by a dot, for
7670 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7671 * called major version. This function extracts the major version from either
7672 * $CFG->release (default) or eventually from the $release variable defined in
7673 * the main version.php.
7675 * @param bool $fromdisk should the version if source code files be used
7676 * @return string|false the major version like '2.3', false if could not be determined
7678 function moodle_major_version($fromdisk = false) {
7679 global $CFG;
7681 if ($fromdisk) {
7682 $release = null;
7683 require($CFG->dirroot.'/version.php');
7684 if (empty($release)) {
7685 return false;
7688 } else {
7689 if (empty($CFG->release)) {
7690 return false;
7692 $release = $CFG->release;
7695 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7696 return $matches[0];
7697 } else {
7698 return false;
7702 // MISCELLANEOUS.
7705 * Sets the system locale
7707 * @category string
7708 * @param string $locale Can be used to force a locale
7710 function moodle_setlocale($locale='') {
7711 global $CFG;
7713 static $currentlocale = ''; // Last locale caching.
7715 $oldlocale = $currentlocale;
7717 // Fetch the correct locale based on ostype.
7718 if ($CFG->ostype == 'WINDOWS') {
7719 $stringtofetch = 'localewin';
7720 } else {
7721 $stringtofetch = 'locale';
7724 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7725 if (!empty($locale)) {
7726 $currentlocale = $locale;
7727 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7728 $currentlocale = $CFG->locale;
7729 } else {
7730 $currentlocale = get_string($stringtofetch, 'langconfig');
7733 // Do nothing if locale already set up.
7734 if ($oldlocale == $currentlocale) {
7735 return;
7738 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7739 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7740 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7742 // Get current values.
7743 $monetary= setlocale (LC_MONETARY, 0);
7744 $numeric = setlocale (LC_NUMERIC, 0);
7745 $ctype = setlocale (LC_CTYPE, 0);
7746 if ($CFG->ostype != 'WINDOWS') {
7747 $messages= setlocale (LC_MESSAGES, 0);
7749 // Set locale to all.
7750 $result = setlocale (LC_ALL, $currentlocale);
7751 // If setting of locale fails try the other utf8 or utf-8 variant,
7752 // some operating systems support both (Debian), others just one (OSX).
7753 if ($result === false) {
7754 if (stripos($currentlocale, '.UTF-8') !== false) {
7755 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7756 setlocale (LC_ALL, $newlocale);
7757 } else if (stripos($currentlocale, '.UTF8') !== false) {
7758 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7759 setlocale (LC_ALL, $newlocale);
7762 // Set old values.
7763 setlocale (LC_MONETARY, $monetary);
7764 setlocale (LC_NUMERIC, $numeric);
7765 if ($CFG->ostype != 'WINDOWS') {
7766 setlocale (LC_MESSAGES, $messages);
7768 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7769 // To workaround a well-known PHP problem with Turkish letter Ii.
7770 setlocale (LC_CTYPE, $ctype);
7775 * Count words in a string.
7777 * Words are defined as things between whitespace.
7779 * @category string
7780 * @param string $string The text to be searched for words.
7781 * @return int The count of words in the specified string
7783 function count_words($string) {
7784 $string = strip_tags($string);
7785 // Decode HTML entities.
7786 $string = html_entity_decode($string);
7787 // Replace underscores (which are classed as word characters) with spaces.
7788 $string = preg_replace('/_/u', ' ', $string);
7789 // Remove any characters that shouldn't be treated as word boundaries.
7790 $string = preg_replace('/[\'"’-]/u', '', $string);
7791 // Remove dots and commas from within numbers only.
7792 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7794 return count(preg_split('/\w\b/u', $string)) - 1;
7798 * Count letters in a string.
7800 * Letters are defined as chars not in tags and different from whitespace.
7802 * @category string
7803 * @param string $string The text to be searched for letters.
7804 * @return int The count of letters in the specified text.
7806 function count_letters($string) {
7807 $string = strip_tags($string); // Tags are out now.
7808 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7810 return core_text::strlen($string);
7814 * Generate and return a random string of the specified length.
7816 * @param int $length The length of the string to be created.
7817 * @return string
7819 function random_string($length=15) {
7820 $randombytes = random_bytes_emulate($length);
7821 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7822 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7823 $pool .= '0123456789';
7824 $poollen = strlen($pool);
7825 $string = '';
7826 for ($i = 0; $i < $length; $i++) {
7827 $rand = ord($randombytes[$i]);
7828 $string .= substr($pool, ($rand%($poollen)), 1);
7830 return $string;
7834 * Generate a complex random string (useful for md5 salts)
7836 * This function is based on the above {@link random_string()} however it uses a
7837 * larger pool of characters and generates a string between 24 and 32 characters
7839 * @param int $length Optional if set generates a string to exactly this length
7840 * @return string
7842 function complex_random_string($length=null) {
7843 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7844 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7845 $poollen = strlen($pool);
7846 if ($length===null) {
7847 $length = floor(rand(24, 32));
7849 $randombytes = random_bytes_emulate($length);
7850 $string = '';
7851 for ($i = 0; $i < $length; $i++) {
7852 $rand = ord($randombytes[$i]);
7853 $string .= $pool[($rand%$poollen)];
7855 return $string;
7859 * Try to generates cryptographically secure pseudo-random bytes.
7861 * Note this is achieved by fallbacking between:
7862 * - PHP 7 random_bytes().
7863 * - OpenSSL openssl_random_pseudo_bytes().
7864 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
7866 * @param int $length requested length in bytes
7867 * @return string binary data
7869 function random_bytes_emulate($length) {
7870 global $CFG;
7871 if ($length <= 0) {
7872 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
7873 return '';
7875 if (function_exists('random_bytes')) {
7876 // Use PHP 7 goodness.
7877 $hash = @random_bytes($length);
7878 if ($hash !== false) {
7879 return $hash;
7882 if (function_exists('openssl_random_pseudo_bytes')) {
7883 // For PHP 5.3 and later with openssl extension.
7884 $hash = openssl_random_pseudo_bytes($length);
7885 if ($hash !== false) {
7886 return $hash;
7890 // Bad luck, there is no reliable random generator, let's just hash some unique stuff that is hard to guess.
7891 $staticdata = serialize($CFG) . serialize($_SERVER);
7892 $hash = '';
7893 do {
7894 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
7895 } while (strlen($hash) < $length);
7896 return substr($hash, 0, $length);
7900 * Given some text (which may contain HTML) and an ideal length,
7901 * this function truncates the text neatly on a word boundary if possible
7903 * @category string
7904 * @param string $text text to be shortened
7905 * @param int $ideal ideal string length
7906 * @param boolean $exact if false, $text will not be cut mid-word
7907 * @param string $ending The string to append if the passed string is truncated
7908 * @return string $truncate shortened string
7910 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7911 // If the plain text is shorter than the maximum length, return the whole text.
7912 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7913 return $text;
7916 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7917 // and only tag in its 'line'.
7918 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
7920 $totallength = core_text::strlen($ending);
7921 $truncate = '';
7923 // This array stores information about open and close tags and their position
7924 // in the truncated string. Each item in the array is an object with fields
7925 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7926 // (byte position in truncated text).
7927 $tagdetails = array();
7929 foreach ($lines as $linematchings) {
7930 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7931 if (!empty($linematchings[1])) {
7932 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7933 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7934 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7935 // Record closing tag.
7936 $tagdetails[] = (object) array(
7937 'open' => false,
7938 'tag' => core_text::strtolower($tagmatchings[1]),
7939 'pos' => core_text::strlen($truncate),
7942 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7943 // Record opening tag.
7944 $tagdetails[] = (object) array(
7945 'open' => true,
7946 'tag' => core_text::strtolower($tagmatchings[1]),
7947 'pos' => core_text::strlen($truncate),
7949 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
7950 $tagdetails[] = (object) array(
7951 'open' => true,
7952 'tag' => core_text::strtolower('if'),
7953 'pos' => core_text::strlen($truncate),
7955 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
7956 $tagdetails[] = (object) array(
7957 'open' => false,
7958 'tag' => core_text::strtolower('if'),
7959 'pos' => core_text::strlen($truncate),
7963 // Add html-tag to $truncate'd text.
7964 $truncate .= $linematchings[1];
7967 // Calculate the length of the plain text part of the line; handle entities as one character.
7968 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7969 if ($totallength + $contentlength > $ideal) {
7970 // The number of characters which are left.
7971 $left = $ideal - $totallength;
7972 $entitieslength = 0;
7973 // Search for html entities.
7974 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)) {
7975 // Calculate the real length of all entities in the legal range.
7976 foreach ($entities[0] as $entity) {
7977 if ($entity[1]+1-$entitieslength <= $left) {
7978 $left--;
7979 $entitieslength += core_text::strlen($entity[0]);
7980 } else {
7981 // No more characters left.
7982 break;
7986 $breakpos = $left + $entitieslength;
7988 // If the words shouldn't be cut in the middle...
7989 if (!$exact) {
7990 // Search the last occurence of a space.
7991 for (; $breakpos > 0; $breakpos--) {
7992 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
7993 if ($char === '.' or $char === ' ') {
7994 $breakpos += 1;
7995 break;
7996 } else if (strlen($char) > 2) {
7997 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7998 $breakpos += 1;
7999 break;
8004 if ($breakpos == 0) {
8005 // This deals with the test_shorten_text_no_spaces case.
8006 $breakpos = $left + $entitieslength;
8007 } else if ($breakpos > $left + $entitieslength) {
8008 // This deals with the previous for loop breaking on the first char.
8009 $breakpos = $left + $entitieslength;
8012 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8013 // Maximum length is reached, so get off the loop.
8014 break;
8015 } else {
8016 $truncate .= $linematchings[2];
8017 $totallength += $contentlength;
8020 // If the maximum length is reached, get off the loop.
8021 if ($totallength >= $ideal) {
8022 break;
8026 // Add the defined ending to the text.
8027 $truncate .= $ending;
8029 // Now calculate the list of open html tags based on the truncate position.
8030 $opentags = array();
8031 foreach ($tagdetails as $taginfo) {
8032 if ($taginfo->open) {
8033 // Add tag to the beginning of $opentags list.
8034 array_unshift($opentags, $taginfo->tag);
8035 } else {
8036 // Can have multiple exact same open tags, close the last one.
8037 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8038 if ($pos !== false) {
8039 unset($opentags[$pos]);
8044 // Close all unclosed html-tags.
8045 foreach ($opentags as $tag) {
8046 if ($tag === 'if') {
8047 $truncate .= '<!--<![endif]-->';
8048 } else {
8049 $truncate .= '</' . $tag . '>';
8053 return $truncate;
8058 * Given dates in seconds, how many weeks is the date from startdate
8059 * The first week is 1, the second 2 etc ...
8061 * @param int $startdate Timestamp for the start date
8062 * @param int $thedate Timestamp for the end date
8063 * @return string
8065 function getweek ($startdate, $thedate) {
8066 if ($thedate < $startdate) {
8067 return 0;
8070 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8074 * Returns a randomly generated password of length $maxlen. inspired by
8076 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8077 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8079 * @param int $maxlen The maximum size of the password being generated.
8080 * @return string
8082 function generate_password($maxlen=10) {
8083 global $CFG;
8085 if (empty($CFG->passwordpolicy)) {
8086 $fillers = PASSWORD_DIGITS;
8087 $wordlist = file($CFG->wordlist);
8088 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8089 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8090 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8091 $password = $word1 . $filler1 . $word2;
8092 } else {
8093 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8094 $digits = $CFG->minpassworddigits;
8095 $lower = $CFG->minpasswordlower;
8096 $upper = $CFG->minpasswordupper;
8097 $nonalphanum = $CFG->minpasswordnonalphanum;
8098 $total = $lower + $upper + $digits + $nonalphanum;
8099 // Var minlength should be the greater one of the two ( $minlen and $total ).
8100 $minlen = $minlen < $total ? $total : $minlen;
8101 // Var maxlen can never be smaller than minlen.
8102 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8103 $additional = $maxlen - $total;
8105 // Make sure we have enough characters to fulfill
8106 // complexity requirements.
8107 $passworddigits = PASSWORD_DIGITS;
8108 while ($digits > strlen($passworddigits)) {
8109 $passworddigits .= PASSWORD_DIGITS;
8111 $passwordlower = PASSWORD_LOWER;
8112 while ($lower > strlen($passwordlower)) {
8113 $passwordlower .= PASSWORD_LOWER;
8115 $passwordupper = PASSWORD_UPPER;
8116 while ($upper > strlen($passwordupper)) {
8117 $passwordupper .= PASSWORD_UPPER;
8119 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8120 while ($nonalphanum > strlen($passwordnonalphanum)) {
8121 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8124 // Now mix and shuffle it all.
8125 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8126 substr(str_shuffle ($passwordupper), 0, $upper) .
8127 substr(str_shuffle ($passworddigits), 0, $digits) .
8128 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8129 substr(str_shuffle ($passwordlower .
8130 $passwordupper .
8131 $passworddigits .
8132 $passwordnonalphanum), 0 , $additional));
8135 return substr ($password, 0, $maxlen);
8139 * Given a float, prints it nicely.
8140 * Localized floats must not be used in calculations!
8142 * The stripzeros feature is intended for making numbers look nicer in small
8143 * areas where it is not necessary to indicate the degree of accuracy by showing
8144 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8145 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8147 * @param float $float The float to print
8148 * @param int $decimalpoints The number of decimal places to print.
8149 * @param bool $localized use localized decimal separator
8150 * @param bool $stripzeros If true, removes final zeros after decimal point
8151 * @return string locale float
8153 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8154 if (is_null($float)) {
8155 return '';
8157 if ($localized) {
8158 $separator = get_string('decsep', 'langconfig');
8159 } else {
8160 $separator = '.';
8162 $result = number_format($float, $decimalpoints, $separator, '');
8163 if ($stripzeros) {
8164 // Remove zeros and final dot if not needed.
8165 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8167 return $result;
8171 * Converts locale specific floating point/comma number back to standard PHP float value
8172 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8174 * @param string $localefloat locale aware float representation
8175 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8176 * @return mixed float|bool - false or the parsed float.
8178 function unformat_float($localefloat, $strict = false) {
8179 $localefloat = trim($localefloat);
8181 if ($localefloat == '') {
8182 return null;
8185 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8186 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8188 if ($strict && !is_numeric($localefloat)) {
8189 return false;
8192 return (float)$localefloat;
8196 * Given a simple array, this shuffles it up just like shuffle()
8197 * Unlike PHP's shuffle() this function works on any machine.
8199 * @param array $array The array to be rearranged
8200 * @return array
8202 function swapshuffle($array) {
8204 $last = count($array) - 1;
8205 for ($i = 0; $i <= $last; $i++) {
8206 $from = rand(0, $last);
8207 $curr = $array[$i];
8208 $array[$i] = $array[$from];
8209 $array[$from] = $curr;
8211 return $array;
8215 * Like {@link swapshuffle()}, but works on associative arrays
8217 * @param array $array The associative array to be rearranged
8218 * @return array
8220 function swapshuffle_assoc($array) {
8222 $newarray = array();
8223 $newkeys = swapshuffle(array_keys($array));
8225 foreach ($newkeys as $newkey) {
8226 $newarray[$newkey] = $array[$newkey];
8228 return $newarray;
8232 * Given an arbitrary array, and a number of draws,
8233 * this function returns an array with that amount
8234 * of items. The indexes are retained.
8236 * @todo Finish documenting this function
8238 * @param array $array
8239 * @param int $draws
8240 * @return array
8242 function draw_rand_array($array, $draws) {
8244 $return = array();
8246 $last = count($array);
8248 if ($draws > $last) {
8249 $draws = $last;
8252 while ($draws > 0) {
8253 $last--;
8255 $keys = array_keys($array);
8256 $rand = rand(0, $last);
8258 $return[$keys[$rand]] = $array[$keys[$rand]];
8259 unset($array[$keys[$rand]]);
8261 $draws--;
8264 return $return;
8268 * Calculate the difference between two microtimes
8270 * @param string $a The first Microtime
8271 * @param string $b The second Microtime
8272 * @return string
8274 function microtime_diff($a, $b) {
8275 list($adec, $asec) = explode(' ', $a);
8276 list($bdec, $bsec) = explode(' ', $b);
8277 return $bsec - $asec + $bdec - $adec;
8281 * Given a list (eg a,b,c,d,e) this function returns
8282 * an array of 1->a, 2->b, 3->c etc
8284 * @param string $list The string to explode into array bits
8285 * @param string $separator The separator used within the list string
8286 * @return array The now assembled array
8288 function make_menu_from_list($list, $separator=',') {
8290 $array = array_reverse(explode($separator, $list), true);
8291 foreach ($array as $key => $item) {
8292 $outarray[$key+1] = trim($item);
8294 return $outarray;
8298 * Creates an array that represents all the current grades that
8299 * can be chosen using the given grading type.
8301 * Negative numbers
8302 * are scales, zero is no grade, and positive numbers are maximum
8303 * grades.
8305 * @todo Finish documenting this function or better deprecated this completely!
8307 * @param int $gradingtype
8308 * @return array
8310 function make_grades_menu($gradingtype) {
8311 global $DB;
8313 $grades = array();
8314 if ($gradingtype < 0) {
8315 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8316 return make_menu_from_list($scale->scale);
8318 } else if ($gradingtype > 0) {
8319 for ($i=$gradingtype; $i>=0; $i--) {
8320 $grades[$i] = $i .' / '. $gradingtype;
8322 return $grades;
8324 return $grades;
8328 * make_unique_id_code
8330 * @todo Finish documenting this function
8332 * @uses $_SERVER
8333 * @param string $extra Extra string to append to the end of the code
8334 * @return string
8336 function make_unique_id_code($extra = '') {
8338 $hostname = 'unknownhost';
8339 if (!empty($_SERVER['HTTP_HOST'])) {
8340 $hostname = $_SERVER['HTTP_HOST'];
8341 } else if (!empty($_ENV['HTTP_HOST'])) {
8342 $hostname = $_ENV['HTTP_HOST'];
8343 } else if (!empty($_SERVER['SERVER_NAME'])) {
8344 $hostname = $_SERVER['SERVER_NAME'];
8345 } else if (!empty($_ENV['SERVER_NAME'])) {
8346 $hostname = $_ENV['SERVER_NAME'];
8349 $date = gmdate("ymdHis");
8351 $random = random_string(6);
8353 if ($extra) {
8354 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8355 } else {
8356 return $hostname .'+'. $date .'+'. $random;
8362 * Function to check the passed address is within the passed subnet
8364 * The parameter is a comma separated string of subnet definitions.
8365 * Subnet strings can be in one of three formats:
8366 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8367 * 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)
8368 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8369 * Code for type 1 modified from user posted comments by mediator at
8370 * {@link http://au.php.net/manual/en/function.ip2long.php}
8372 * @param string $addr The address you are checking
8373 * @param string $subnetstr The string of subnet addresses
8374 * @return bool
8376 function address_in_subnet($addr, $subnetstr) {
8378 if ($addr == '0.0.0.0') {
8379 return false;
8381 $subnets = explode(',', $subnetstr);
8382 $found = false;
8383 $addr = trim($addr);
8384 $addr = cleanremoteaddr($addr, false); // Normalise.
8385 if ($addr === null) {
8386 return false;
8388 $addrparts = explode(':', $addr);
8390 $ipv6 = strpos($addr, ':');
8392 foreach ($subnets as $subnet) {
8393 $subnet = trim($subnet);
8394 if ($subnet === '') {
8395 continue;
8398 if (strpos($subnet, '/') !== false) {
8399 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8400 list($ip, $mask) = explode('/', $subnet);
8401 $mask = trim($mask);
8402 if (!is_number($mask)) {
8403 continue; // Incorect mask number, eh?
8405 $ip = cleanremoteaddr($ip, false); // Normalise.
8406 if ($ip === null) {
8407 continue;
8409 if (strpos($ip, ':') !== false) {
8410 // IPv6.
8411 if (!$ipv6) {
8412 continue;
8414 if ($mask > 128 or $mask < 0) {
8415 continue; // Nonsense.
8417 if ($mask == 0) {
8418 return true; // Any address.
8420 if ($mask == 128) {
8421 if ($ip === $addr) {
8422 return true;
8424 continue;
8426 $ipparts = explode(':', $ip);
8427 $modulo = $mask % 16;
8428 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8429 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8430 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8431 if ($modulo == 0) {
8432 return true;
8434 $pos = ($mask-$modulo)/16;
8435 $ipnet = hexdec($ipparts[$pos]);
8436 $addrnet = hexdec($addrparts[$pos]);
8437 $mask = 0xffff << (16 - $modulo);
8438 if (($addrnet & $mask) == ($ipnet & $mask)) {
8439 return true;
8443 } else {
8444 // IPv4.
8445 if ($ipv6) {
8446 continue;
8448 if ($mask > 32 or $mask < 0) {
8449 continue; // Nonsense.
8451 if ($mask == 0) {
8452 return true;
8454 if ($mask == 32) {
8455 if ($ip === $addr) {
8456 return true;
8458 continue;
8460 $mask = 0xffffffff << (32 - $mask);
8461 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8462 return true;
8466 } else if (strpos($subnet, '-') !== false) {
8467 // 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.
8468 $parts = explode('-', $subnet);
8469 if (count($parts) != 2) {
8470 continue;
8473 if (strpos($subnet, ':') !== false) {
8474 // IPv6.
8475 if (!$ipv6) {
8476 continue;
8478 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8479 if ($ipstart === null) {
8480 continue;
8482 $ipparts = explode(':', $ipstart);
8483 $start = hexdec(array_pop($ipparts));
8484 $ipparts[] = trim($parts[1]);
8485 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8486 if ($ipend === null) {
8487 continue;
8489 $ipparts[7] = '';
8490 $ipnet = implode(':', $ipparts);
8491 if (strpos($addr, $ipnet) !== 0) {
8492 continue;
8494 $ipparts = explode(':', $ipend);
8495 $end = hexdec($ipparts[7]);
8497 $addrend = hexdec($addrparts[7]);
8499 if (($addrend >= $start) and ($addrend <= $end)) {
8500 return true;
8503 } else {
8504 // IPv4.
8505 if ($ipv6) {
8506 continue;
8508 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8509 if ($ipstart === null) {
8510 continue;
8512 $ipparts = explode('.', $ipstart);
8513 $ipparts[3] = trim($parts[1]);
8514 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8515 if ($ipend === null) {
8516 continue;
8519 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8520 return true;
8524 } else {
8525 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8526 if (strpos($subnet, ':') !== false) {
8527 // IPv6.
8528 if (!$ipv6) {
8529 continue;
8531 $parts = explode(':', $subnet);
8532 $count = count($parts);
8533 if ($parts[$count-1] === '') {
8534 unset($parts[$count-1]); // Trim trailing :'s.
8535 $count--;
8536 $subnet = implode('.', $parts);
8538 $isip = cleanremoteaddr($subnet, false); // Normalise.
8539 if ($isip !== null) {
8540 if ($isip === $addr) {
8541 return true;
8543 continue;
8544 } else if ($count > 8) {
8545 continue;
8547 $zeros = array_fill(0, 8-$count, '0');
8548 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8549 if (address_in_subnet($addr, $subnet)) {
8550 return true;
8553 } else {
8554 // IPv4.
8555 if ($ipv6) {
8556 continue;
8558 $parts = explode('.', $subnet);
8559 $count = count($parts);
8560 if ($parts[$count-1] === '') {
8561 unset($parts[$count-1]); // Trim trailing .
8562 $count--;
8563 $subnet = implode('.', $parts);
8565 if ($count == 4) {
8566 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8567 if ($subnet === $addr) {
8568 return true;
8570 continue;
8571 } else if ($count > 4) {
8572 continue;
8574 $zeros = array_fill(0, 4-$count, '0');
8575 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8576 if (address_in_subnet($addr, $subnet)) {
8577 return true;
8583 return false;
8587 * For outputting debugging info
8589 * @param string $string The string to write
8590 * @param string $eol The end of line char(s) to use
8591 * @param string $sleep Period to make the application sleep
8592 * This ensures any messages have time to display before redirect
8594 function mtrace($string, $eol="\n", $sleep=0) {
8596 if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
8597 fwrite(STDOUT, $string.$eol);
8598 } else {
8599 echo $string . $eol;
8602 flush();
8604 // Delay to keep message on user's screen in case of subsequent redirect.
8605 if ($sleep) {
8606 sleep($sleep);
8611 * Replace 1 or more slashes or backslashes to 1 slash
8613 * @param string $path The path to strip
8614 * @return string the path with double slashes removed
8616 function cleardoubleslashes ($path) {
8617 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8621 * Is current ip in give list?
8623 * @param string $list
8624 * @return bool
8626 function remoteip_in_list($list) {
8627 $inlist = false;
8628 $clientip = getremoteaddr(null);
8630 if (!$clientip) {
8631 // Ensure access on cli.
8632 return true;
8635 $list = explode("\n", $list);
8636 foreach ($list as $subnet) {
8637 $subnet = trim($subnet);
8638 if (address_in_subnet($clientip, $subnet)) {
8639 $inlist = true;
8640 break;
8643 return $inlist;
8647 * Returns most reliable client address
8649 * @param string $default If an address can't be determined, then return this
8650 * @return string The remote IP address
8652 function getremoteaddr($default='0.0.0.0') {
8653 global $CFG;
8655 if (empty($CFG->getremoteaddrconf)) {
8656 // This will happen, for example, before just after the upgrade, as the
8657 // user is redirected to the admin screen.
8658 $variablestoskip = 0;
8659 } else {
8660 $variablestoskip = $CFG->getremoteaddrconf;
8662 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8663 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8664 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8665 return $address ? $address : $default;
8668 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8669 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8670 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8671 $address = $forwardedaddresses[0];
8673 if (substr_count($address, ":") > 1) {
8674 // Remove port and brackets from IPv6.
8675 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8676 $address = $matches[1];
8678 } else {
8679 // Remove port from IPv4.
8680 if (substr_count($address, ":") == 1) {
8681 $parts = explode(":", $address);
8682 $address = $parts[0];
8686 $address = cleanremoteaddr($address);
8687 return $address ? $address : $default;
8690 if (!empty($_SERVER['REMOTE_ADDR'])) {
8691 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8692 return $address ? $address : $default;
8693 } else {
8694 return $default;
8699 * Cleans an ip address. Internal addresses are now allowed.
8700 * (Originally local addresses were not allowed.)
8702 * @param string $addr IPv4 or IPv6 address
8703 * @param bool $compress use IPv6 address compression
8704 * @return string normalised ip address string, null if error
8706 function cleanremoteaddr($addr, $compress=false) {
8707 $addr = trim($addr);
8709 // TODO: maybe add a separate function is_addr_public() or something like this.
8711 if (strpos($addr, ':') !== false) {
8712 // Can be only IPv6.
8713 $parts = explode(':', $addr);
8714 $count = count($parts);
8716 if (strpos($parts[$count-1], '.') !== false) {
8717 // Legacy ipv4 notation.
8718 $last = array_pop($parts);
8719 $ipv4 = cleanremoteaddr($last, true);
8720 if ($ipv4 === null) {
8721 return null;
8723 $bits = explode('.', $ipv4);
8724 $parts[] = dechex($bits[0]).dechex($bits[1]);
8725 $parts[] = dechex($bits[2]).dechex($bits[3]);
8726 $count = count($parts);
8727 $addr = implode(':', $parts);
8730 if ($count < 3 or $count > 8) {
8731 return null; // Severly malformed.
8734 if ($count != 8) {
8735 if (strpos($addr, '::') === false) {
8736 return null; // Malformed.
8738 // Uncompress.
8739 $insertat = array_search('', $parts, true);
8740 $missing = array_fill(0, 1 + 8 - $count, '0');
8741 array_splice($parts, $insertat, 1, $missing);
8742 foreach ($parts as $key => $part) {
8743 if ($part === '') {
8744 $parts[$key] = '0';
8749 $adr = implode(':', $parts);
8750 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8751 return null; // Incorrect format - sorry.
8754 // Normalise 0s and case.
8755 $parts = array_map('hexdec', $parts);
8756 $parts = array_map('dechex', $parts);
8758 $result = implode(':', $parts);
8760 if (!$compress) {
8761 return $result;
8764 if ($result === '0:0:0:0:0:0:0:0') {
8765 return '::'; // All addresses.
8768 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8769 if ($compressed !== $result) {
8770 return $compressed;
8773 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8774 if ($compressed !== $result) {
8775 return $compressed;
8778 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8779 if ($compressed !== $result) {
8780 return $compressed;
8783 return $result;
8786 // First get all things that look like IPv4 addresses.
8787 $parts = array();
8788 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8789 return null;
8791 unset($parts[0]);
8793 foreach ($parts as $key => $match) {
8794 if ($match > 255) {
8795 return null;
8797 $parts[$key] = (int)$match; // Normalise 0s.
8800 return implode('.', $parts);
8804 * This function will make a complete copy of anything it's given,
8805 * regardless of whether it's an object or not.
8807 * @param mixed $thing Something you want cloned
8808 * @return mixed What ever it is you passed it
8810 function fullclone($thing) {
8811 return unserialize(serialize($thing));
8815 * If new messages are waiting for the current user, then insert
8816 * JavaScript to pop up the messaging window into the page
8818 * @return void
8820 function message_popup_window() {
8821 global $USER, $DB, $PAGE, $CFG;
8823 if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
8824 return;
8827 if (!isloggedin() || isguestuser()) {
8828 return;
8831 if (!isset($USER->message_lastpopup)) {
8832 $USER->message_lastpopup = 0;
8833 } else if ($USER->message_lastpopup > (time()-120)) {
8834 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8835 return;
8838 // A quick query to check whether the user has new messages.
8839 $messagecount = $DB->count_records('message', array('useridto' => $USER->id));
8840 if ($messagecount < 1) {
8841 return;
8844 // There are unread messages so now do a more complex but slower query.
8845 $messagesql = "SELECT m.id, c.blocked
8846 FROM {message} m
8847 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8848 JOIN {message_processors} p ON mw.processorid=p.id
8849 LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
8850 AND c.userid = m.useridto
8851 WHERE m.useridto = :userid
8852 AND p.name='popup'";
8854 // If the user was last notified over an hour ago we can re-notify them of old messages
8855 // so don't worry about when the new message was sent.
8856 $lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
8857 if (!$lastnotifiedlongago) {
8858 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8861 $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id, 'lastpopuptime' => $USER->message_lastpopup));
8863 $validmessages = 0;
8864 foreach ($waitingmessages as $messageinfo) {
8865 if ($messageinfo->blocked) {
8866 // Message is from a user who has since been blocked so just mark it read.
8867 // Get the full message to mark as read.
8868 $messageobject = $DB->get_record('message', array('id' => $messageinfo->id));
8869 message_mark_message_read($messageobject, time());
8870 } else {
8871 $validmessages++;
8875 if ($validmessages > 0) {
8876 $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
8877 $strgomessage = get_string('gotomessages', 'message');
8878 $strstaymessage = get_string('ignore', 'admin');
8880 $notificationsound = null;
8881 $beep = get_user_preferences('message_beepnewmessage', '');
8882 if (!empty($beep)) {
8883 // Browsers will work down this list until they find something they support.
8884 $sourcetags = html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.wav', 'type' => 'audio/wav'));
8885 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.ogg', 'type' => 'audio/ogg'));
8886 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8887 $sourcetags .= html_writer::empty_tag('embed', array('src' => $CFG->wwwroot.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8889 $notificationsound = html_writer::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8892 $url = $CFG->wwwroot.'/message/index.php';
8893 $content = html_writer::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8894 html_writer::start_tag('div', array('id' => 'newmessagetext')).
8895 $strmessages.
8896 html_writer::end_tag('div').
8898 $notificationsound.
8899 html_writer::start_tag('div', array('id' => 'newmessagelinks')).
8900 html_writer::link($url, $strgomessage, array('id' => 'notificationyes')).'&nbsp;&nbsp;&nbsp;'.
8901 html_writer::link('', $strstaymessage, array('id' => 'notificationno')).
8902 html_writer::end_tag('div');
8903 html_writer::end_tag('div');
8905 $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
8907 $USER->message_lastpopup = time();
8912 * Used to make sure that $min <= $value <= $max
8914 * Make sure that value is between min, and max
8916 * @param int $min The minimum value
8917 * @param int $value The value to check
8918 * @param int $max The maximum value
8919 * @return int
8921 function bounded_number($min, $value, $max) {
8922 if ($value < $min) {
8923 return $min;
8925 if ($value > $max) {
8926 return $max;
8928 return $value;
8932 * Check if there is a nested array within the passed array
8934 * @param array $array
8935 * @return bool true if there is a nested array false otherwise
8937 function array_is_nested($array) {
8938 foreach ($array as $value) {
8939 if (is_array($value)) {
8940 return true;
8943 return false;
8947 * get_performance_info() pairs up with init_performance_info()
8948 * loaded in setup.php. Returns an array with 'html' and 'txt'
8949 * values ready for use, and each of the individual stats provided
8950 * separately as well.
8952 * @return array
8954 function get_performance_info() {
8955 global $CFG, $PERF, $DB, $PAGE;
8957 $info = array();
8958 $info['html'] = ''; // Holds userfriendly HTML representation.
8959 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8961 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
8963 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8964 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8966 if (function_exists('memory_get_usage')) {
8967 $info['memory_total'] = memory_get_usage();
8968 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
8969 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8970 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8971 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8974 if (function_exists('memory_get_peak_usage')) {
8975 $info['memory_peak'] = memory_get_peak_usage();
8976 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8977 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8980 $inc = get_included_files();
8981 $info['includecount'] = count($inc);
8982 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8983 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8985 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
8986 // We can not track more performance before installation or before PAGE init, sorry.
8987 return $info;
8990 $filtermanager = filter_manager::instance();
8991 if (method_exists($filtermanager, 'get_performance_summary')) {
8992 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8993 $info = array_merge($filterinfo, $info);
8994 foreach ($filterinfo as $key => $value) {
8995 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8996 $info['txt'] .= "$key: $value ";
9000 $stringmanager = get_string_manager();
9001 if (method_exists($stringmanager, 'get_performance_summary')) {
9002 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9003 $info = array_merge($filterinfo, $info);
9004 foreach ($filterinfo as $key => $value) {
9005 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
9006 $info['txt'] .= "$key: $value ";
9010 if (!empty($PERF->logwrites)) {
9011 $info['logwrites'] = $PERF->logwrites;
9012 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
9013 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9016 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9017 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
9018 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9020 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9021 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
9022 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9024 if (function_exists('posix_times')) {
9025 $ptimes = posix_times();
9026 if (is_array($ptimes)) {
9027 foreach ($ptimes as $key => $val) {
9028 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9030 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
9031 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9035 // Grab the load average for the last minute.
9036 // /proc will only work under some linux configurations
9037 // while uptime is there under MacOSX/Darwin and other unices.
9038 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9039 list($serverload) = explode(' ', $loadavg[0]);
9040 unset($loadavg);
9041 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9042 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9043 $serverload = $matches[1];
9044 } else {
9045 trigger_error('Could not parse uptime output!');
9048 if (!empty($serverload)) {
9049 $info['serverload'] = $serverload;
9050 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
9051 $info['txt'] .= "serverload: {$info['serverload']} ";
9054 // Display size of session if session started.
9055 if ($si = \core\session\manager::get_performance_info()) {
9056 $info['sessionsize'] = $si['size'];
9057 $info['html'] .= $si['html'];
9058 $info['txt'] .= $si['txt'];
9061 if ($stats = cache_helper::get_stats()) {
9062 $html = '<span class="cachesused">';
9063 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
9064 $text = 'Caches used (hits/misses/sets): ';
9065 $hits = 0;
9066 $misses = 0;
9067 $sets = 0;
9068 foreach ($stats as $definition => $details) {
9069 switch ($details['mode']) {
9070 case cache_store::MODE_APPLICATION:
9071 $modeclass = 'application';
9072 $mode = ' <span title="application cache">[a]</span>';
9073 break;
9074 case cache_store::MODE_SESSION:
9075 $modeclass = 'session';
9076 $mode = ' <span title="session cache">[s]</span>';
9077 break;
9078 case cache_store::MODE_REQUEST:
9079 $modeclass = 'request';
9080 $mode = ' <span title="request cache">[r]</span>';
9081 break;
9083 $html .= '<span class="cache-definition-stats cache-mode-'.$modeclass.'">';
9084 $html .= '<span class="cache-definition-stats-heading">'.$definition.$mode.'</span>';
9085 $text .= "$definition {";
9086 foreach ($details['stores'] as $store => $data) {
9087 $hits += $data['hits'];
9088 $misses += $data['misses'];
9089 $sets += $data['sets'];
9090 if ($data['hits'] == 0 and $data['misses'] > 0) {
9091 $cachestoreclass = 'nohits';
9092 } else if ($data['hits'] < $data['misses']) {
9093 $cachestoreclass = 'lowhits';
9094 } else {
9095 $cachestoreclass = 'hihits';
9097 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9098 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
9100 $html .= '</span>';
9101 $text .= '} ';
9103 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
9104 $html .= '</span> ';
9105 $info['cachesused'] = "$hits / $misses / $sets";
9106 $info['html'] .= $html;
9107 $info['txt'] .= $text.'. ';
9108 } else {
9109 $info['cachesused'] = '0 / 0 / 0';
9110 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
9111 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9114 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
9115 return $info;
9119 * Delete directory or only its content
9121 * @param string $dir directory path
9122 * @param bool $contentonly
9123 * @return bool success, true also if dir does not exist
9125 function remove_dir($dir, $contentonly=false) {
9126 if (!file_exists($dir)) {
9127 // Nothing to do.
9128 return true;
9130 if (!$handle = opendir($dir)) {
9131 return false;
9133 $result = true;
9134 while (false!==($item = readdir($handle))) {
9135 if ($item != '.' && $item != '..') {
9136 if (is_dir($dir.'/'.$item)) {
9137 $result = remove_dir($dir.'/'.$item) && $result;
9138 } else {
9139 $result = unlink($dir.'/'.$item) && $result;
9143 closedir($handle);
9144 if ($contentonly) {
9145 clearstatcache(); // Make sure file stat cache is properly invalidated.
9146 return $result;
9148 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9149 clearstatcache(); // Make sure file stat cache is properly invalidated.
9150 return $result;
9154 * Detect if an object or a class contains a given property
9155 * will take an actual object or the name of a class
9157 * @param mix $obj Name of class or real object to test
9158 * @param string $property name of property to find
9159 * @return bool true if property exists
9161 function object_property_exists( $obj, $property ) {
9162 if (is_string( $obj )) {
9163 $properties = get_class_vars( $obj );
9164 } else {
9165 $properties = get_object_vars( $obj );
9167 return array_key_exists( $property, $properties );
9171 * Converts an object into an associative array
9173 * This function converts an object into an associative array by iterating
9174 * over its public properties. Because this function uses the foreach
9175 * construct, Iterators are respected. It works recursively on arrays of objects.
9176 * Arrays and simple values are returned as is.
9178 * If class has magic properties, it can implement IteratorAggregate
9179 * and return all available properties in getIterator()
9181 * @param mixed $var
9182 * @return array
9184 function convert_to_array($var) {
9185 $result = array();
9187 // Loop over elements/properties.
9188 foreach ($var as $key => $value) {
9189 // Recursively convert objects.
9190 if (is_object($value) || is_array($value)) {
9191 $result[$key] = convert_to_array($value);
9192 } else {
9193 // Simple values are untouched.
9194 $result[$key] = $value;
9197 return $result;
9201 * Detect a custom script replacement in the data directory that will
9202 * replace an existing moodle script
9204 * @return string|bool full path name if a custom script exists, false if no custom script exists
9206 function custom_script_path() {
9207 global $CFG, $SCRIPT;
9209 if ($SCRIPT === null) {
9210 // Probably some weird external script.
9211 return false;
9214 $scriptpath = $CFG->customscripts . $SCRIPT;
9216 // Check the custom script exists.
9217 if (file_exists($scriptpath) and is_file($scriptpath)) {
9218 return $scriptpath;
9219 } else {
9220 return false;
9225 * Returns whether or not the user object is a remote MNET user. This function
9226 * is in moodlelib because it does not rely on loading any of the MNET code.
9228 * @param object $user A valid user object
9229 * @return bool True if the user is from a remote Moodle.
9231 function is_mnet_remote_user($user) {
9232 global $CFG;
9234 if (!isset($CFG->mnet_localhost_id)) {
9235 include_once($CFG->dirroot . '/mnet/lib.php');
9236 $env = new mnet_environment();
9237 $env->init();
9238 unset($env);
9241 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9245 * This function will search for browser prefereed languages, setting Moodle
9246 * to use the best one available if $SESSION->lang is undefined
9248 function setup_lang_from_browser() {
9249 global $CFG, $SESSION, $USER;
9251 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9252 // Lang is defined in session or user profile, nothing to do.
9253 return;
9256 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9257 return;
9260 // Extract and clean langs from headers.
9261 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9262 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9263 $rawlangs = explode(',', $rawlangs); // Convert to array.
9264 $langs = array();
9266 $order = 1.0;
9267 foreach ($rawlangs as $lang) {
9268 if (strpos($lang, ';') === false) {
9269 $langs[(string)$order] = $lang;
9270 $order = $order-0.01;
9271 } else {
9272 $parts = explode(';', $lang);
9273 $pos = strpos($parts[1], '=');
9274 $langs[substr($parts[1], $pos+1)] = $parts[0];
9277 krsort($langs, SORT_NUMERIC);
9279 // Look for such langs under standard locations.
9280 foreach ($langs as $lang) {
9281 // Clean it properly for include.
9282 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9283 if (get_string_manager()->translation_exists($lang, false)) {
9284 // Lang exists, set it in session.
9285 $SESSION->lang = $lang;
9286 // We have finished. Go out.
9287 break;
9290 return;
9294 * Check if $url matches anything in proxybypass list
9296 * Any errors just result in the proxy being used (least bad)
9298 * @param string $url url to check
9299 * @return boolean true if we should bypass the proxy
9301 function is_proxybypass( $url ) {
9302 global $CFG;
9304 // Sanity check.
9305 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9306 return false;
9309 // Get the host part out of the url.
9310 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9311 return false;
9314 // Get the possible bypass hosts into an array.
9315 $matches = explode( ',', $CFG->proxybypass );
9317 // Check for a match.
9318 // (IPs need to match the left hand side and hosts the right of the url,
9319 // but we can recklessly check both as there can't be a false +ve).
9320 foreach ($matches as $match) {
9321 $match = trim($match);
9323 // Try for IP match (Left side).
9324 $lhs = substr($host, 0, strlen($match));
9325 if (strcasecmp($match, $lhs)==0) {
9326 return true;
9329 // Try for host match (Right side).
9330 $rhs = substr($host, -strlen($match));
9331 if (strcasecmp($match, $rhs)==0) {
9332 return true;
9336 // Nothing matched.
9337 return false;
9341 * Check if the passed navigation is of the new style
9343 * @param mixed $navigation
9344 * @return bool true for yes false for no
9346 function is_newnav($navigation) {
9347 if (is_array($navigation) && !empty($navigation['newnav'])) {
9348 return true;
9349 } else {
9350 return false;
9355 * Checks whether the given variable name is defined as a variable within the given object.
9357 * This will NOT work with stdClass objects, which have no class variables.
9359 * @param string $var The variable name
9360 * @param object $object The object to check
9361 * @return boolean
9363 function in_object_vars($var, $object) {
9364 $classvars = get_class_vars(get_class($object));
9365 $classvars = array_keys($classvars);
9366 return in_array($var, $classvars);
9370 * Returns an array without repeated objects.
9371 * This function is similar to array_unique, but for arrays that have objects as values
9373 * @param array $array
9374 * @param bool $keepkeyassoc
9375 * @return array
9377 function object_array_unique($array, $keepkeyassoc = true) {
9378 $duplicatekeys = array();
9379 $tmp = array();
9381 foreach ($array as $key => $val) {
9382 // Convert objects to arrays, in_array() does not support objects.
9383 if (is_object($val)) {
9384 $val = (array)$val;
9387 if (!in_array($val, $tmp)) {
9388 $tmp[] = $val;
9389 } else {
9390 $duplicatekeys[] = $key;
9394 foreach ($duplicatekeys as $key) {
9395 unset($array[$key]);
9398 return $keepkeyassoc ? $array : array_values($array);
9402 * Is a userid the primary administrator?
9404 * @param int $userid int id of user to check
9405 * @return boolean
9407 function is_primary_admin($userid) {
9408 $primaryadmin = get_admin();
9410 if ($userid == $primaryadmin->id) {
9411 return true;
9412 } else {
9413 return false;
9418 * Returns the site identifier
9420 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9422 function get_site_identifier() {
9423 global $CFG;
9424 // Check to see if it is missing. If so, initialise it.
9425 if (empty($CFG->siteidentifier)) {
9426 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9428 // Return it.
9429 return $CFG->siteidentifier;
9433 * Check whether the given password has no more than the specified
9434 * number of consecutive identical characters.
9436 * @param string $password password to be checked against the password policy
9437 * @param integer $maxchars maximum number of consecutive identical characters
9438 * @return bool
9440 function check_consecutive_identical_characters($password, $maxchars) {
9442 if ($maxchars < 1) {
9443 return true; // Zero 0 is to disable this check.
9445 if (strlen($password) <= $maxchars) {
9446 return true; // Too short to fail this test.
9449 $previouschar = '';
9450 $consecutivecount = 1;
9451 foreach (str_split($password) as $char) {
9452 if ($char != $previouschar) {
9453 $consecutivecount = 1;
9454 } else {
9455 $consecutivecount++;
9456 if ($consecutivecount > $maxchars) {
9457 return false; // Check failed already.
9461 $previouschar = $char;
9464 return true;
9468 * Helper function to do partial function binding.
9469 * so we can use it for preg_replace_callback, for example
9470 * this works with php functions, user functions, static methods and class methods
9471 * it returns you a callback that you can pass on like so:
9473 * $callback = partial('somefunction', $arg1, $arg2);
9474 * or
9475 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9476 * or even
9477 * $obj = new someclass();
9478 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9480 * and then the arguments that are passed through at calltime are appended to the argument list.
9482 * @param mixed $function a php callback
9483 * @param mixed $arg1,... $argv arguments to partially bind with
9484 * @return array Array callback
9486 function partial() {
9487 if (!class_exists('partial')) {
9489 * Used to manage function binding.
9490 * @copyright 2009 Penny Leach
9491 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9493 class partial{
9494 /** @var array */
9495 public $values = array();
9496 /** @var string The function to call as a callback. */
9497 public $func;
9499 * Constructor
9500 * @param string $func
9501 * @param array $args
9503 public function __construct($func, $args) {
9504 $this->values = $args;
9505 $this->func = $func;
9508 * Calls the callback function.
9509 * @return mixed
9511 public function method() {
9512 $args = func_get_args();
9513 return call_user_func_array($this->func, array_merge($this->values, $args));
9517 $args = func_get_args();
9518 $func = array_shift($args);
9519 $p = new partial($func, $args);
9520 return array($p, 'method');
9524 * helper function to load up and initialise the mnet environment
9525 * this must be called before you use mnet functions.
9527 * @return mnet_environment the equivalent of old $MNET global
9529 function get_mnet_environment() {
9530 global $CFG;
9531 require_once($CFG->dirroot . '/mnet/lib.php');
9532 static $instance = null;
9533 if (empty($instance)) {
9534 $instance = new mnet_environment();
9535 $instance->init();
9537 return $instance;
9541 * during xmlrpc server code execution, any code wishing to access
9542 * information about the remote peer must use this to get it.
9544 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9546 function get_mnet_remote_client() {
9547 if (!defined('MNET_SERVER')) {
9548 debugging(get_string('notinxmlrpcserver', 'mnet'));
9549 return false;
9551 global $MNET_REMOTE_CLIENT;
9552 if (isset($MNET_REMOTE_CLIENT)) {
9553 return $MNET_REMOTE_CLIENT;
9555 return false;
9559 * during the xmlrpc server code execution, this will be called
9560 * to setup the object returned by {@link get_mnet_remote_client}
9562 * @param mnet_remote_client $client the client to set up
9563 * @throws moodle_exception
9565 function set_mnet_remote_client($client) {
9566 if (!defined('MNET_SERVER')) {
9567 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9569 global $MNET_REMOTE_CLIENT;
9570 $MNET_REMOTE_CLIENT = $client;
9574 * return the jump url for a given remote user
9575 * this is used for rewriting forum post links in emails, etc
9577 * @param stdclass $user the user to get the idp url for
9579 function mnet_get_idp_jump_url($user) {
9580 global $CFG;
9582 static $mnetjumps = array();
9583 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9584 $idp = mnet_get_peer_host($user->mnethostid);
9585 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9586 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9588 return $mnetjumps[$user->mnethostid];
9592 * Gets the homepage to use for the current user
9594 * @return int One of HOMEPAGE_*
9596 function get_home_page() {
9597 global $CFG;
9599 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9600 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9601 return HOMEPAGE_MY;
9602 } else {
9603 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9606 return HOMEPAGE_SITE;
9610 * Gets the name of a course to be displayed when showing a list of courses.
9611 * By default this is just $course->fullname but user can configure it. The
9612 * result of this function should be passed through print_string.
9613 * @param stdClass|course_in_list $course Moodle course object
9614 * @return string Display name of course (either fullname or short + fullname)
9616 function get_course_display_name_for_list($course) {
9617 global $CFG;
9618 if (!empty($CFG->courselistshortnames)) {
9619 if (!($course instanceof stdClass)) {
9620 $course = (object)convert_to_array($course);
9622 return get_string('courseextendednamedisplay', '', $course);
9623 } else {
9624 return $course->fullname;
9629 * Safe analogue of unserialize() that can only parse arrays
9631 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
9632 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
9633 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
9635 * @param string $expression
9636 * @return array|bool either parsed array or false if parsing was impossible.
9638 function unserialize_array($expression) {
9639 $subs = [];
9640 // Find nested arrays, parse them and store in $subs , substitute with special string.
9641 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
9642 $key = '--SUB' . count($subs) . '--';
9643 $subs[$key] = unserialize_array($matches[2]);
9644 if ($subs[$key] === false) {
9645 return false;
9647 $expression = str_replace($matches[2], $key . ';', $expression);
9650 // Check the expression is an array.
9651 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
9652 return false;
9654 // Get the size and elements of an array (key;value;key;value;....).
9655 $parts = explode(';', $matches1[2]);
9656 $size = intval($matches1[1]);
9657 if (count($parts) < $size * 2 + 1) {
9658 return false;
9660 // Analyze each part and make sure it is an integer or string or a substitute.
9661 $value = [];
9662 for ($i = 0; $i < $size * 2; $i++) {
9663 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
9664 $parts[$i] = (int)$matches2[1];
9665 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
9666 $parts[$i] = $matches3[2];
9667 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
9668 $parts[$i] = $subs[$parts[$i]];
9669 } else {
9670 return false;
9673 // Combine keys and values.
9674 for ($i = 0; $i < $size * 2; $i += 2) {
9675 $value[$parts[$i]] = $parts[$i+1];
9677 return $value;
9681 * The lang_string class
9683 * This special class is used to create an object representation of a string request.
9684 * It is special because processing doesn't occur until the object is first used.
9685 * The class was created especially to aid performance in areas where strings were
9686 * required to be generated but were not necessarily used.
9687 * As an example the admin tree when generated uses over 1500 strings, of which
9688 * normally only 1/3 are ever actually printed at any time.
9689 * The performance advantage is achieved by not actually processing strings that
9690 * arn't being used, as such reducing the processing required for the page.
9692 * How to use the lang_string class?
9693 * There are two methods of using the lang_string class, first through the
9694 * forth argument of the get_string function, and secondly directly.
9695 * The following are examples of both.
9696 * 1. Through get_string calls e.g.
9697 * $string = get_string($identifier, $component, $a, true);
9698 * $string = get_string('yes', 'moodle', null, true);
9699 * 2. Direct instantiation
9700 * $string = new lang_string($identifier, $component, $a, $lang);
9701 * $string = new lang_string('yes');
9703 * How do I use a lang_string object?
9704 * The lang_string object makes use of a magic __toString method so that you
9705 * are able to use the object exactly as you would use a string in most cases.
9706 * This means you are able to collect it into a variable and then directly
9707 * echo it, or concatenate it into another string, or similar.
9708 * The other thing you can do is manually get the string by calling the
9709 * lang_strings out method e.g.
9710 * $string = new lang_string('yes');
9711 * $string->out();
9712 * Also worth noting is that the out method can take one argument, $lang which
9713 * allows the developer to change the language on the fly.
9715 * When should I use a lang_string object?
9716 * The lang_string object is designed to be used in any situation where a
9717 * string may not be needed, but needs to be generated.
9718 * The admin tree is a good example of where lang_string objects should be
9719 * used.
9720 * A more practical example would be any class that requries strings that may
9721 * not be printed (after all classes get renderer by renderers and who knows
9722 * what they will do ;))
9724 * When should I not use a lang_string object?
9725 * Don't use lang_strings when you are going to use a string immediately.
9726 * There is no need as it will be processed immediately and there will be no
9727 * advantage, and in fact perhaps a negative hit as a class has to be
9728 * instantiated for a lang_string object, however get_string won't require
9729 * that.
9731 * Limitations:
9732 * 1. You cannot use a lang_string object as an array offset. Doing so will
9733 * result in PHP throwing an error. (You can use it as an object property!)
9735 * @package core
9736 * @category string
9737 * @copyright 2011 Sam Hemelryk
9738 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9740 class lang_string {
9742 /** @var string The strings identifier */
9743 protected $identifier;
9744 /** @var string The strings component. Default '' */
9745 protected $component = '';
9746 /** @var array|stdClass Any arguments required for the string. Default null */
9747 protected $a = null;
9748 /** @var string The language to use when processing the string. Default null */
9749 protected $lang = null;
9751 /** @var string The processed string (once processed) */
9752 protected $string = null;
9755 * A special boolean. If set to true then the object has been woken up and
9756 * cannot be regenerated. If this is set then $this->string MUST be used.
9757 * @var bool
9759 protected $forcedstring = false;
9762 * Constructs a lang_string object
9764 * This function should do as little processing as possible to ensure the best
9765 * performance for strings that won't be used.
9767 * @param string $identifier The strings identifier
9768 * @param string $component The strings component
9769 * @param stdClass|array $a Any arguments the string requires
9770 * @param string $lang The language to use when processing the string.
9771 * @throws coding_exception
9773 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9774 if (empty($component)) {
9775 $component = 'moodle';
9778 $this->identifier = $identifier;
9779 $this->component = $component;
9780 $this->lang = $lang;
9782 // We MUST duplicate $a to ensure that it if it changes by reference those
9783 // changes are not carried across.
9784 // To do this we always ensure $a or its properties/values are strings
9785 // and that any properties/values that arn't convertable are forgotten.
9786 if (!empty($a)) {
9787 if (is_scalar($a)) {
9788 $this->a = $a;
9789 } else if ($a instanceof lang_string) {
9790 $this->a = $a->out();
9791 } else if (is_object($a) or is_array($a)) {
9792 $a = (array)$a;
9793 $this->a = array();
9794 foreach ($a as $key => $value) {
9795 // Make sure conversion errors don't get displayed (results in '').
9796 if (is_array($value)) {
9797 $this->a[$key] = '';
9798 } else if (is_object($value)) {
9799 if (method_exists($value, '__toString')) {
9800 $this->a[$key] = $value->__toString();
9801 } else {
9802 $this->a[$key] = '';
9804 } else {
9805 $this->a[$key] = (string)$value;
9811 if (debugging(false, DEBUG_DEVELOPER)) {
9812 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9813 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9815 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9816 throw new coding_exception('Invalid string compontent. Please check your string definition');
9818 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9819 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9825 * Processes the string.
9827 * This function actually processes the string, stores it in the string property
9828 * and then returns it.
9829 * You will notice that this function is VERY similar to the get_string method.
9830 * That is because it is pretty much doing the same thing.
9831 * However as this function is an upgrade it isn't as tolerant to backwards
9832 * compatibility.
9834 * @return string
9835 * @throws coding_exception
9837 protected function get_string() {
9838 global $CFG;
9840 // Check if we need to process the string.
9841 if ($this->string === null) {
9842 // Check the quality of the identifier.
9843 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9844 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);
9847 // Process the string.
9848 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9849 // Debugging feature lets you display string identifier and component.
9850 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9851 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9854 // Return the string.
9855 return $this->string;
9859 * Returns the string
9861 * @param string $lang The langauge to use when processing the string
9862 * @return string
9864 public function out($lang = null) {
9865 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9866 if ($this->forcedstring) {
9867 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9868 return $this->get_string();
9870 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9871 return $translatedstring->out();
9873 return $this->get_string();
9877 * Magic __toString method for printing a string
9879 * @return string
9881 public function __toString() {
9882 return $this->get_string();
9886 * Magic __set_state method used for var_export
9888 * @return string
9890 public function __set_state() {
9891 return $this->get_string();
9895 * Prepares the lang_string for sleep and stores only the forcedstring and
9896 * string properties... the string cannot be regenerated so we need to ensure
9897 * it is generated for this.
9899 * @return string
9901 public function __sleep() {
9902 $this->get_string();
9903 $this->forcedstring = true;
9904 return array('forcedstring', 'string', 'lang');