MDL-56739 auth: Support custom confirmation URL
[moodle.git] / lib / moodlelib.php
blobecff98b12453decc18c403e34b19b81dac336095
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * moodlelib.php - Moodle main library
20 * Main library file of miscellaneous general-purpose Moodle functions.
21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - datalib.php - functions that access the database
25 * @package core
26 * @subpackage lib
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') || die();
33 // CONSTANTS (Encased in phpdoc proper comments).
35 // Date and time constants.
36 /**
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
41 /**
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
46 /**
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
51 /**
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
56 /**
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
61 /**
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
66 /**
67 * Time constant - the number of minutes in an hour
69 define('HOURMINS', 60);
71 // Parameter constants - every call to optional_param(), required_param()
72 // or clean_param() should have a specified type of parameter.
74 /**
75 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
77 define('PARAM_ALPHA', 'alpha');
79 /**
80 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
81 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
83 define('PARAM_ALPHAEXT', 'alphaext');
85 /**
86 * PARAM_ALPHANUM - expected numbers and letters only.
88 define('PARAM_ALPHANUM', 'alphanum');
90 /**
91 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
95 /**
96 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
98 define('PARAM_AUTH', 'auth');
101 * PARAM_BASE64 - Base 64 encoded format
103 define('PARAM_BASE64', 'base64');
106 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
108 define('PARAM_BOOL', 'bool');
111 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
112 * checked against the list of capabilities in the database.
114 define('PARAM_CAPABILITY', 'capability');
117 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118 * to use this. The normal mode of operation is to use PARAM_RAW when recieving
119 * the input (required/optional_param or formslib) and then sanitse the HTML
120 * using format_text on output. This is for the rare cases when you want to
121 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
123 define('PARAM_CLEANHTML', 'cleanhtml');
126 * PARAM_EMAIL - an email address following the RFC
128 define('PARAM_EMAIL', 'email');
131 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
133 define('PARAM_FILE', 'file');
136 * PARAM_FLOAT - a real/floating point number.
138 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
139 * It does not work for languages that use , as a decimal separator.
140 * Instead, do something like
141 * $rawvalue = required_param('name', PARAM_RAW);
142 * // ... other code including require_login, which sets current lang ...
143 * $realvalue = unformat_float($rawvalue);
144 * // ... then use $realvalue
146 define('PARAM_FLOAT', 'float');
149 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
151 define('PARAM_HOST', 'host');
154 * PARAM_INT - integers only, use when expecting only numbers.
156 define('PARAM_INT', 'int');
159 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
161 define('PARAM_LANG', 'lang');
164 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
165 * others! Implies PARAM_URL!)
167 define('PARAM_LOCALURL', 'localurl');
170 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
172 define('PARAM_NOTAGS', 'notags');
175 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
176 * traversals note: the leading slash is not removed, window drive letter is not allowed
178 define('PARAM_PATH', 'path');
181 * PARAM_PEM - Privacy Enhanced Mail format
183 define('PARAM_PEM', 'pem');
186 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
188 define('PARAM_PERMISSION', 'permission');
191 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
193 define('PARAM_RAW', 'raw');
196 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
198 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
201 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
203 define('PARAM_SAFEDIR', 'safedir');
206 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
208 define('PARAM_SAFEPATH', 'safepath');
211 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
213 define('PARAM_SEQUENCE', 'sequence');
216 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
218 define('PARAM_TAG', 'tag');
221 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
223 define('PARAM_TAGLIST', 'taglist');
226 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
228 define('PARAM_TEXT', 'text');
231 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
233 define('PARAM_THEME', 'theme');
236 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
237 * http://localhost.localdomain/ is ok.
239 define('PARAM_URL', 'url');
242 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
243 * accounts, do NOT use when syncing with external systems!!
245 define('PARAM_USERNAME', 'username');
248 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
250 define('PARAM_STRINGID', 'stringid');
252 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
254 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
255 * It was one of the first types, that is why it is abused so much ;-)
256 * @deprecated since 2.0
258 define('PARAM_CLEAN', 'clean');
261 * PARAM_INTEGER - deprecated alias for PARAM_INT
262 * @deprecated since 2.0
264 define('PARAM_INTEGER', 'int');
267 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
268 * @deprecated since 2.0
270 define('PARAM_NUMBER', 'float');
273 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
274 * NOTE: originally alias for PARAM_APLHA
275 * @deprecated since 2.0
277 define('PARAM_ACTION', 'alphanumext');
280 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
281 * NOTE: originally alias for PARAM_APLHA
282 * @deprecated since 2.0
284 define('PARAM_FORMAT', 'alphanumext');
287 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
288 * @deprecated since 2.0
290 define('PARAM_MULTILANG', 'text');
293 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
294 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
295 * America/Port-au-Prince)
297 define('PARAM_TIMEZONE', 'timezone');
300 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
302 define('PARAM_CLEANFILE', 'file');
305 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
306 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
307 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308 * NOTE: numbers and underscores are strongly discouraged in plugin names!
310 define('PARAM_COMPONENT', 'component');
313 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
314 * It is usually used together with context id and component.
315 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
317 define('PARAM_AREA', 'area');
320 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
321 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
324 define('PARAM_PLUGIN', 'plugin');
327 // Web Services.
330 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
332 define('VALUE_REQUIRED', 1);
335 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
337 define('VALUE_OPTIONAL', 2);
340 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
342 define('VALUE_DEFAULT', 0);
345 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
347 define('NULL_NOT_ALLOWED', false);
350 * NULL_ALLOWED - the parameter can be set to null in the database
352 define('NULL_ALLOWED', true);
354 // Page types.
357 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
359 define('PAGE_COURSE_VIEW', 'course-view');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363 /** Get remote addr constant */
364 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
366 // Blog access level constant declaration.
367 define ('BLOG_USER_LEVEL', 1);
368 define ('BLOG_GROUP_LEVEL', 2);
369 define ('BLOG_COURSE_LEVEL', 3);
370 define ('BLOG_SITE_LEVEL', 4);
371 define ('BLOG_GLOBAL_LEVEL', 5);
374 // Tag constants.
376 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
377 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
380 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
382 define('TAG_MAX_LENGTH', 50);
384 // Password policy constants.
385 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387 define ('PASSWORD_DIGITS', '0123456789');
388 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
390 // Feature constants.
391 // Used for plugin_supports() to report features that are, or are not, supported by a module.
393 /** True if module can provide a grade */
394 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
395 /** True if module supports outcomes */
396 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
397 /** True if module supports advanced grading methods */
398 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
399 /** True if module controls the grade visibility over the gradebook */
400 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
401 /** True if module supports plagiarism plugins */
402 define('FEATURE_PLAGIARISM', 'plagiarism');
404 /** True if module has code to track whether somebody viewed it */
405 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
406 /** True if module has custom completion rules */
407 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
409 /** True if module has no 'view' page (like label) */
410 define('FEATURE_NO_VIEW_LINK', 'viewlink');
411 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
418 * True if module supports groupmembersonly (which no longer exists)
419 * @deprecated Since Moodle 2.8
421 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
423 /** Type of module */
424 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
425 /** True if module supports intro editor */
426 define('FEATURE_MOD_INTRO', 'mod_intro');
427 /** True if module has default completion */
428 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
430 define('FEATURE_COMMENT', 'comment');
432 define('FEATURE_RATE', 'rate');
433 /** True if module supports backup/restore of moodle2 format */
434 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
436 /** True if module can show description on course main page */
437 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
439 /** True if module uses the question bank */
440 define('FEATURE_USES_QUESTIONS', 'usesquestions');
442 /** Unspecified module archetype */
443 define('MOD_ARCHETYPE_OTHER', 0);
444 /** Resource-like type module */
445 define('MOD_ARCHETYPE_RESOURCE', 1);
446 /** Assignment module archetype */
447 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
448 /** System (not user-addable) module archetype */
449 define('MOD_ARCHETYPE_SYSTEM', 3);
452 * Return this from modname_get_types callback to use default display in activity chooser.
453 * Deprecated, will be removed in 3.5, TODO MDL-53697.
454 * @deprecated since Moodle 3.1
456 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
459 * Security token used for allowing access
460 * from external application such as web services.
461 * Scripts do not use any session, performance is relatively
462 * low because we need to load access info in each request.
463 * Scripts are executed in parallel.
465 define('EXTERNAL_TOKEN_PERMANENT', 0);
468 * Security token used for allowing access
469 * of embedded applications, the code is executed in the
470 * active user session. Token is invalidated after user logs out.
471 * Scripts are executed serially - normal session locking is used.
473 define('EXTERNAL_TOKEN_EMBEDDED', 1);
476 * The home page should be the site home
478 define('HOMEPAGE_SITE', 0);
480 * The home page should be the users my page
482 define('HOMEPAGE_MY', 1);
484 * The home page can be chosen by the user
486 define('HOMEPAGE_USER', 2);
489 * Hub directory url (should be moodle.org)
491 define('HUB_HUBDIRECTORYURL', "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');
524 * Email from header to never include via information.
526 define('EMAIL_VIA_NEVER', 0);
529 * Email from header to always include via information.
531 define('EMAIL_VIA_ALWAYS', 1);
534 * Email from header to only include via information if the address is no-reply.
536 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
538 // PARAMETER HANDLING.
541 * Returns a particular value for the named variable, taken from
542 * POST or GET. If the parameter doesn't exist then an error is
543 * thrown because we require this variable.
545 * This function should be used to initialise all required values
546 * in a script that are based on parameters. Usually it will be
547 * used like this:
548 * $id = required_param('id', PARAM_INT);
550 * Please note the $type parameter is now required and the value can not be array.
552 * @param string $parname the name of the page parameter we want
553 * @param string $type expected type of parameter
554 * @return mixed
555 * @throws coding_exception
557 function required_param($parname, $type) {
558 if (func_num_args() != 2 or empty($parname) or empty($type)) {
559 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
561 // POST has precedence.
562 if (isset($_POST[$parname])) {
563 $param = $_POST[$parname];
564 } else if (isset($_GET[$parname])) {
565 $param = $_GET[$parname];
566 } else {
567 print_error('missingparam', '', '', $parname);
570 if (is_array($param)) {
571 debugging('Invalid array parameter detected in required_param(): '.$parname);
572 // TODO: switch to fatal error in Moodle 2.3.
573 return required_param_array($parname, $type);
576 return clean_param($param, $type);
580 * Returns a particular array value for the named variable, taken from
581 * POST or GET. If the parameter doesn't exist then an error is
582 * thrown because we require this variable.
584 * This function should be used to initialise all required values
585 * in a script that are based on parameters. Usually it will be
586 * used like this:
587 * $ids = required_param_array('ids', PARAM_INT);
589 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
591 * @param string $parname the name of the page parameter we want
592 * @param string $type expected type of parameter
593 * @return array
594 * @throws coding_exception
596 function required_param_array($parname, $type) {
597 if (func_num_args() != 2 or empty($parname) or empty($type)) {
598 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
600 // POST has precedence.
601 if (isset($_POST[$parname])) {
602 $param = $_POST[$parname];
603 } else if (isset($_GET[$parname])) {
604 $param = $_GET[$parname];
605 } else {
606 print_error('missingparam', '', '', $parname);
608 if (!is_array($param)) {
609 print_error('missingparam', '', '', $parname);
612 $result = array();
613 foreach ($param as $key => $value) {
614 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
615 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
616 continue;
618 $result[$key] = clean_param($value, $type);
621 return $result;
625 * Returns a particular value for the named variable, taken from
626 * POST or GET, otherwise returning a given default.
628 * This function should be used to initialise all optional values
629 * in a script that are based on parameters. Usually it will be
630 * used like this:
631 * $name = optional_param('name', 'Fred', PARAM_TEXT);
633 * Please note the $type parameter is now required and the value can not be array.
635 * @param string $parname the name of the page parameter we want
636 * @param mixed $default the default value to return if nothing is found
637 * @param string $type expected type of parameter
638 * @return mixed
639 * @throws coding_exception
641 function optional_param($parname, $default, $type) {
642 if (func_num_args() != 3 or empty($parname) or empty($type)) {
643 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
646 // POST has precedence.
647 if (isset($_POST[$parname])) {
648 $param = $_POST[$parname];
649 } else if (isset($_GET[$parname])) {
650 $param = $_GET[$parname];
651 } else {
652 return $default;
655 if (is_array($param)) {
656 debugging('Invalid array parameter detected in required_param(): '.$parname);
657 // TODO: switch to $default in Moodle 2.3.
658 return optional_param_array($parname, $default, $type);
661 return clean_param($param, $type);
665 * Returns a particular array value for the named variable, taken from
666 * POST or GET, otherwise returning a given default.
668 * This function should be used to initialise all optional values
669 * in a script that are based on parameters. Usually it will be
670 * used like this:
671 * $ids = optional_param('id', array(), PARAM_INT);
673 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
675 * @param string $parname the name of the page parameter we want
676 * @param mixed $default the default value to return if nothing is found
677 * @param string $type expected type of parameter
678 * @return array
679 * @throws coding_exception
681 function optional_param_array($parname, $default, $type) {
682 if (func_num_args() != 3 or empty($parname) or empty($type)) {
683 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
686 // POST has precedence.
687 if (isset($_POST[$parname])) {
688 $param = $_POST[$parname];
689 } else if (isset($_GET[$parname])) {
690 $param = $_GET[$parname];
691 } else {
692 return $default;
694 if (!is_array($param)) {
695 debugging('optional_param_array() expects array parameters only: '.$parname);
696 return $default;
699 $result = array();
700 foreach ($param as $key => $value) {
701 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
702 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
703 continue;
705 $result[$key] = clean_param($value, $type);
708 return $result;
712 * Strict validation of parameter values, the values are only converted
713 * to requested PHP type. Internally it is using clean_param, the values
714 * before and after cleaning must be equal - otherwise
715 * an invalid_parameter_exception is thrown.
716 * Objects and classes are not accepted.
718 * @param mixed $param
719 * @param string $type PARAM_ constant
720 * @param bool $allownull are nulls valid value?
721 * @param string $debuginfo optional debug information
722 * @return mixed the $param value converted to PHP type
723 * @throws invalid_parameter_exception if $param is not of given type
725 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
726 if (is_null($param)) {
727 if ($allownull == NULL_ALLOWED) {
728 return null;
729 } else {
730 throw new invalid_parameter_exception($debuginfo);
733 if (is_array($param) or is_object($param)) {
734 throw new invalid_parameter_exception($debuginfo);
737 $cleaned = clean_param($param, $type);
739 if ($type == PARAM_FLOAT) {
740 // Do not detect precision loss here.
741 if (is_float($param) or is_int($param)) {
742 // These always fit.
743 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
744 throw new invalid_parameter_exception($debuginfo);
746 } else if ((string)$param !== (string)$cleaned) {
747 // Conversion to string is usually lossless.
748 throw new invalid_parameter_exception($debuginfo);
751 return $cleaned;
755 * Makes sure array contains only the allowed types, this function does not validate array key names!
757 * <code>
758 * $options = clean_param($options, PARAM_INT);
759 * </code>
761 * @param array $param the variable array we are cleaning
762 * @param string $type expected format of param after cleaning.
763 * @param bool $recursive clean recursive arrays
764 * @return array
765 * @throws coding_exception
767 function clean_param_array(array $param = null, $type, $recursive = false) {
768 // Convert null to empty array.
769 $param = (array)$param;
770 foreach ($param as $key => $value) {
771 if (is_array($value)) {
772 if ($recursive) {
773 $param[$key] = clean_param_array($value, $type, true);
774 } else {
775 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
777 } else {
778 $param[$key] = clean_param($value, $type);
781 return $param;
785 * Used by {@link optional_param()} and {@link required_param()} to
786 * clean the variables and/or cast to specific types, based on
787 * an options field.
788 * <code>
789 * $course->format = clean_param($course->format, PARAM_ALPHA);
790 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
791 * </code>
793 * @param mixed $param the variable we are cleaning
794 * @param string $type expected format of param after cleaning.
795 * @return mixed
796 * @throws coding_exception
798 function clean_param($param, $type) {
799 global $CFG;
801 if (is_array($param)) {
802 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
803 } else if (is_object($param)) {
804 if (method_exists($param, '__toString')) {
805 $param = $param->__toString();
806 } else {
807 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
811 switch ($type) {
812 case PARAM_RAW:
813 // No cleaning at all.
814 $param = fix_utf8($param);
815 return $param;
817 case PARAM_RAW_TRIMMED:
818 // No cleaning, but strip leading and trailing whitespace.
819 $param = fix_utf8($param);
820 return trim($param);
822 case PARAM_CLEAN:
823 // General HTML cleaning, try to use more specific type if possible this is deprecated!
824 // Please use more specific type instead.
825 if (is_numeric($param)) {
826 return $param;
828 $param = fix_utf8($param);
829 // Sweep for scripts, etc.
830 return clean_text($param);
832 case PARAM_CLEANHTML:
833 // Clean html fragment.
834 $param = fix_utf8($param);
835 // Sweep for scripts, etc.
836 $param = clean_text($param, FORMAT_HTML);
837 return trim($param);
839 case PARAM_INT:
840 // Convert to integer.
841 return (int)$param;
843 case PARAM_FLOAT:
844 // Convert to float.
845 return (float)$param;
847 case PARAM_ALPHA:
848 // Remove everything not `a-z`.
849 return preg_replace('/[^a-zA-Z]/i', '', $param);
851 case PARAM_ALPHAEXT:
852 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
853 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
855 case PARAM_ALPHANUM:
856 // Remove everything not `a-zA-Z0-9`.
857 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
859 case PARAM_ALPHANUMEXT:
860 // Remove everything not `a-zA-Z0-9_-`.
861 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
863 case PARAM_SEQUENCE:
864 // Remove everything not `0-9,`.
865 return preg_replace('/[^0-9,]/i', '', $param);
867 case PARAM_BOOL:
868 // Convert to 1 or 0.
869 $tempstr = strtolower($param);
870 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
871 $param = 1;
872 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
873 $param = 0;
874 } else {
875 $param = empty($param) ? 0 : 1;
877 return $param;
879 case PARAM_NOTAGS:
880 // Strip all tags.
881 $param = fix_utf8($param);
882 return strip_tags($param);
884 case PARAM_TEXT:
885 // Leave only tags needed for multilang.
886 $param = fix_utf8($param);
887 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
888 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
889 do {
890 if (strpos($param, '</lang>') !== false) {
891 // Old and future mutilang syntax.
892 $param = strip_tags($param, '<lang>');
893 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
894 break;
896 $open = false;
897 foreach ($matches[0] as $match) {
898 if ($match === '</lang>') {
899 if ($open) {
900 $open = false;
901 continue;
902 } else {
903 break 2;
906 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
907 break 2;
908 } else {
909 $open = true;
912 if ($open) {
913 break;
915 return $param;
917 } else if (strpos($param, '</span>') !== false) {
918 // Current problematic multilang syntax.
919 $param = strip_tags($param, '<span>');
920 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
921 break;
923 $open = false;
924 foreach ($matches[0] as $match) {
925 if ($match === '</span>') {
926 if ($open) {
927 $open = false;
928 continue;
929 } else {
930 break 2;
933 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
934 break 2;
935 } else {
936 $open = true;
939 if ($open) {
940 break;
942 return $param;
944 } while (false);
945 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
946 return strip_tags($param);
948 case PARAM_COMPONENT:
949 // We do not want any guessing here, either the name is correct or not
950 // please note only normalised component names are accepted.
951 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
952 return '';
954 if (strpos($param, '__') !== false) {
955 return '';
957 if (strpos($param, 'mod_') === 0) {
958 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
959 if (substr_count($param, '_') != 1) {
960 return '';
963 return $param;
965 case PARAM_PLUGIN:
966 case PARAM_AREA:
967 // We do not want any guessing here, either the name is correct or not.
968 if (!is_valid_plugin_name($param)) {
969 return '';
971 return $param;
973 case PARAM_SAFEDIR:
974 // Remove everything not a-zA-Z0-9_- .
975 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
977 case PARAM_SAFEPATH:
978 // Remove everything not a-zA-Z0-9/_- .
979 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
981 case PARAM_FILE:
982 // Strip all suspicious characters from filename.
983 $param = fix_utf8($param);
984 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
985 if ($param === '.' || $param === '..') {
986 $param = '';
988 return $param;
990 case PARAM_PATH:
991 // Strip all suspicious characters from file path.
992 $param = fix_utf8($param);
993 $param = str_replace('\\', '/', $param);
995 // Explode the path and clean each element using the PARAM_FILE rules.
996 $breadcrumb = explode('/', $param);
997 foreach ($breadcrumb as $key => $crumb) {
998 if ($crumb === '.' && $key === 0) {
999 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1000 } else {
1001 $crumb = clean_param($crumb, PARAM_FILE);
1003 $breadcrumb[$key] = $crumb;
1005 $param = implode('/', $breadcrumb);
1007 // Remove multiple current path (./././) and multiple slashes (///).
1008 $param = preg_replace('~//+~', '/', $param);
1009 $param = preg_replace('~/(\./)+~', '/', $param);
1010 return $param;
1012 case PARAM_HOST:
1013 // Allow FQDN or IPv4 dotted quad.
1014 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1015 // Match ipv4 dotted quad.
1016 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1017 // Confirm values are ok.
1018 if ( $match[0] > 255
1019 || $match[1] > 255
1020 || $match[3] > 255
1021 || $match[4] > 255 ) {
1022 // Hmmm, what kind of dotted quad is this?
1023 $param = '';
1025 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1026 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1027 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1029 // All is ok - $param is respected.
1030 } else {
1031 // All is not ok...
1032 $param='';
1034 return $param;
1036 case PARAM_URL: // Allow safe ftp, http, mailto urls.
1037 $param = fix_utf8($param);
1038 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1039 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1040 // All is ok, param is respected.
1041 } else {
1042 // Not really ok.
1043 $param ='';
1045 return $param;
1047 case PARAM_LOCALURL:
1048 // Allow http absolute, root relative and relative URLs within wwwroot.
1049 $param = clean_param($param, PARAM_URL);
1050 if (!empty($param)) {
1052 // Simulate the HTTPS version of the site.
1053 $httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot);
1055 if ($param === $CFG->wwwroot) {
1056 // Exact match;
1057 } else if (!empty($CFG->loginhttps) && $param === $httpswwwroot) {
1058 // Exact match;
1059 } else if (preg_match(':^/:', $param)) {
1060 // Root-relative, ok!
1061 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1062 // Absolute, and matches our wwwroot.
1063 } else if (!empty($CFG->loginhttps) && preg_match('/^' . preg_quote($httpswwwroot . '/', '/') . '/i', $param)) {
1064 // Absolute, and matches our httpswwwroot.
1065 } else {
1066 // Relative - let's make sure there are no tricks.
1067 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1068 // Looks ok.
1069 } else {
1070 $param = '';
1074 return $param;
1076 case PARAM_PEM:
1077 $param = trim($param);
1078 // PEM formatted strings may contain letters/numbers and the symbols:
1079 // forward slash: /
1080 // plus sign: +
1081 // equal sign: =
1082 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1083 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1084 list($wholething, $body) = $matches;
1085 unset($wholething, $matches);
1086 $b64 = clean_param($body, PARAM_BASE64);
1087 if (!empty($b64)) {
1088 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1089 } else {
1090 return '';
1093 return '';
1095 case PARAM_BASE64:
1096 if (!empty($param)) {
1097 // PEM formatted strings may contain letters/numbers and the symbols
1098 // forward slash: /
1099 // plus sign: +
1100 // equal sign: =.
1101 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1102 return '';
1104 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1105 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1106 // than (or equal to) 64 characters long.
1107 for ($i=0, $j=count($lines); $i < $j; $i++) {
1108 if ($i + 1 == $j) {
1109 if (64 < strlen($lines[$i])) {
1110 return '';
1112 continue;
1115 if (64 != strlen($lines[$i])) {
1116 return '';
1119 return implode("\n", $lines);
1120 } else {
1121 return '';
1124 case PARAM_TAG:
1125 $param = fix_utf8($param);
1126 // Please note it is not safe to use the tag name directly anywhere,
1127 // it must be processed with s(), urlencode() before embedding anywhere.
1128 // Remove some nasties.
1129 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1130 // Convert many whitespace chars into one.
1131 $param = preg_replace('/\s+/u', ' ', $param);
1132 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1133 return $param;
1135 case PARAM_TAGLIST:
1136 $param = fix_utf8($param);
1137 $tags = explode(',', $param);
1138 $result = array();
1139 foreach ($tags as $tag) {
1140 $res = clean_param($tag, PARAM_TAG);
1141 if ($res !== '') {
1142 $result[] = $res;
1145 if ($result) {
1146 return implode(',', $result);
1147 } else {
1148 return '';
1151 case PARAM_CAPABILITY:
1152 if (get_capability_info($param)) {
1153 return $param;
1154 } else {
1155 return '';
1158 case PARAM_PERMISSION:
1159 $param = (int)$param;
1160 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1161 return $param;
1162 } else {
1163 return CAP_INHERIT;
1166 case PARAM_AUTH:
1167 $param = clean_param($param, PARAM_PLUGIN);
1168 if (empty($param)) {
1169 return '';
1170 } else if (exists_auth_plugin($param)) {
1171 return $param;
1172 } else {
1173 return '';
1176 case PARAM_LANG:
1177 $param = clean_param($param, PARAM_SAFEDIR);
1178 if (get_string_manager()->translation_exists($param)) {
1179 return $param;
1180 } else {
1181 // Specified language is not installed or param malformed.
1182 return '';
1185 case PARAM_THEME:
1186 $param = clean_param($param, PARAM_PLUGIN);
1187 if (empty($param)) {
1188 return '';
1189 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1190 return $param;
1191 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1192 return $param;
1193 } else {
1194 // Specified theme is not installed.
1195 return '';
1198 case PARAM_USERNAME:
1199 $param = fix_utf8($param);
1200 $param = trim($param);
1201 // Convert uppercase to lowercase MDL-16919.
1202 $param = core_text::strtolower($param);
1203 if (empty($CFG->extendedusernamechars)) {
1204 $param = str_replace(" " , "", $param);
1205 // Regular expression, eliminate all chars EXCEPT:
1206 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1207 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1209 return $param;
1211 case PARAM_EMAIL:
1212 $param = fix_utf8($param);
1213 if (validate_email($param)) {
1214 return $param;
1215 } else {
1216 return '';
1219 case PARAM_STRINGID:
1220 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1221 return $param;
1222 } else {
1223 return '';
1226 case PARAM_TIMEZONE:
1227 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1228 $param = fix_utf8($param);
1229 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1230 if (preg_match($timezonepattern, $param)) {
1231 return $param;
1232 } else {
1233 return '';
1236 default:
1237 // Doh! throw error, switched parameters in optional_param or another serious problem.
1238 print_error("unknownparamtype", '', '', $type);
1243 * Whether the PARAM_* type is compatible in RTL.
1245 * Being compatible with RTL means that the data they contain can flow
1246 * from right-to-left or left-to-right without compromising the user experience.
1248 * Take URLs for example, they are not RTL compatible as they should always
1249 * flow from the left to the right. This also applies to numbers, email addresses,
1250 * configuration snippets, base64 strings, etc...
1252 * This function tries to best guess which parameters can contain localised strings.
1254 * @param string $paramtype Constant PARAM_*.
1255 * @return bool
1257 function is_rtl_compatible($paramtype) {
1258 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1262 * Makes sure the data is using valid utf8, invalid characters are discarded.
1264 * Note: this function is not intended for full objects with methods and private properties.
1266 * @param mixed $value
1267 * @return mixed with proper utf-8 encoding
1269 function fix_utf8($value) {
1270 if (is_null($value) or $value === '') {
1271 return $value;
1273 } else if (is_string($value)) {
1274 if ((string)(int)$value === $value) {
1275 // Shortcut.
1276 return $value;
1278 // No null bytes expected in our data, so let's remove it.
1279 $value = str_replace("\0", '', $value);
1281 // Note: this duplicates min_fix_utf8() intentionally.
1282 static $buggyiconv = null;
1283 if ($buggyiconv === null) {
1284 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1287 if ($buggyiconv) {
1288 if (function_exists('mb_convert_encoding')) {
1289 $subst = mb_substitute_character();
1290 mb_substitute_character('');
1291 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1292 mb_substitute_character($subst);
1294 } else {
1295 // Warn admins on admin/index.php page.
1296 $result = $value;
1299 } else {
1300 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1303 return $result;
1305 } else if (is_array($value)) {
1306 foreach ($value as $k => $v) {
1307 $value[$k] = fix_utf8($v);
1309 return $value;
1311 } else if (is_object($value)) {
1312 // Do not modify original.
1313 $value = clone($value);
1314 foreach ($value as $k => $v) {
1315 $value->$k = fix_utf8($v);
1317 return $value;
1319 } else {
1320 // This is some other type, no utf-8 here.
1321 return $value;
1326 * Return true if given value is integer or string with integer value
1328 * @param mixed $value String or Int
1329 * @return bool true if number, false if not
1331 function is_number($value) {
1332 if (is_int($value)) {
1333 return true;
1334 } else if (is_string($value)) {
1335 return ((string)(int)$value) === $value;
1336 } else {
1337 return false;
1342 * Returns host part from url.
1344 * @param string $url full url
1345 * @return string host, null if not found
1347 function get_host_from_url($url) {
1348 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1349 if ($matches) {
1350 return $matches[1];
1352 return null;
1356 * Tests whether anything was returned by text editor
1358 * This function is useful for testing whether something you got back from
1359 * the HTML editor actually contains anything. Sometimes the HTML editor
1360 * appear to be empty, but actually you get back a <br> tag or something.
1362 * @param string $string a string containing HTML.
1363 * @return boolean does the string contain any actual content - that is text,
1364 * images, objects, etc.
1366 function html_is_blank($string) {
1367 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1371 * Set a key in global configuration
1373 * Set a key/value pair in both this session's {@link $CFG} global variable
1374 * and in the 'config' database table for future sessions.
1376 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1377 * In that case it doesn't affect $CFG.
1379 * A NULL value will delete the entry.
1381 * NOTE: this function is called from lib/db/upgrade.php
1383 * @param string $name the key to set
1384 * @param string $value the value to set (without magic quotes)
1385 * @param string $plugin (optional) the plugin scope, default null
1386 * @return bool true or exception
1388 function set_config($name, $value, $plugin=null) {
1389 global $CFG, $DB;
1391 if (empty($plugin)) {
1392 if (!array_key_exists($name, $CFG->config_php_settings)) {
1393 // So it's defined for this invocation at least.
1394 if (is_null($value)) {
1395 unset($CFG->$name);
1396 } else {
1397 // Settings from db are always strings.
1398 $CFG->$name = (string)$value;
1402 if ($DB->get_field('config', 'name', array('name' => $name))) {
1403 if ($value === null) {
1404 $DB->delete_records('config', array('name' => $name));
1405 } else {
1406 $DB->set_field('config', 'value', $value, array('name' => $name));
1408 } else {
1409 if ($value !== null) {
1410 $config = new stdClass();
1411 $config->name = $name;
1412 $config->value = $value;
1413 $DB->insert_record('config', $config, false);
1416 if ($name === 'siteidentifier') {
1417 cache_helper::update_site_identifier($value);
1419 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1420 } else {
1421 // Plugin scope.
1422 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1423 if ($value===null) {
1424 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1425 } else {
1426 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1428 } else {
1429 if ($value !== null) {
1430 $config = new stdClass();
1431 $config->plugin = $plugin;
1432 $config->name = $name;
1433 $config->value = $value;
1434 $DB->insert_record('config_plugins', $config, false);
1437 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1440 return true;
1444 * Get configuration values from the global config table
1445 * or the config_plugins table.
1447 * If called with one parameter, it will load all the config
1448 * variables for one plugin, and return them as an object.
1450 * If called with 2 parameters it will return a string single
1451 * value or false if the value is not found.
1453 * NOTE: this function is called from lib/db/upgrade.php
1455 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1456 * that we need only fetch it once per request.
1457 * @param string $plugin full component name
1458 * @param string $name default null
1459 * @return mixed hash-like object or single value, return false no config found
1460 * @throws dml_exception
1462 function get_config($plugin, $name = null) {
1463 global $CFG, $DB;
1465 static $siteidentifier = null;
1467 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1468 $forced =& $CFG->config_php_settings;
1469 $iscore = true;
1470 $plugin = 'core';
1471 } else {
1472 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1473 $forced =& $CFG->forced_plugin_settings[$plugin];
1474 } else {
1475 $forced = array();
1477 $iscore = false;
1480 if ($siteidentifier === null) {
1481 try {
1482 // This may fail during installation.
1483 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1484 // install the database.
1485 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1486 } catch (dml_exception $ex) {
1487 // Set siteidentifier to false. We don't want to trip this continually.
1488 $siteidentifier = false;
1489 throw $ex;
1493 if (!empty($name)) {
1494 if (array_key_exists($name, $forced)) {
1495 return (string)$forced[$name];
1496 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1497 return $siteidentifier;
1501 $cache = cache::make('core', 'config');
1502 $result = $cache->get($plugin);
1503 if ($result === false) {
1504 // The user is after a recordset.
1505 if (!$iscore) {
1506 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1507 } else {
1508 // This part is not really used any more, but anyway...
1509 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1511 $cache->set($plugin, $result);
1514 if (!empty($name)) {
1515 if (array_key_exists($name, $result)) {
1516 return $result[$name];
1518 return false;
1521 if ($plugin === 'core') {
1522 $result['siteidentifier'] = $siteidentifier;
1525 foreach ($forced as $key => $value) {
1526 if (is_null($value) or is_array($value) or is_object($value)) {
1527 // We do not want any extra mess here, just real settings that could be saved in db.
1528 unset($result[$key]);
1529 } else {
1530 // Convert to string as if it went through the DB.
1531 $result[$key] = (string)$value;
1535 return (object)$result;
1539 * Removes a key from global configuration.
1541 * NOTE: this function is called from lib/db/upgrade.php
1543 * @param string $name the key to set
1544 * @param string $plugin (optional) the plugin scope
1545 * @return boolean whether the operation succeeded.
1547 function unset_config($name, $plugin=null) {
1548 global $CFG, $DB;
1550 if (empty($plugin)) {
1551 unset($CFG->$name);
1552 $DB->delete_records('config', array('name' => $name));
1553 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1554 } else {
1555 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1556 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1559 return true;
1563 * Remove all the config variables for a given plugin.
1565 * NOTE: this function is called from lib/db/upgrade.php
1567 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1568 * @return boolean whether the operation succeeded.
1570 function unset_all_config_for_plugin($plugin) {
1571 global $DB;
1572 // Delete from the obvious config_plugins first.
1573 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1574 // Next delete any suspect settings from config.
1575 $like = $DB->sql_like('name', '?', true, true, false, '|');
1576 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1577 $DB->delete_records_select('config', $like, $params);
1578 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1579 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1581 return true;
1585 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1587 * All users are verified if they still have the necessary capability.
1589 * @param string $value the value of the config setting.
1590 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1591 * @param bool $includeadmins include administrators.
1592 * @return array of user objects.
1594 function get_users_from_config($value, $capability, $includeadmins = true) {
1595 if (empty($value) or $value === '$@NONE@$') {
1596 return array();
1599 // We have to make sure that users still have the necessary capability,
1600 // it should be faster to fetch them all first and then test if they are present
1601 // instead of validating them one-by-one.
1602 $users = get_users_by_capability(context_system::instance(), $capability);
1603 if ($includeadmins) {
1604 $admins = get_admins();
1605 foreach ($admins as $admin) {
1606 $users[$admin->id] = $admin;
1610 if ($value === '$@ALL@$') {
1611 return $users;
1614 $result = array(); // Result in correct order.
1615 $allowed = explode(',', $value);
1616 foreach ($allowed as $uid) {
1617 if (isset($users[$uid])) {
1618 $user = $users[$uid];
1619 $result[$user->id] = $user;
1623 return $result;
1628 * Invalidates browser caches and cached data in temp.
1630 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1631 * {@link phpunit_util::reset_dataroot()}
1633 * @return void
1635 function purge_all_caches() {
1636 global $CFG, $DB;
1638 reset_text_filters_cache();
1639 js_reset_all_caches();
1640 theme_reset_all_caches();
1641 get_string_manager()->reset_caches();
1642 core_text::reset_caches();
1643 if (class_exists('core_plugin_manager')) {
1644 core_plugin_manager::reset_caches();
1647 // Bump up cacherev field for all courses.
1648 try {
1649 increment_revision_number('course', 'cacherev', '');
1650 } catch (moodle_exception $e) {
1651 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1654 $DB->reset_caches();
1655 cache_helper::purge_all();
1657 // Purge all other caches: rss, simplepie, etc.
1658 clearstatcache();
1659 remove_dir($CFG->cachedir.'', true);
1661 // Make sure cache dir is writable, throws exception if not.
1662 make_cache_directory('');
1664 // This is the only place where we purge local caches, we are only adding files there.
1665 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1666 remove_dir($CFG->localcachedir, true);
1667 set_config('localcachedirpurged', time());
1668 make_localcache_directory('', true);
1669 \core\task\manager::clear_static_caches();
1673 * Get volatile flags
1675 * @param string $type
1676 * @param int $changedsince default null
1677 * @return array records array
1679 function get_cache_flags($type, $changedsince = null) {
1680 global $DB;
1682 $params = array('type' => $type, 'expiry' => time());
1683 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1684 if ($changedsince !== null) {
1685 $params['changedsince'] = $changedsince;
1686 $sqlwhere .= " AND timemodified > :changedsince";
1688 $cf = array();
1689 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1690 foreach ($flags as $flag) {
1691 $cf[$flag->name] = $flag->value;
1694 return $cf;
1698 * Get volatile flags
1700 * @param string $type
1701 * @param string $name
1702 * @param int $changedsince default null
1703 * @return string|false The cache flag value or false
1705 function get_cache_flag($type, $name, $changedsince=null) {
1706 global $DB;
1708 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1710 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1711 if ($changedsince !== null) {
1712 $params['changedsince'] = $changedsince;
1713 $sqlwhere .= " AND timemodified > :changedsince";
1716 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1720 * Set a volatile flag
1722 * @param string $type the "type" namespace for the key
1723 * @param string $name the key to set
1724 * @param string $value the value to set (without magic quotes) - null will remove the flag
1725 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1726 * @return bool Always returns true
1728 function set_cache_flag($type, $name, $value, $expiry = null) {
1729 global $DB;
1731 $timemodified = time();
1732 if ($expiry === null || $expiry < $timemodified) {
1733 $expiry = $timemodified + 24 * 60 * 60;
1734 } else {
1735 $expiry = (int)$expiry;
1738 if ($value === null) {
1739 unset_cache_flag($type, $name);
1740 return true;
1743 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1744 // This is a potential problem in DEBUG_DEVELOPER.
1745 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1746 return true; // No need to update.
1748 $f->value = $value;
1749 $f->expiry = $expiry;
1750 $f->timemodified = $timemodified;
1751 $DB->update_record('cache_flags', $f);
1752 } else {
1753 $f = new stdClass();
1754 $f->flagtype = $type;
1755 $f->name = $name;
1756 $f->value = $value;
1757 $f->expiry = $expiry;
1758 $f->timemodified = $timemodified;
1759 $DB->insert_record('cache_flags', $f);
1761 return true;
1765 * Removes a single volatile flag
1767 * @param string $type the "type" namespace for the key
1768 * @param string $name the key to set
1769 * @return bool
1771 function unset_cache_flag($type, $name) {
1772 global $DB;
1773 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1774 return true;
1778 * Garbage-collect volatile flags
1780 * @return bool Always returns true
1782 function gc_cache_flags() {
1783 global $DB;
1784 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1785 return true;
1788 // USER PREFERENCE API.
1791 * Refresh user preference cache. This is used most often for $USER
1792 * object that is stored in session, but it also helps with performance in cron script.
1794 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1796 * @package core
1797 * @category preference
1798 * @access public
1799 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1800 * @param int $cachelifetime Cache life time on the current page (in seconds)
1801 * @throws coding_exception
1802 * @return null
1804 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1805 global $DB;
1806 // Static cache, we need to check on each page load, not only every 2 minutes.
1807 static $loadedusers = array();
1809 if (!isset($user->id)) {
1810 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1813 if (empty($user->id) or isguestuser($user->id)) {
1814 // No permanent storage for not-logged-in users and guest.
1815 if (!isset($user->preference)) {
1816 $user->preference = array();
1818 return;
1821 $timenow = time();
1823 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1824 // Already loaded at least once on this page. Are we up to date?
1825 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1826 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1827 return;
1829 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1830 // No change since the lastcheck on this page.
1831 $user->preference['_lastloaded'] = $timenow;
1832 return;
1836 // OK, so we have to reload all preferences.
1837 $loadedusers[$user->id] = true;
1838 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1839 $user->preference['_lastloaded'] = $timenow;
1843 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1845 * NOTE: internal function, do not call from other code.
1847 * @package core
1848 * @access private
1849 * @param integer $userid the user whose prefs were changed.
1851 function mark_user_preferences_changed($userid) {
1852 global $CFG;
1854 if (empty($userid) or isguestuser($userid)) {
1855 // No cache flags for guest and not-logged-in users.
1856 return;
1859 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1863 * Sets a preference for the specified user.
1865 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1867 * @package core
1868 * @category preference
1869 * @access public
1870 * @param string $name The key to set as preference for the specified user
1871 * @param string $value The value to set for the $name key in the specified user's
1872 * record, null means delete current value.
1873 * @param stdClass|int|null $user A moodle user object or id, null means current user
1874 * @throws coding_exception
1875 * @return bool Always true or exception
1877 function set_user_preference($name, $value, $user = null) {
1878 global $USER, $DB;
1880 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1881 throw new coding_exception('Invalid preference name in set_user_preference() call');
1884 if (is_null($value)) {
1885 // Null means delete current.
1886 return unset_user_preference($name, $user);
1887 } else if (is_object($value)) {
1888 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1889 } else if (is_array($value)) {
1890 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1892 // Value column maximum length is 1333 characters.
1893 $value = (string)$value;
1894 if (core_text::strlen($value) > 1333) {
1895 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1898 if (is_null($user)) {
1899 $user = $USER;
1900 } else if (isset($user->id)) {
1901 // It is a valid object.
1902 } else if (is_numeric($user)) {
1903 $user = (object)array('id' => (int)$user);
1904 } else {
1905 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1908 check_user_preferences_loaded($user);
1910 if (empty($user->id) or isguestuser($user->id)) {
1911 // No permanent storage for not-logged-in users and guest.
1912 $user->preference[$name] = $value;
1913 return true;
1916 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1917 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1918 // Preference already set to this value.
1919 return true;
1921 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1923 } else {
1924 $preference = new stdClass();
1925 $preference->userid = $user->id;
1926 $preference->name = $name;
1927 $preference->value = $value;
1928 $DB->insert_record('user_preferences', $preference);
1931 // Update value in cache.
1932 $user->preference[$name] = $value;
1934 // Set reload flag for other sessions.
1935 mark_user_preferences_changed($user->id);
1937 return true;
1941 * Sets a whole array of preferences for the current user
1943 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1945 * @package core
1946 * @category preference
1947 * @access public
1948 * @param array $prefarray An array of key/value pairs to be set
1949 * @param stdClass|int|null $user A moodle user object or id, null means current user
1950 * @return bool Always true or exception
1952 function set_user_preferences(array $prefarray, $user = null) {
1953 foreach ($prefarray as $name => $value) {
1954 set_user_preference($name, $value, $user);
1956 return true;
1960 * Unsets a preference completely by deleting it from the database
1962 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1964 * @package core
1965 * @category preference
1966 * @access public
1967 * @param string $name The key to unset as preference for the specified user
1968 * @param stdClass|int|null $user A moodle user object or id, null means current user
1969 * @throws coding_exception
1970 * @return bool Always true or exception
1972 function unset_user_preference($name, $user = null) {
1973 global $USER, $DB;
1975 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1976 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1979 if (is_null($user)) {
1980 $user = $USER;
1981 } else if (isset($user->id)) {
1982 // It is a valid object.
1983 } else if (is_numeric($user)) {
1984 $user = (object)array('id' => (int)$user);
1985 } else {
1986 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1989 check_user_preferences_loaded($user);
1991 if (empty($user->id) or isguestuser($user->id)) {
1992 // No permanent storage for not-logged-in user and guest.
1993 unset($user->preference[$name]);
1994 return true;
1997 // Delete from DB.
1998 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2000 // Delete the preference from cache.
2001 unset($user->preference[$name]);
2003 // Set reload flag for other sessions.
2004 mark_user_preferences_changed($user->id);
2006 return true;
2010 * Used to fetch user preference(s)
2012 * If no arguments are supplied this function will return
2013 * all of the current user preferences as an array.
2015 * If a name is specified then this function
2016 * attempts to return that particular preference value. If
2017 * none is found, then the optional value $default is returned,
2018 * otherwise null.
2020 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2022 * @package core
2023 * @category preference
2024 * @access public
2025 * @param string $name Name of the key to use in finding a preference value
2026 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2027 * @param stdClass|int|null $user A moodle user object or id, null means current user
2028 * @throws coding_exception
2029 * @return string|mixed|null A string containing the value of a single preference. An
2030 * array with all of the preferences or null
2032 function get_user_preferences($name = null, $default = null, $user = null) {
2033 global $USER;
2035 if (is_null($name)) {
2036 // All prefs.
2037 } else if (is_numeric($name) or $name === '_lastloaded') {
2038 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2041 if (is_null($user)) {
2042 $user = $USER;
2043 } else if (isset($user->id)) {
2044 // Is a valid object.
2045 } else if (is_numeric($user)) {
2046 $user = (object)array('id' => (int)$user);
2047 } else {
2048 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2051 check_user_preferences_loaded($user);
2053 if (empty($name)) {
2054 // All values.
2055 return $user->preference;
2056 } else if (isset($user->preference[$name])) {
2057 // The single string value.
2058 return $user->preference[$name];
2059 } else {
2060 // Default value (null if not specified).
2061 return $default;
2065 // FUNCTIONS FOR HANDLING TIME.
2068 * Given Gregorian date parts in user time produce a GMT timestamp.
2070 * @package core
2071 * @category time
2072 * @param int $year The year part to create timestamp of
2073 * @param int $month The month part to create timestamp of
2074 * @param int $day The day part to create timestamp of
2075 * @param int $hour The hour part to create timestamp of
2076 * @param int $minute The minute part to create timestamp of
2077 * @param int $second The second part to create timestamp of
2078 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2079 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2080 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2081 * applied only if timezone is 99 or string.
2082 * @return int GMT timestamp
2084 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2085 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2086 $date->setDate((int)$year, (int)$month, (int)$day);
2087 $date->setTime((int)$hour, (int)$minute, (int)$second);
2089 $time = $date->getTimestamp();
2091 if ($time === false) {
2092 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2093 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2096 // Moodle BC DST stuff.
2097 if (!$applydst) {
2098 $time += dst_offset_on($time, $timezone);
2101 return $time;
2106 * Format a date/time (seconds) as weeks, days, hours etc as needed
2108 * Given an amount of time in seconds, returns string
2109 * formatted nicely as weeks, days, hours etc as needed
2111 * @package core
2112 * @category time
2113 * @uses MINSECS
2114 * @uses HOURSECS
2115 * @uses DAYSECS
2116 * @uses YEARSECS
2117 * @param int $totalsecs Time in seconds
2118 * @param stdClass $str Should be a time object
2119 * @return string A nicely formatted date/time string
2121 function format_time($totalsecs, $str = null) {
2123 $totalsecs = abs($totalsecs);
2125 if (!$str) {
2126 // Create the str structure the slow way.
2127 $str = new stdClass();
2128 $str->day = get_string('day');
2129 $str->days = get_string('days');
2130 $str->hour = get_string('hour');
2131 $str->hours = get_string('hours');
2132 $str->min = get_string('min');
2133 $str->mins = get_string('mins');
2134 $str->sec = get_string('sec');
2135 $str->secs = get_string('secs');
2136 $str->year = get_string('year');
2137 $str->years = get_string('years');
2140 $years = floor($totalsecs/YEARSECS);
2141 $remainder = $totalsecs - ($years*YEARSECS);
2142 $days = floor($remainder/DAYSECS);
2143 $remainder = $totalsecs - ($days*DAYSECS);
2144 $hours = floor($remainder/HOURSECS);
2145 $remainder = $remainder - ($hours*HOURSECS);
2146 $mins = floor($remainder/MINSECS);
2147 $secs = $remainder - ($mins*MINSECS);
2149 $ss = ($secs == 1) ? $str->sec : $str->secs;
2150 $sm = ($mins == 1) ? $str->min : $str->mins;
2151 $sh = ($hours == 1) ? $str->hour : $str->hours;
2152 $sd = ($days == 1) ? $str->day : $str->days;
2153 $sy = ($years == 1) ? $str->year : $str->years;
2155 $oyears = '';
2156 $odays = '';
2157 $ohours = '';
2158 $omins = '';
2159 $osecs = '';
2161 if ($years) {
2162 $oyears = $years .' '. $sy;
2164 if ($days) {
2165 $odays = $days .' '. $sd;
2167 if ($hours) {
2168 $ohours = $hours .' '. $sh;
2170 if ($mins) {
2171 $omins = $mins .' '. $sm;
2173 if ($secs) {
2174 $osecs = $secs .' '. $ss;
2177 if ($years) {
2178 return trim($oyears .' '. $odays);
2180 if ($days) {
2181 return trim($odays .' '. $ohours);
2183 if ($hours) {
2184 return trim($ohours .' '. $omins);
2186 if ($mins) {
2187 return trim($omins .' '. $osecs);
2189 if ($secs) {
2190 return $osecs;
2192 return get_string('now');
2196 * Returns a formatted string that represents a date in user time.
2198 * @package core
2199 * @category time
2200 * @param int $date the timestamp in UTC, as obtained from the database.
2201 * @param string $format strftime format. You should probably get this using
2202 * get_string('strftime...', 'langconfig');
2203 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2204 * not 99 then daylight saving will not be added.
2205 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2206 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2207 * If false then the leading zero is maintained.
2208 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2209 * @return string the formatted date/time.
2211 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2212 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2213 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2217 * Returns a formatted date ensuring it is UTF-8.
2219 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2220 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2222 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2223 * @param string $format strftime format.
2224 * @param int|float|string $tz the user timezone
2225 * @return string the formatted date/time.
2226 * @since Moodle 2.3.3
2228 function date_format_string($date, $format, $tz = 99) {
2229 global $CFG;
2231 $localewincharset = null;
2232 // Get the calendar type user is using.
2233 if ($CFG->ostype == 'WINDOWS') {
2234 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2235 $localewincharset = $calendartype->locale_win_charset();
2238 if ($localewincharset) {
2239 $format = core_text::convert($format, 'utf-8', $localewincharset);
2242 date_default_timezone_set(core_date::get_user_timezone($tz));
2243 $datestring = strftime($format, $date);
2244 core_date::set_default_server_timezone();
2246 if ($localewincharset) {
2247 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2250 return $datestring;
2254 * Given a $time timestamp in GMT (seconds since epoch),
2255 * returns an array that represents the Gregorian date in user time
2257 * @package core
2258 * @category time
2259 * @param int $time Timestamp in GMT
2260 * @param float|int|string $timezone user timezone
2261 * @return array An array that represents the date in user time
2263 function usergetdate($time, $timezone=99) {
2264 date_default_timezone_set(core_date::get_user_timezone($timezone));
2265 $result = getdate($time);
2266 core_date::set_default_server_timezone();
2268 return $result;
2272 * Given a GMT timestamp (seconds since epoch), offsets it by
2273 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2275 * NOTE: this function does not include DST properly,
2276 * you should use the PHP date stuff instead!
2278 * @package core
2279 * @category time
2280 * @param int $date Timestamp in GMT
2281 * @param float|int|string $timezone user timezone
2282 * @return int
2284 function usertime($date, $timezone=99) {
2285 $userdate = new DateTime('@' . $date);
2286 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2287 $dst = dst_offset_on($date, $timezone);
2289 return $date - $userdate->getOffset() + $dst;
2293 * Given a time, return the GMT timestamp of the most recent midnight
2294 * for the current user.
2296 * @package core
2297 * @category time
2298 * @param int $date Timestamp in GMT
2299 * @param float|int|string $timezone user timezone
2300 * @return int Returns a GMT timestamp
2302 function usergetmidnight($date, $timezone=99) {
2304 $userdate = usergetdate($date, $timezone);
2306 // Time of midnight of this user's day, in GMT.
2307 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2312 * Returns a string that prints the user's timezone
2314 * @package core
2315 * @category time
2316 * @param float|int|string $timezone user timezone
2317 * @return string
2319 function usertimezone($timezone=99) {
2320 $tz = core_date::get_user_timezone($timezone);
2321 return core_date::get_localised_timezone($tz);
2325 * Returns a float or a string which denotes the user's timezone
2326 * 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)
2327 * means that for this timezone there are also DST rules to be taken into account
2328 * Checks various settings and picks the most dominant of those which have a value
2330 * @package core
2331 * @category time
2332 * @param float|int|string $tz timezone to calculate GMT time offset before
2333 * calculating user timezone, 99 is default user timezone
2334 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2335 * @return float|string
2337 function get_user_timezone($tz = 99) {
2338 global $USER, $CFG;
2340 $timezones = array(
2341 $tz,
2342 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2343 isset($USER->timezone) ? $USER->timezone : 99,
2344 isset($CFG->timezone) ? $CFG->timezone : 99,
2347 $tz = 99;
2349 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2350 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2351 $tz = $next['value'];
2353 return is_numeric($tz) ? (float) $tz : $tz;
2357 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2358 * - Note: Daylight saving only works for string timezones and not for float.
2360 * @package core
2361 * @category time
2362 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2363 * @param int|float|string $strtimezone user timezone
2364 * @return int
2366 function dst_offset_on($time, $strtimezone = null) {
2367 $tz = core_date::get_user_timezone($strtimezone);
2368 $date = new DateTime('@' . $time);
2369 $date->setTimezone(new DateTimeZone($tz));
2370 if ($date->format('I') == '1') {
2371 if ($tz === 'Australia/Lord_Howe') {
2372 return 1800;
2374 return 3600;
2376 return 0;
2380 * Calculates when the day appears in specific month
2382 * @package core
2383 * @category time
2384 * @param int $startday starting day of the month
2385 * @param int $weekday The day when week starts (normally taken from user preferences)
2386 * @param int $month The month whose day is sought
2387 * @param int $year The year of the month whose day is sought
2388 * @return int
2390 function find_day_in_month($startday, $weekday, $month, $year) {
2391 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2393 $daysinmonth = days_in_month($month, $year);
2394 $daysinweek = count($calendartype->get_weekdays());
2396 if ($weekday == -1) {
2397 // Don't care about weekday, so return:
2398 // abs($startday) if $startday != -1
2399 // $daysinmonth otherwise.
2400 return ($startday == -1) ? $daysinmonth : abs($startday);
2403 // From now on we 're looking for a specific weekday.
2404 // Give "end of month" its actual value, since we know it.
2405 if ($startday == -1) {
2406 $startday = -1 * $daysinmonth;
2409 // Starting from day $startday, the sign is the direction.
2410 if ($startday < 1) {
2411 $startday = abs($startday);
2412 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2414 // This is the last such weekday of the month.
2415 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2416 if ($lastinmonth > $daysinmonth) {
2417 $lastinmonth -= $daysinweek;
2420 // Find the first such weekday <= $startday.
2421 while ($lastinmonth > $startday) {
2422 $lastinmonth -= $daysinweek;
2425 return $lastinmonth;
2426 } else {
2427 $indexweekday = dayofweek($startday, $month, $year);
2429 $diff = $weekday - $indexweekday;
2430 if ($diff < 0) {
2431 $diff += $daysinweek;
2434 // This is the first such weekday of the month equal to or after $startday.
2435 $firstfromindex = $startday + $diff;
2437 return $firstfromindex;
2442 * Calculate the number of days in a given month
2444 * @package core
2445 * @category time
2446 * @param int $month The month whose day count is sought
2447 * @param int $year The year of the month whose day count is sought
2448 * @return int
2450 function days_in_month($month, $year) {
2451 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2452 return $calendartype->get_num_days_in_month($year, $month);
2456 * Calculate the position in the week of a specific calendar day
2458 * @package core
2459 * @category time
2460 * @param int $day The day of the date whose position in the week is sought
2461 * @param int $month The month of the date whose position in the week is sought
2462 * @param int $year The year of the date whose position in the week is sought
2463 * @return int
2465 function dayofweek($day, $month, $year) {
2466 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2467 return $calendartype->get_weekday($year, $month, $day);
2470 // USER AUTHENTICATION AND LOGIN.
2473 * Returns full login url.
2475 * @return string login url
2477 function get_login_url() {
2478 global $CFG;
2480 $url = "$CFG->wwwroot/login/index.php";
2482 if (!empty($CFG->loginhttps)) {
2483 $url = str_replace('http:', 'https:', $url);
2486 return $url;
2490 * This function checks that the current user is logged in and has the
2491 * required privileges
2493 * This function checks that the current user is logged in, and optionally
2494 * whether they are allowed to be in a particular course and view a particular
2495 * course module.
2496 * If they are not logged in, then it redirects them to the site login unless
2497 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2498 * case they are automatically logged in as guests.
2499 * If $courseid is given and the user is not enrolled in that course then the
2500 * user is redirected to the course enrolment page.
2501 * If $cm is given and the course module is hidden and the user is not a teacher
2502 * in the course then the user is redirected to the course home page.
2504 * When $cm parameter specified, this function sets page layout to 'module'.
2505 * You need to change it manually later if some other layout needed.
2507 * @package core_access
2508 * @category access
2510 * @param mixed $courseorid id of the course or course object
2511 * @param bool $autologinguest default true
2512 * @param object $cm course module object
2513 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2514 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2515 * in order to keep redirects working properly. MDL-14495
2516 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2517 * @return mixed Void, exit, and die depending on path
2518 * @throws coding_exception
2519 * @throws require_login_exception
2521 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2522 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2524 // Must not redirect when byteserving already started.
2525 if (!empty($_SERVER['HTTP_RANGE'])) {
2526 $preventredirect = true;
2529 if (AJAX_SCRIPT) {
2530 // We cannot redirect for AJAX scripts either.
2531 $preventredirect = true;
2534 // Setup global $COURSE, themes, language and locale.
2535 if (!empty($courseorid)) {
2536 if (is_object($courseorid)) {
2537 $course = $courseorid;
2538 } else if ($courseorid == SITEID) {
2539 $course = clone($SITE);
2540 } else {
2541 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2543 if ($cm) {
2544 if ($cm->course != $course->id) {
2545 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2547 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2548 if (!($cm instanceof cm_info)) {
2549 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2550 // db queries so this is not really a performance concern, however it is obviously
2551 // better if you use get_fast_modinfo to get the cm before calling this.
2552 $modinfo = get_fast_modinfo($course);
2553 $cm = $modinfo->get_cm($cm->id);
2556 } else {
2557 // Do not touch global $COURSE via $PAGE->set_course(),
2558 // the reasons is we need to be able to call require_login() at any time!!
2559 $course = $SITE;
2560 if ($cm) {
2561 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2565 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2566 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2567 // risk leading the user back to the AJAX request URL.
2568 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2569 $setwantsurltome = false;
2572 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2573 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2574 if ($preventredirect) {
2575 throw new require_login_session_timeout_exception();
2576 } else {
2577 if ($setwantsurltome) {
2578 $SESSION->wantsurl = qualified_me();
2580 redirect(get_login_url());
2584 // If the user is not even logged in yet then make sure they are.
2585 if (!isloggedin()) {
2586 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2587 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2588 // Misconfigured site guest, just redirect to login page.
2589 redirect(get_login_url());
2590 exit; // Never reached.
2592 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2593 complete_user_login($guest);
2594 $USER->autologinguest = true;
2595 $SESSION->lang = $lang;
2596 } else {
2597 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2598 if ($preventredirect) {
2599 throw new require_login_exception('You are not logged in');
2602 if ($setwantsurltome) {
2603 $SESSION->wantsurl = qualified_me();
2606 $referer = get_local_referer(false);
2607 if (!empty($referer)) {
2608 $SESSION->fromurl = $referer;
2611 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2612 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2613 foreach($authsequence as $authname) {
2614 $authplugin = get_auth_plugin($authname);
2615 $authplugin->pre_loginpage_hook();
2616 if (isloggedin()) {
2617 break;
2621 // If we're still not logged in then go to the login page
2622 if (!isloggedin()) {
2623 redirect(get_login_url());
2624 exit; // Never reached.
2629 // Loginas as redirection if needed.
2630 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2631 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2632 if ($USER->loginascontext->instanceid != $course->id) {
2633 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2638 // Check whether the user should be changing password (but only if it is REALLY them).
2639 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2640 $userauth = get_auth_plugin($USER->auth);
2641 if ($userauth->can_change_password() and !$preventredirect) {
2642 if ($setwantsurltome) {
2643 $SESSION->wantsurl = qualified_me();
2645 if ($changeurl = $userauth->change_password_url()) {
2646 // Use plugin custom url.
2647 redirect($changeurl);
2648 } else {
2649 // Use moodle internal method.
2650 if (empty($CFG->loginhttps)) {
2651 redirect($CFG->wwwroot .'/login/change_password.php');
2652 } else {
2653 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2654 redirect($wwwroot .'/login/change_password.php');
2657 } else if ($userauth->can_change_password()) {
2658 throw new moodle_exception('forcepasswordchangenotice');
2659 } else {
2660 throw new moodle_exception('nopasswordchangeforced', 'auth');
2664 // Check that the user account is properly set up. If we can't redirect to
2665 // edit their profile, perform just the lax check. It will allow them to
2666 // use filepicker on the profile edit page.
2668 if ($preventredirect) {
2669 $usernotfullysetup = user_not_fully_set_up($USER, false);
2670 } else {
2671 $usernotfullysetup = user_not_fully_set_up($USER, true);
2674 if ($usernotfullysetup) {
2675 if ($preventredirect) {
2676 throw new moodle_exception('usernotfullysetup');
2678 if ($setwantsurltome) {
2679 $SESSION->wantsurl = qualified_me();
2681 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2684 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2685 sesskey();
2687 // Do not bother admins with any formalities.
2688 if (is_siteadmin()) {
2689 // Set the global $COURSE.
2690 if ($cm) {
2691 $PAGE->set_cm($cm, $course);
2692 $PAGE->set_pagelayout('incourse');
2693 } else if (!empty($courseorid)) {
2694 $PAGE->set_course($course);
2696 // Set accesstime or the user will appear offline which messes up messaging.
2697 user_accesstime_log($course->id);
2698 return;
2701 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2702 if (!$USER->policyagreed and !is_siteadmin()) {
2703 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2704 if ($preventredirect) {
2705 throw new moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicy);
2707 if ($setwantsurltome) {
2708 $SESSION->wantsurl = qualified_me();
2710 redirect($CFG->wwwroot .'/user/policy.php');
2711 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2712 if ($preventredirect) {
2713 throw new moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicyguest);
2715 if ($setwantsurltome) {
2716 $SESSION->wantsurl = qualified_me();
2718 redirect($CFG->wwwroot .'/user/policy.php');
2722 // Fetch the system context, the course context, and prefetch its child contexts.
2723 $sysctx = context_system::instance();
2724 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2725 if ($cm) {
2726 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2727 } else {
2728 $cmcontext = null;
2731 // If the site is currently under maintenance, then print a message.
2732 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2733 if ($preventredirect) {
2734 throw new require_login_exception('Maintenance in progress');
2736 $PAGE->set_context(null);
2737 print_maintenance_message();
2740 // Make sure the course itself is not hidden.
2741 if ($course->id == SITEID) {
2742 // Frontpage can not be hidden.
2743 } else {
2744 if (is_role_switched($course->id)) {
2745 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2746 } else {
2747 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2748 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2749 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2750 if ($preventredirect) {
2751 throw new require_login_exception('Course is hidden');
2753 $PAGE->set_context(null);
2754 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2755 // the navigation will mess up when trying to find it.
2756 navigation_node::override_active_url(new moodle_url('/'));
2757 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2762 // Is the user enrolled?
2763 if ($course->id == SITEID) {
2764 // Everybody is enrolled on the frontpage.
2765 } else {
2766 if (\core\session\manager::is_loggedinas()) {
2767 // Make sure the REAL person can access this course first.
2768 $realuser = \core\session\manager::get_realuser();
2769 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2770 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2771 if ($preventredirect) {
2772 throw new require_login_exception('Invalid course login-as access');
2774 $PAGE->set_context(null);
2775 echo $OUTPUT->header();
2776 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2780 $access = false;
2782 if (is_role_switched($course->id)) {
2783 // Ok, user had to be inside this course before the switch.
2784 $access = true;
2786 } else if (is_viewing($coursecontext, $USER)) {
2787 // Ok, no need to mess with enrol.
2788 $access = true;
2790 } else {
2791 if (isset($USER->enrol['enrolled'][$course->id])) {
2792 if ($USER->enrol['enrolled'][$course->id] > time()) {
2793 $access = true;
2794 if (isset($USER->enrol['tempguest'][$course->id])) {
2795 unset($USER->enrol['tempguest'][$course->id]);
2796 remove_temp_course_roles($coursecontext);
2798 } else {
2799 // Expired.
2800 unset($USER->enrol['enrolled'][$course->id]);
2803 if (isset($USER->enrol['tempguest'][$course->id])) {
2804 if ($USER->enrol['tempguest'][$course->id] == 0) {
2805 $access = true;
2806 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2807 $access = true;
2808 } else {
2809 // Expired.
2810 unset($USER->enrol['tempguest'][$course->id]);
2811 remove_temp_course_roles($coursecontext);
2815 if (!$access) {
2816 // Cache not ok.
2817 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2818 if ($until !== false) {
2819 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2820 if ($until == 0) {
2821 $until = ENROL_MAX_TIMESTAMP;
2823 $USER->enrol['enrolled'][$course->id] = $until;
2824 $access = true;
2826 } else {
2827 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2828 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2829 $enrols = enrol_get_plugins(true);
2830 // First ask all enabled enrol instances in course if they want to auto enrol user.
2831 foreach ($instances as $instance) {
2832 if (!isset($enrols[$instance->enrol])) {
2833 continue;
2835 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2836 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2837 if ($until !== false) {
2838 if ($until == 0) {
2839 $until = ENROL_MAX_TIMESTAMP;
2841 $USER->enrol['enrolled'][$course->id] = $until;
2842 $access = true;
2843 break;
2846 // If not enrolled yet try to gain temporary guest access.
2847 if (!$access) {
2848 foreach ($instances as $instance) {
2849 if (!isset($enrols[$instance->enrol])) {
2850 continue;
2852 // Get a duration for the guest access, a timestamp in the future or false.
2853 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2854 if ($until !== false and $until > time()) {
2855 $USER->enrol['tempguest'][$course->id] = $until;
2856 $access = true;
2857 break;
2865 if (!$access) {
2866 if ($preventredirect) {
2867 throw new require_login_exception('Not enrolled');
2869 if ($setwantsurltome) {
2870 $SESSION->wantsurl = qualified_me();
2872 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2876 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2877 if ($cm && !$cm->uservisible) {
2878 if ($preventredirect) {
2879 throw new require_login_exception('Activity is hidden');
2881 if ($course->id != SITEID) {
2882 $url = new moodle_url('/course/view.php', array('id' => $course->id));
2883 } else {
2884 $url = new moodle_url('/');
2886 redirect($url, get_string('activityiscurrentlyhidden'));
2889 // Set the global $COURSE.
2890 if ($cm) {
2891 $PAGE->set_cm($cm, $course);
2892 $PAGE->set_pagelayout('incourse');
2893 } else if (!empty($courseorid)) {
2894 $PAGE->set_course($course);
2897 // Finally access granted, update lastaccess times.
2898 user_accesstime_log($course->id);
2903 * This function just makes sure a user is logged out.
2905 * @package core_access
2906 * @category access
2908 function require_logout() {
2909 global $USER, $DB;
2911 if (!isloggedin()) {
2912 // This should not happen often, no need for hooks or events here.
2913 \core\session\manager::terminate_current();
2914 return;
2917 // Execute hooks before action.
2918 $authplugins = array();
2919 $authsequence = get_enabled_auth_plugins();
2920 foreach ($authsequence as $authname) {
2921 $authplugins[$authname] = get_auth_plugin($authname);
2922 $authplugins[$authname]->prelogout_hook();
2925 // Store info that gets removed during logout.
2926 $sid = session_id();
2927 $event = \core\event\user_loggedout::create(
2928 array(
2929 'userid' => $USER->id,
2930 'objectid' => $USER->id,
2931 'other' => array('sessionid' => $sid),
2934 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2935 $event->add_record_snapshot('sessions', $session);
2938 // Clone of $USER object to be used by auth plugins.
2939 $user = fullclone($USER);
2941 // Delete session record and drop $_SESSION content.
2942 \core\session\manager::terminate_current();
2944 // Trigger event AFTER action.
2945 $event->trigger();
2947 // Hook to execute auth plugins redirection after event trigger.
2948 foreach ($authplugins as $authplugin) {
2949 $authplugin->postlogout_hook($user);
2954 * Weaker version of require_login()
2956 * This is a weaker version of {@link require_login()} which only requires login
2957 * when called from within a course rather than the site page, unless
2958 * the forcelogin option is turned on.
2959 * @see require_login()
2961 * @package core_access
2962 * @category access
2964 * @param mixed $courseorid The course object or id in question
2965 * @param bool $autologinguest Allow autologin guests if that is wanted
2966 * @param object $cm Course activity module if known
2967 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2968 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2969 * in order to keep redirects working properly. MDL-14495
2970 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2971 * @return void
2972 * @throws coding_exception
2974 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2975 global $CFG, $PAGE, $SITE;
2976 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
2977 or (!is_object($courseorid) and $courseorid == SITEID));
2978 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2979 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2980 // db queries so this is not really a performance concern, however it is obviously
2981 // better if you use get_fast_modinfo to get the cm before calling this.
2982 if (is_object($courseorid)) {
2983 $course = $courseorid;
2984 } else {
2985 $course = clone($SITE);
2987 $modinfo = get_fast_modinfo($course);
2988 $cm = $modinfo->get_cm($cm->id);
2990 if (!empty($CFG->forcelogin)) {
2991 // Login required for both SITE and courses.
2992 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2994 } else if ($issite && !empty($cm) and !$cm->uservisible) {
2995 // Always login for hidden activities.
2996 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2998 } else if ($issite) {
2999 // Login for SITE not required.
3000 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3001 if (!empty($courseorid)) {
3002 if (is_object($courseorid)) {
3003 $course = $courseorid;
3004 } else {
3005 $course = clone $SITE;
3007 if ($cm) {
3008 if ($cm->course != $course->id) {
3009 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3011 $PAGE->set_cm($cm, $course);
3012 $PAGE->set_pagelayout('incourse');
3013 } else {
3014 $PAGE->set_course($course);
3016 } else {
3017 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3018 $PAGE->set_course($PAGE->course);
3020 user_accesstime_log(SITEID);
3021 return;
3023 } else {
3024 // Course login always required.
3025 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3030 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3032 * @param string $keyvalue the key value
3033 * @param string $script unique script identifier
3034 * @param int $instance instance id
3035 * @return stdClass the key entry in the user_private_key table
3036 * @since Moodle 3.2
3037 * @throws moodle_exception
3039 function validate_user_key($keyvalue, $script, $instance) {
3040 global $DB;
3042 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3043 print_error('invalidkey');
3046 if (!empty($key->validuntil) and $key->validuntil < time()) {
3047 print_error('expiredkey');
3050 if ($key->iprestriction) {
3051 $remoteaddr = getremoteaddr(null);
3052 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3053 print_error('ipmismatch');
3056 return $key;
3060 * Require key login. Function terminates with error if key not found or incorrect.
3062 * @uses NO_MOODLE_COOKIES
3063 * @uses PARAM_ALPHANUM
3064 * @param string $script unique script identifier
3065 * @param int $instance optional instance id
3066 * @return int Instance ID
3068 function require_user_key_login($script, $instance=null) {
3069 global $DB;
3071 if (!NO_MOODLE_COOKIES) {
3072 print_error('sessioncookiesdisable');
3075 // Extra safety.
3076 \core\session\manager::write_close();
3078 $keyvalue = required_param('key', PARAM_ALPHANUM);
3080 $key = validate_user_key($keyvalue, $script, $instance);
3082 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3083 print_error('invaliduserid');
3086 // Emulate normal session.
3087 enrol_check_plugins($user);
3088 \core\session\manager::set_user($user);
3090 // Note we are not using normal login.
3091 if (!defined('USER_KEY_LOGIN')) {
3092 define('USER_KEY_LOGIN', true);
3095 // Return instance id - it might be empty.
3096 return $key->instance;
3100 * Creates a new private user access key.
3102 * @param string $script unique target identifier
3103 * @param int $userid
3104 * @param int $instance optional instance id
3105 * @param string $iprestriction optional ip restricted access
3106 * @param int $validuntil key valid only until given data
3107 * @return string access key value
3109 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3110 global $DB;
3112 $key = new stdClass();
3113 $key->script = $script;
3114 $key->userid = $userid;
3115 $key->instance = $instance;
3116 $key->iprestriction = $iprestriction;
3117 $key->validuntil = $validuntil;
3118 $key->timecreated = time();
3120 // Something long and unique.
3121 $key->value = md5($userid.'_'.time().random_string(40));
3122 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3123 // Must be unique.
3124 $key->value = md5($userid.'_'.time().random_string(40));
3126 $DB->insert_record('user_private_key', $key);
3127 return $key->value;
3131 * Delete the user's new private user access keys for a particular script.
3133 * @param string $script unique target identifier
3134 * @param int $userid
3135 * @return void
3137 function delete_user_key($script, $userid) {
3138 global $DB;
3139 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3143 * Gets a private user access key (and creates one if one doesn't exist).
3145 * @param string $script unique target identifier
3146 * @param int $userid
3147 * @param int $instance optional instance id
3148 * @param string $iprestriction optional ip restricted access
3149 * @param int $validuntil key valid only until given date
3150 * @return string access key value
3152 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3153 global $DB;
3155 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3156 'instance' => $instance, 'iprestriction' => $iprestriction,
3157 'validuntil' => $validuntil))) {
3158 return $key->value;
3159 } else {
3160 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3166 * Modify the user table by setting the currently logged in user's last login to now.
3168 * @return bool Always returns true
3170 function update_user_login_times() {
3171 global $USER, $DB;
3173 if (isguestuser()) {
3174 // Do not update guest access times/ips for performance.
3175 return true;
3178 $now = time();
3180 $user = new stdClass();
3181 $user->id = $USER->id;
3183 // Make sure all users that logged in have some firstaccess.
3184 if ($USER->firstaccess == 0) {
3185 $USER->firstaccess = $user->firstaccess = $now;
3188 // Store the previous current as lastlogin.
3189 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3191 $USER->currentlogin = $user->currentlogin = $now;
3193 // Function user_accesstime_log() may not update immediately, better do it here.
3194 $USER->lastaccess = $user->lastaccess = $now;
3195 $USER->lastip = $user->lastip = getremoteaddr();
3197 // Note: do not call user_update_user() here because this is part of the login process,
3198 // the login event means that these fields were updated.
3199 $DB->update_record('user', $user);
3200 return true;
3204 * Determines if a user has completed setting up their account.
3206 * The lax mode (with $strict = false) has been introduced for special cases
3207 * only where we want to skip certain checks intentionally. This is valid in
3208 * certain mnet or ajax scenarios when the user cannot / should not be
3209 * redirected to edit their profile. In most cases, you should perform the
3210 * strict check.
3212 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3213 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3214 * @return bool
3216 function user_not_fully_set_up($user, $strict = true) {
3217 global $CFG;
3218 require_once($CFG->dirroot.'/user/profile/lib.php');
3220 if (isguestuser($user)) {
3221 return false;
3224 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3225 return true;
3228 if ($strict) {
3229 if (empty($user->id)) {
3230 // Strict mode can be used with existing accounts only.
3231 return true;
3233 if (!profile_has_required_custom_fields_set($user->id)) {
3234 return true;
3238 return false;
3242 * Check whether the user has exceeded the bounce threshold
3244 * @param stdClass $user A {@link $USER} object
3245 * @return bool true => User has exceeded bounce threshold
3247 function over_bounce_threshold($user) {
3248 global $CFG, $DB;
3250 if (empty($CFG->handlebounces)) {
3251 return false;
3254 if (empty($user->id)) {
3255 // No real (DB) user, nothing to do here.
3256 return false;
3259 // Set sensible defaults.
3260 if (empty($CFG->minbounces)) {
3261 $CFG->minbounces = 10;
3263 if (empty($CFG->bounceratio)) {
3264 $CFG->bounceratio = .20;
3266 $bouncecount = 0;
3267 $sendcount = 0;
3268 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3269 $bouncecount = $bounce->value;
3271 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3272 $sendcount = $send->value;
3274 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3278 * Used to increment or reset email sent count
3280 * @param stdClass $user object containing an id
3281 * @param bool $reset will reset the count to 0
3282 * @return void
3284 function set_send_count($user, $reset=false) {
3285 global $DB;
3287 if (empty($user->id)) {
3288 // No real (DB) user, nothing to do here.
3289 return;
3292 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3293 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3294 $DB->update_record('user_preferences', $pref);
3295 } else if (!empty($reset)) {
3296 // If it's not there and we're resetting, don't bother. Make a new one.
3297 $pref = new stdClass();
3298 $pref->name = 'email_send_count';
3299 $pref->value = 1;
3300 $pref->userid = $user->id;
3301 $DB->insert_record('user_preferences', $pref, false);
3306 * Increment or reset user's email bounce count
3308 * @param stdClass $user object containing an id
3309 * @param bool $reset will reset the count to 0
3311 function set_bounce_count($user, $reset=false) {
3312 global $DB;
3314 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3315 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3316 $DB->update_record('user_preferences', $pref);
3317 } else if (!empty($reset)) {
3318 // If it's not there and we're resetting, don't bother. Make a new one.
3319 $pref = new stdClass();
3320 $pref->name = 'email_bounce_count';
3321 $pref->value = 1;
3322 $pref->userid = $user->id;
3323 $DB->insert_record('user_preferences', $pref, false);
3328 * Determines if the logged in user is currently moving an activity
3330 * @param int $courseid The id of the course being tested
3331 * @return bool
3333 function ismoving($courseid) {
3334 global $USER;
3336 if (!empty($USER->activitycopy)) {
3337 return ($USER->activitycopycourse == $courseid);
3339 return false;
3343 * Returns a persons full name
3345 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3346 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3347 * specify one.
3349 * @param stdClass $user A {@link $USER} object to get full name of.
3350 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3351 * @return string
3353 function fullname($user, $override=false) {
3354 global $CFG, $SESSION;
3356 if (!isset($user->firstname) and !isset($user->lastname)) {
3357 return '';
3360 // Get all of the name fields.
3361 $allnames = get_all_user_name_fields();
3362 if ($CFG->debugdeveloper) {
3363 foreach ($allnames as $allname) {
3364 if (!property_exists($user, $allname)) {
3365 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3366 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3367 // Message has been sent, no point in sending the message multiple times.
3368 break;
3373 if (!$override) {
3374 if (!empty($CFG->forcefirstname)) {
3375 $user->firstname = $CFG->forcefirstname;
3377 if (!empty($CFG->forcelastname)) {
3378 $user->lastname = $CFG->forcelastname;
3382 if (!empty($SESSION->fullnamedisplay)) {
3383 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3386 $template = null;
3387 // If the fullnamedisplay setting is available, set the template to that.
3388 if (isset($CFG->fullnamedisplay)) {
3389 $template = $CFG->fullnamedisplay;
3391 // If the template is empty, or set to language, return the language string.
3392 if ((empty($template) || $template == 'language') && !$override) {
3393 return get_string('fullnamedisplay', null, $user);
3396 // Check to see if we are displaying according to the alternative full name format.
3397 if ($override) {
3398 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3399 // Default to show just the user names according to the fullnamedisplay string.
3400 return get_string('fullnamedisplay', null, $user);
3401 } else {
3402 // If the override is true, then change the template to use the complete name.
3403 $template = $CFG->alternativefullnameformat;
3407 $requirednames = array();
3408 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3409 foreach ($allnames as $allname) {
3410 if (strpos($template, $allname) !== false) {
3411 $requirednames[] = $allname;
3415 $displayname = $template;
3416 // Switch in the actual data into the template.
3417 foreach ($requirednames as $altname) {
3418 if (isset($user->$altname)) {
3419 // Using empty() on the below if statement causes breakages.
3420 if ((string)$user->$altname == '') {
3421 $displayname = str_replace($altname, 'EMPTY', $displayname);
3422 } else {
3423 $displayname = str_replace($altname, $user->$altname, $displayname);
3425 } else {
3426 $displayname = str_replace($altname, 'EMPTY', $displayname);
3429 // Tidy up any misc. characters (Not perfect, but gets most characters).
3430 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3431 // katakana and parenthesis.
3432 $patterns = array();
3433 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3434 // filled in by a user.
3435 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3436 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3437 // This regular expression is to remove any double spaces in the display name.
3438 $patterns[] = '/\s{2,}/u';
3439 foreach ($patterns as $pattern) {
3440 $displayname = preg_replace($pattern, ' ', $displayname);
3443 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3444 $displayname = trim($displayname);
3445 if (empty($displayname)) {
3446 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3447 // people in general feel is a good setting to fall back on.
3448 $displayname = $user->firstname;
3450 return $displayname;
3454 * A centralised location for the all name fields. Returns an array / sql string snippet.
3456 * @param bool $returnsql True for an sql select field snippet.
3457 * @param string $tableprefix table query prefix to use in front of each field.
3458 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3459 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3460 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3461 * @return array|string All name fields.
3463 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3464 // This array is provided in this order because when called by fullname() (above) if firstname is before
3465 // firstnamephonetic str_replace() will change the wrong placeholder.
3466 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3467 'lastnamephonetic' => 'lastnamephonetic',
3468 'middlename' => 'middlename',
3469 'alternatename' => 'alternatename',
3470 'firstname' => 'firstname',
3471 'lastname' => 'lastname');
3473 // Let's add a prefix to the array of user name fields if provided.
3474 if ($prefix) {
3475 foreach ($alternatenames as $key => $altname) {
3476 $alternatenames[$key] = $prefix . $altname;
3480 // If we want the end result to have firstname and lastname at the front / top of the result.
3481 if ($order) {
3482 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3483 for ($i = 0; $i < 2; $i++) {
3484 // Get the last element.
3485 $lastelement = end($alternatenames);
3486 // Remove it from the array.
3487 unset($alternatenames[$lastelement]);
3488 // Put the element back on the top of the array.
3489 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3493 // Create an sql field snippet if requested.
3494 if ($returnsql) {
3495 if ($tableprefix) {
3496 if ($fieldprefix) {
3497 foreach ($alternatenames as $key => $altname) {
3498 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3500 } else {
3501 foreach ($alternatenames as $key => $altname) {
3502 $alternatenames[$key] = $tableprefix . '.' . $altname;
3506 $alternatenames = implode(',', $alternatenames);
3508 return $alternatenames;
3512 * Reduces lines of duplicated code for getting user name fields.
3514 * See also {@link user_picture::unalias()}
3516 * @param object $addtoobject Object to add user name fields to.
3517 * @param object $secondobject Object that contains user name field information.
3518 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3519 * @param array $additionalfields Additional fields to be matched with data in the second object.
3520 * The key can be set to the user table field name.
3521 * @return object User name fields.
3523 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3524 $fields = get_all_user_name_fields(false, null, $prefix);
3525 if ($additionalfields) {
3526 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3527 // the key is a number and then sets the key to the array value.
3528 foreach ($additionalfields as $key => $value) {
3529 if (is_numeric($key)) {
3530 $additionalfields[$value] = $prefix . $value;
3531 unset($additionalfields[$key]);
3532 } else {
3533 $additionalfields[$key] = $prefix . $value;
3536 $fields = array_merge($fields, $additionalfields);
3538 foreach ($fields as $key => $field) {
3539 // Important that we have all of the user name fields present in the object that we are sending back.
3540 $addtoobject->$key = '';
3541 if (isset($secondobject->$field)) {
3542 $addtoobject->$key = $secondobject->$field;
3545 return $addtoobject;
3549 * Returns an array of values in order of occurance in a provided string.
3550 * The key in the result is the character postion in the string.
3552 * @param array $values Values to be found in the string format
3553 * @param string $stringformat The string which may contain values being searched for.
3554 * @return array An array of values in order according to placement in the string format.
3556 function order_in_string($values, $stringformat) {
3557 $valuearray = array();
3558 foreach ($values as $value) {
3559 $pattern = "/$value\b/";
3560 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3561 if (preg_match($pattern, $stringformat)) {
3562 $replacement = "thing";
3563 // Replace the value with something more unique to ensure we get the right position when using strpos().
3564 $newformat = preg_replace($pattern, $replacement, $stringformat);
3565 $position = strpos($newformat, $replacement);
3566 $valuearray[$position] = $value;
3569 ksort($valuearray);
3570 return $valuearray;
3574 * Checks if current user is shown any extra fields when listing users.
3576 * @param object $context Context
3577 * @param array $already Array of fields that we're going to show anyway
3578 * so don't bother listing them
3579 * @return array Array of field names from user table, not including anything
3580 * listed in $already
3582 function get_extra_user_fields($context, $already = array()) {
3583 global $CFG;
3585 // Only users with permission get the extra fields.
3586 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3587 return array();
3590 // Split showuseridentity on comma.
3591 if (empty($CFG->showuseridentity)) {
3592 // Explode gives wrong result with empty string.
3593 $extra = array();
3594 } else {
3595 $extra = explode(',', $CFG->showuseridentity);
3597 $renumber = false;
3598 foreach ($extra as $key => $field) {
3599 if (in_array($field, $already)) {
3600 unset($extra[$key]);
3601 $renumber = true;
3604 if ($renumber) {
3605 // For consistency, if entries are removed from array, renumber it
3606 // so they are numbered as you would expect.
3607 $extra = array_merge($extra);
3609 return $extra;
3613 * If the current user is to be shown extra user fields when listing or
3614 * selecting users, returns a string suitable for including in an SQL select
3615 * clause to retrieve those fields.
3617 * @param context $context Context
3618 * @param string $alias Alias of user table, e.g. 'u' (default none)
3619 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3620 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3621 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3623 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3624 $fields = get_extra_user_fields($context, $already);
3625 $result = '';
3626 // Add punctuation for alias.
3627 if ($alias !== '') {
3628 $alias .= '.';
3630 foreach ($fields as $field) {
3631 $result .= ', ' . $alias . $field;
3632 if ($prefix) {
3633 $result .= ' AS ' . $prefix . $field;
3636 return $result;
3640 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3641 * @param string $field Field name, e.g. 'phone1'
3642 * @return string Text description taken from language file, e.g. 'Phone number'
3644 function get_user_field_name($field) {
3645 // Some fields have language strings which are not the same as field name.
3646 switch ($field) {
3647 case 'url' : {
3648 return get_string('webpage');
3650 case 'icq' : {
3651 return get_string('icqnumber');
3653 case 'skype' : {
3654 return get_string('skypeid');
3656 case 'aim' : {
3657 return get_string('aimid');
3659 case 'yahoo' : {
3660 return get_string('yahooid');
3662 case 'msn' : {
3663 return get_string('msnid');
3666 // Otherwise just use the same lang string.
3667 return get_string($field);
3671 * Returns whether a given authentication plugin exists.
3673 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3674 * @return boolean Whether the plugin is available.
3676 function exists_auth_plugin($auth) {
3677 global $CFG;
3679 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3680 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3682 return false;
3686 * Checks if a given plugin is in the list of enabled authentication plugins.
3688 * @param string $auth Authentication plugin.
3689 * @return boolean Whether the plugin is enabled.
3691 function is_enabled_auth($auth) {
3692 if (empty($auth)) {
3693 return false;
3696 $enabled = get_enabled_auth_plugins();
3698 return in_array($auth, $enabled);
3702 * Returns an authentication plugin instance.
3704 * @param string $auth name of authentication plugin
3705 * @return auth_plugin_base An instance of the required authentication plugin.
3707 function get_auth_plugin($auth) {
3708 global $CFG;
3710 // Check the plugin exists first.
3711 if (! exists_auth_plugin($auth)) {
3712 print_error('authpluginnotfound', 'debug', '', $auth);
3715 // Return auth plugin instance.
3716 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3717 $class = "auth_plugin_$auth";
3718 return new $class;
3722 * Returns array of active auth plugins.
3724 * @param bool $fix fix $CFG->auth if needed
3725 * @return array
3727 function get_enabled_auth_plugins($fix=false) {
3728 global $CFG;
3730 $default = array('manual', 'nologin');
3732 if (empty($CFG->auth)) {
3733 $auths = array();
3734 } else {
3735 $auths = explode(',', $CFG->auth);
3738 if ($fix) {
3739 $auths = array_unique($auths);
3740 foreach ($auths as $k => $authname) {
3741 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3742 unset($auths[$k]);
3745 $newconfig = implode(',', $auths);
3746 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3747 set_config('auth', $newconfig);
3751 return (array_merge($default, $auths));
3755 * Returns true if an internal authentication method is being used.
3756 * if method not specified then, global default is assumed
3758 * @param string $auth Form of authentication required
3759 * @return bool
3761 function is_internal_auth($auth) {
3762 // Throws error if bad $auth.
3763 $authplugin = get_auth_plugin($auth);
3764 return $authplugin->is_internal();
3768 * Returns true if the user is a 'restored' one.
3770 * Used in the login process to inform the user and allow him/her to reset the password
3772 * @param string $username username to be checked
3773 * @return bool
3775 function is_restored_user($username) {
3776 global $CFG, $DB;
3778 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3782 * Returns an array of user fields
3784 * @return array User field/column names
3786 function get_user_fieldnames() {
3787 global $DB;
3789 $fieldarray = $DB->get_columns('user');
3790 unset($fieldarray['id']);
3791 $fieldarray = array_keys($fieldarray);
3793 return $fieldarray;
3797 * Creates a bare-bones user record
3799 * @todo Outline auth types and provide code example
3801 * @param string $username New user's username to add to record
3802 * @param string $password New user's password to add to record
3803 * @param string $auth Form of authentication required
3804 * @return stdClass A complete user object
3806 function create_user_record($username, $password, $auth = 'manual') {
3807 global $CFG, $DB;
3808 require_once($CFG->dirroot.'/user/profile/lib.php');
3809 require_once($CFG->dirroot.'/user/lib.php');
3811 // Just in case check text case.
3812 $username = trim(core_text::strtolower($username));
3814 $authplugin = get_auth_plugin($auth);
3815 $customfields = $authplugin->get_custom_user_profile_fields();
3816 $newuser = new stdClass();
3817 if ($newinfo = $authplugin->get_userinfo($username)) {
3818 $newinfo = truncate_userinfo($newinfo);
3819 foreach ($newinfo as $key => $value) {
3820 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3821 $newuser->$key = $value;
3826 if (!empty($newuser->email)) {
3827 if (email_is_not_allowed($newuser->email)) {
3828 unset($newuser->email);
3832 if (!isset($newuser->city)) {
3833 $newuser->city = '';
3836 $newuser->auth = $auth;
3837 $newuser->username = $username;
3839 // Fix for MDL-8480
3840 // user CFG lang for user if $newuser->lang is empty
3841 // or $user->lang is not an installed language.
3842 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3843 $newuser->lang = $CFG->lang;
3845 $newuser->confirmed = 1;
3846 $newuser->lastip = getremoteaddr();
3847 $newuser->timecreated = time();
3848 $newuser->timemodified = $newuser->timecreated;
3849 $newuser->mnethostid = $CFG->mnet_localhost_id;
3851 $newuser->id = user_create_user($newuser, false, false);
3853 // Save user profile data.
3854 profile_save_data($newuser);
3856 $user = get_complete_user_data('id', $newuser->id);
3857 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3858 set_user_preference('auth_forcepasswordchange', 1, $user);
3860 // Set the password.
3861 update_internal_user_password($user, $password);
3863 // Trigger event.
3864 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3866 return $user;
3870 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3872 * @param string $username user's username to update the record
3873 * @return stdClass A complete user object
3875 function update_user_record($username) {
3876 global $DB, $CFG;
3877 // Just in case check text case.
3878 $username = trim(core_text::strtolower($username));
3880 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3881 return update_user_record_by_id($oldinfo->id);
3885 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3887 * @param int $id user id
3888 * @return stdClass A complete user object
3890 function update_user_record_by_id($id) {
3891 global $DB, $CFG;
3892 require_once($CFG->dirroot."/user/profile/lib.php");
3893 require_once($CFG->dirroot.'/user/lib.php');
3895 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3896 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3898 $newuser = array();
3899 $userauth = get_auth_plugin($oldinfo->auth);
3901 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3902 $newinfo = truncate_userinfo($newinfo);
3903 $customfields = $userauth->get_custom_user_profile_fields();
3905 foreach ($newinfo as $key => $value) {
3906 $iscustom = in_array($key, $customfields);
3907 if (!$iscustom) {
3908 $key = strtolower($key);
3910 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3911 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3912 // Unknown or must not be changed.
3913 continue;
3915 $confval = $userauth->config->{'field_updatelocal_' . $key};
3916 $lockval = $userauth->config->{'field_lock_' . $key};
3917 if (empty($confval) || empty($lockval)) {
3918 continue;
3920 if ($confval === 'onlogin') {
3921 // MDL-4207 Don't overwrite modified user profile values with
3922 // empty LDAP values when 'unlocked if empty' is set. The purpose
3923 // of the setting 'unlocked if empty' is to allow the user to fill
3924 // in a value for the selected field _if LDAP is giving
3925 // nothing_ for this field. Thus it makes sense to let this value
3926 // stand in until LDAP is giving a value for this field.
3927 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3928 if ($iscustom || (in_array($key, $userauth->userfields) &&
3929 ((string)$oldinfo->$key !== (string)$value))) {
3930 $newuser[$key] = (string)$value;
3935 if ($newuser) {
3936 $newuser['id'] = $oldinfo->id;
3937 $newuser['timemodified'] = time();
3938 user_update_user((object) $newuser, false, false);
3940 // Save user profile data.
3941 profile_save_data((object) $newuser);
3943 // Trigger event.
3944 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
3948 return get_complete_user_data('id', $oldinfo->id);
3952 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
3954 * @param array $info Array of user properties to truncate if needed
3955 * @return array The now truncated information that was passed in
3957 function truncate_userinfo(array $info) {
3958 // Define the limits.
3959 $limit = array(
3960 'username' => 100,
3961 'idnumber' => 255,
3962 'firstname' => 100,
3963 'lastname' => 100,
3964 'email' => 100,
3965 'icq' => 15,
3966 'phone1' => 20,
3967 'phone2' => 20,
3968 'institution' => 255,
3969 'department' => 255,
3970 'address' => 255,
3971 'city' => 120,
3972 'country' => 2,
3973 'url' => 255,
3976 // Apply where needed.
3977 foreach (array_keys($info) as $key) {
3978 if (!empty($limit[$key])) {
3979 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
3983 return $info;
3987 * Marks user deleted in internal user database and notifies the auth plugin.
3988 * Also unenrols user from all roles and does other cleanup.
3990 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3992 * @param stdClass $user full user object before delete
3993 * @return boolean success
3994 * @throws coding_exception if invalid $user parameter detected
3996 function delete_user(stdClass $user) {
3997 global $CFG, $DB;
3998 require_once($CFG->libdir.'/grouplib.php');
3999 require_once($CFG->libdir.'/gradelib.php');
4000 require_once($CFG->dirroot.'/message/lib.php');
4001 require_once($CFG->dirroot.'/user/lib.php');
4003 // Make sure nobody sends bogus record type as parameter.
4004 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4005 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4008 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4009 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4010 debugging('Attempt to delete unknown user account.');
4011 return false;
4014 // There must be always exactly one guest record, originally the guest account was identified by username only,
4015 // now we use $CFG->siteguest for performance reasons.
4016 if ($user->username === 'guest' or isguestuser($user)) {
4017 debugging('Guest user account can not be deleted.');
4018 return false;
4021 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4022 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4023 if ($user->auth === 'manual' and is_siteadmin($user)) {
4024 debugging('Local administrator accounts can not be deleted.');
4025 return false;
4028 // Allow plugins to use this user object before we completely delete it.
4029 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4030 foreach ($pluginsfunction as $plugintype => $plugins) {
4031 foreach ($plugins as $pluginfunction) {
4032 $pluginfunction($user);
4037 // Keep user record before updating it, as we have to pass this to user_deleted event.
4038 $olduser = clone $user;
4040 // Keep a copy of user context, we need it for event.
4041 $usercontext = context_user::instance($user->id);
4043 // Delete all grades - backup is kept in grade_grades_history table.
4044 grade_user_delete($user->id);
4046 // Move unread messages from this user to read.
4047 message_move_userfrom_unread2read($user->id);
4049 // TODO: remove from cohorts using standard API here.
4051 // Remove user tags.
4052 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4054 // Unconditionally unenrol from all courses.
4055 enrol_user_delete($user);
4057 // Unenrol from all roles in all contexts.
4058 // This might be slow but it is really needed - modules might do some extra cleanup!
4059 role_unassign_all(array('userid' => $user->id));
4061 // Now do a brute force cleanup.
4063 // Remove from all cohorts.
4064 $DB->delete_records('cohort_members', array('userid' => $user->id));
4066 // Remove from all groups.
4067 $DB->delete_records('groups_members', array('userid' => $user->id));
4069 // Brute force unenrol from all courses.
4070 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4072 // Purge user preferences.
4073 $DB->delete_records('user_preferences', array('userid' => $user->id));
4075 // Purge user extra profile info.
4076 $DB->delete_records('user_info_data', array('userid' => $user->id));
4078 // Purge log of previous password hashes.
4079 $DB->delete_records('user_password_history', array('userid' => $user->id));
4081 // Last course access not necessary either.
4082 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4083 // Remove all user tokens.
4084 $DB->delete_records('external_tokens', array('userid' => $user->id));
4086 // Unauthorise the user for all services.
4087 $DB->delete_records('external_services_users', array('userid' => $user->id));
4089 // Remove users private keys.
4090 $DB->delete_records('user_private_key', array('userid' => $user->id));
4092 // Remove users customised pages.
4093 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4095 // Force logout - may fail if file based sessions used, sorry.
4096 \core\session\manager::kill_user_sessions($user->id);
4098 // Generate username from email address, or a fake email.
4099 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4100 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
4102 // Workaround for bulk deletes of users with the same email address.
4103 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4104 $delname++;
4107 // Mark internal user record as "deleted".
4108 $updateuser = new stdClass();
4109 $updateuser->id = $user->id;
4110 $updateuser->deleted = 1;
4111 $updateuser->username = $delname; // Remember it just in case.
4112 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4113 $updateuser->idnumber = ''; // Clear this field to free it up.
4114 $updateuser->picture = 0;
4115 $updateuser->timemodified = time();
4117 // Don't trigger update event, as user is being deleted.
4118 user_update_user($updateuser, false, false);
4120 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4121 context_helper::delete_instance(CONTEXT_USER, $user->id);
4123 // Any plugin that needs to cleanup should register this event.
4124 // Trigger event.
4125 $event = \core\event\user_deleted::create(
4126 array(
4127 'objectid' => $user->id,
4128 'relateduserid' => $user->id,
4129 'context' => $usercontext,
4130 'other' => array(
4131 'username' => $user->username,
4132 'email' => $user->email,
4133 'idnumber' => $user->idnumber,
4134 'picture' => $user->picture,
4135 'mnethostid' => $user->mnethostid
4139 $event->add_record_snapshot('user', $olduser);
4140 $event->trigger();
4142 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4143 // should know about this updated property persisted to the user's table.
4144 $user->timemodified = $updateuser->timemodified;
4146 // Notify auth plugin - do not block the delete even when plugin fails.
4147 $authplugin = get_auth_plugin($user->auth);
4148 $authplugin->user_delete($user);
4150 return true;
4154 * Retrieve the guest user object.
4156 * @return stdClass A {@link $USER} object
4158 function guest_user() {
4159 global $CFG, $DB;
4161 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4162 $newuser->confirmed = 1;
4163 $newuser->lang = $CFG->lang;
4164 $newuser->lastip = getremoteaddr();
4167 return $newuser;
4171 * Authenticates a user against the chosen authentication mechanism
4173 * Given a username and password, this function looks them
4174 * up using the currently selected authentication mechanism,
4175 * and if the authentication is successful, it returns a
4176 * valid $user object from the 'user' table.
4178 * Uses auth_ functions from the currently active auth module
4180 * After authenticate_user_login() returns success, you will need to
4181 * log that the user has logged in, and call complete_user_login() to set
4182 * the session up.
4184 * Note: this function works only with non-mnet accounts!
4186 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4187 * @param string $password User's password
4188 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4189 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4190 * @return stdClass|false A {@link $USER} object or false if error
4192 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4193 global $CFG, $DB;
4194 require_once("$CFG->libdir/authlib.php");
4196 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4197 // we have found the user
4199 } else if (!empty($CFG->authloginviaemail)) {
4200 if ($email = clean_param($username, PARAM_EMAIL)) {
4201 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4202 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4203 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4204 if (count($users) === 1) {
4205 // Use email for login only if unique.
4206 $user = reset($users);
4207 $user = get_complete_user_data('id', $user->id);
4208 $username = $user->username;
4210 unset($users);
4214 $authsenabled = get_enabled_auth_plugins();
4216 if ($user) {
4217 // Use manual if auth not set.
4218 $auth = empty($user->auth) ? 'manual' : $user->auth;
4220 if (in_array($user->auth, $authsenabled)) {
4221 $authplugin = get_auth_plugin($user->auth);
4222 $authplugin->pre_user_login_hook($user);
4225 if (!empty($user->suspended)) {
4226 $failurereason = AUTH_LOGIN_SUSPENDED;
4228 // Trigger login failed event.
4229 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4230 'other' => array('username' => $username, 'reason' => $failurereason)));
4231 $event->trigger();
4232 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4233 return false;
4235 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4236 // Legacy way to suspend user.
4237 $failurereason = AUTH_LOGIN_SUSPENDED;
4239 // Trigger login failed event.
4240 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4241 'other' => array('username' => $username, 'reason' => $failurereason)));
4242 $event->trigger();
4243 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4244 return false;
4246 $auths = array($auth);
4248 } else {
4249 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4250 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4251 $failurereason = AUTH_LOGIN_NOUSER;
4253 // Trigger login failed event.
4254 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4255 'reason' => $failurereason)));
4256 $event->trigger();
4257 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4258 return false;
4261 // User does not exist.
4262 $auths = $authsenabled;
4263 $user = new stdClass();
4264 $user->id = 0;
4267 if ($ignorelockout) {
4268 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4269 // or this function is called from a SSO script.
4270 } else if ($user->id) {
4271 // Verify login lockout after other ways that may prevent user login.
4272 if (login_is_lockedout($user)) {
4273 $failurereason = AUTH_LOGIN_LOCKOUT;
4275 // Trigger login failed event.
4276 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4277 'other' => array('username' => $username, 'reason' => $failurereason)));
4278 $event->trigger();
4280 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4281 return false;
4283 } else {
4284 // We can not lockout non-existing accounts.
4287 foreach ($auths as $auth) {
4288 $authplugin = get_auth_plugin($auth);
4290 // On auth fail fall through to the next plugin.
4291 if (!$authplugin->user_login($username, $password)) {
4292 continue;
4295 // Successful authentication.
4296 if ($user->id) {
4297 // User already exists in database.
4298 if (empty($user->auth)) {
4299 // For some reason auth isn't set yet.
4300 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4301 $user->auth = $auth;
4304 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4305 // the current hash algorithm while we have access to the user's password.
4306 update_internal_user_password($user, $password);
4308 if ($authplugin->is_synchronised_with_external()) {
4309 // Update user record from external DB.
4310 $user = update_user_record_by_id($user->id);
4312 } else {
4313 // The user is authenticated but user creation may be disabled.
4314 if (!empty($CFG->authpreventaccountcreation)) {
4315 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4317 // Trigger login failed event.
4318 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4319 'reason' => $failurereason)));
4320 $event->trigger();
4322 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4323 $_SERVER['HTTP_USER_AGENT']);
4324 return false;
4325 } else {
4326 $user = create_user_record($username, $password, $auth);
4330 $authplugin->sync_roles($user);
4332 foreach ($authsenabled as $hau) {
4333 $hauth = get_auth_plugin($hau);
4334 $hauth->user_authenticated_hook($user, $username, $password);
4337 if (empty($user->id)) {
4338 $failurereason = AUTH_LOGIN_NOUSER;
4339 // Trigger login failed event.
4340 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4341 'reason' => $failurereason)));
4342 $event->trigger();
4343 return false;
4346 if (!empty($user->suspended)) {
4347 // Just in case some auth plugin suspended account.
4348 $failurereason = AUTH_LOGIN_SUSPENDED;
4349 // Trigger login failed event.
4350 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4351 'other' => array('username' => $username, 'reason' => $failurereason)));
4352 $event->trigger();
4353 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4354 return false;
4357 login_attempt_valid($user);
4358 $failurereason = AUTH_LOGIN_OK;
4359 return $user;
4362 // Failed if all the plugins have failed.
4363 if (debugging('', DEBUG_ALL)) {
4364 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4367 if ($user->id) {
4368 login_attempt_failed($user);
4369 $failurereason = AUTH_LOGIN_FAILED;
4370 // Trigger login failed event.
4371 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4372 'other' => array('username' => $username, 'reason' => $failurereason)));
4373 $event->trigger();
4374 } else {
4375 $failurereason = AUTH_LOGIN_NOUSER;
4376 // Trigger login failed event.
4377 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4378 'reason' => $failurereason)));
4379 $event->trigger();
4382 return false;
4386 * Call to complete the user login process after authenticate_user_login()
4387 * has succeeded. It will setup the $USER variable and other required bits
4388 * and pieces.
4390 * NOTE:
4391 * - It will NOT log anything -- up to the caller to decide what to log.
4392 * - this function does not set any cookies any more!
4394 * @param stdClass $user
4395 * @return stdClass A {@link $USER} object - BC only, do not use
4397 function complete_user_login($user) {
4398 global $CFG, $USER, $SESSION;
4400 \core\session\manager::login_user($user);
4402 // Reload preferences from DB.
4403 unset($USER->preference);
4404 check_user_preferences_loaded($USER);
4406 // Update login times.
4407 update_user_login_times();
4409 // Extra session prefs init.
4410 set_login_session_preferences();
4412 // Trigger login event.
4413 $event = \core\event\user_loggedin::create(
4414 array(
4415 'userid' => $USER->id,
4416 'objectid' => $USER->id,
4417 'other' => array('username' => $USER->username),
4420 $event->trigger();
4422 if (isguestuser()) {
4423 // No need to continue when user is THE guest.
4424 return $USER;
4427 if (CLI_SCRIPT) {
4428 // We can redirect to password change URL only in browser.
4429 return $USER;
4432 // Select password change url.
4433 $userauth = get_auth_plugin($USER->auth);
4435 // Check whether the user should be changing password.
4436 if (get_user_preferences('auth_forcepasswordchange', false)) {
4437 if ($userauth->can_change_password()) {
4438 if ($changeurl = $userauth->change_password_url()) {
4439 redirect($changeurl);
4440 } else {
4441 $SESSION->wantsurl = core_login_get_return_url();
4442 redirect($CFG->httpswwwroot.'/login/change_password.php');
4444 } else {
4445 print_error('nopasswordchangeforced', 'auth');
4448 return $USER;
4452 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4454 * @param string $password String to check.
4455 * @return boolean True if the $password matches the format of an md5 sum.
4457 function password_is_legacy_hash($password) {
4458 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4462 * Compare password against hash stored in user object to determine if it is valid.
4464 * If necessary it also updates the stored hash to the current format.
4466 * @param stdClass $user (Password property may be updated).
4467 * @param string $password Plain text password.
4468 * @return bool True if password is valid.
4470 function validate_internal_user_password($user, $password) {
4471 global $CFG;
4473 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4474 // Internal password is not used at all, it can not validate.
4475 return false;
4478 // If hash isn't a legacy (md5) hash, validate using the library function.
4479 if (!password_is_legacy_hash($user->password)) {
4480 return password_verify($password, $user->password);
4483 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4484 // is valid we can then update it to the new algorithm.
4486 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4487 $validated = false;
4489 if ($user->password === md5($password.$sitesalt)
4490 or $user->password === md5($password)
4491 or $user->password === md5(addslashes($password).$sitesalt)
4492 or $user->password === md5(addslashes($password))) {
4493 // Note: we are intentionally using the addslashes() here because we
4494 // need to accept old password hashes of passwords with magic quotes.
4495 $validated = true;
4497 } else {
4498 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4499 $alt = 'passwordsaltalt'.$i;
4500 if (!empty($CFG->$alt)) {
4501 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4502 $validated = true;
4503 break;
4509 if ($validated) {
4510 // If the password matches the existing md5 hash, update to the
4511 // current hash algorithm while we have access to the user's password.
4512 update_internal_user_password($user, $password);
4515 return $validated;
4519 * Calculate hash for a plain text password.
4521 * @param string $password Plain text password to be hashed.
4522 * @param bool $fasthash If true, use a low cost factor when generating the hash
4523 * This is much faster to generate but makes the hash
4524 * less secure. It is used when lots of hashes need to
4525 * be generated quickly.
4526 * @return string The hashed password.
4528 * @throws moodle_exception If a problem occurs while generating the hash.
4530 function hash_internal_user_password($password, $fasthash = false) {
4531 global $CFG;
4533 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4534 $options = ($fasthash) ? array('cost' => 4) : array();
4536 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4538 if ($generatedhash === false || $generatedhash === null) {
4539 throw new moodle_exception('Failed to generate password hash.');
4542 return $generatedhash;
4546 * Update password hash in user object (if necessary).
4548 * The password is updated if:
4549 * 1. The password has changed (the hash of $user->password is different
4550 * to the hash of $password).
4551 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4552 * md5 algorithm).
4554 * Updating the password will modify the $user object and the database
4555 * record to use the current hashing algorithm.
4556 * It will remove Web Services user tokens too.
4558 * @param stdClass $user User object (password property may be updated).
4559 * @param string $password Plain text password.
4560 * @param bool $fasthash If true, use a low cost factor when generating the hash
4561 * This is much faster to generate but makes the hash
4562 * less secure. It is used when lots of hashes need to
4563 * be generated quickly.
4564 * @return bool Always returns true.
4566 function update_internal_user_password($user, $password, $fasthash = false) {
4567 global $CFG, $DB;
4569 // Figure out what the hashed password should be.
4570 if (!isset($user->auth)) {
4571 debugging('User record in update_internal_user_password() must include field auth',
4572 DEBUG_DEVELOPER);
4573 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4575 $authplugin = get_auth_plugin($user->auth);
4576 if ($authplugin->prevent_local_passwords()) {
4577 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4578 } else {
4579 $hashedpassword = hash_internal_user_password($password, $fasthash);
4582 $algorithmchanged = false;
4584 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4585 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4586 $passwordchanged = ($user->password !== $hashedpassword);
4588 } else if (isset($user->password)) {
4589 // If verification fails then it means the password has changed.
4590 $passwordchanged = !password_verify($password, $user->password);
4591 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4592 } else {
4593 // While creating new user, password in unset in $user object, to avoid
4594 // saving it with user_create()
4595 $passwordchanged = true;
4598 if ($passwordchanged || $algorithmchanged) {
4599 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4600 $user->password = $hashedpassword;
4602 // Trigger event.
4603 $user = $DB->get_record('user', array('id' => $user->id));
4604 \core\event\user_password_updated::create_from_user($user)->trigger();
4606 // Remove WS user tokens.
4607 if (!empty($CFG->passwordchangetokendeletion)) {
4608 require_once($CFG->dirroot.'/webservice/lib.php');
4609 webservice::delete_user_ws_tokens($user->id);
4613 return true;
4617 * Get a complete user record, which includes all the info in the user record.
4619 * Intended for setting as $USER session variable
4621 * @param string $field The user field to be checked for a given value.
4622 * @param string $value The value to match for $field.
4623 * @param int $mnethostid
4624 * @return mixed False, or A {@link $USER} object.
4626 function get_complete_user_data($field, $value, $mnethostid = null) {
4627 global $CFG, $DB;
4629 if (!$field || !$value) {
4630 return false;
4633 // Build the WHERE clause for an SQL query.
4634 $params = array('fieldval' => $value);
4635 $constraints = "$field = :fieldval AND deleted <> 1";
4637 // If we are loading user data based on anything other than id,
4638 // we must also restrict our search based on mnet host.
4639 if ($field != 'id') {
4640 if (empty($mnethostid)) {
4641 // If empty, we restrict to local users.
4642 $mnethostid = $CFG->mnet_localhost_id;
4645 if (!empty($mnethostid)) {
4646 $params['mnethostid'] = $mnethostid;
4647 $constraints .= " AND mnethostid = :mnethostid";
4650 // Get all the basic user data.
4651 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4652 return false;
4655 // Get various settings and preferences.
4657 // Preload preference cache.
4658 check_user_preferences_loaded($user);
4660 // Load course enrolment related stuff.
4661 $user->lastcourseaccess = array(); // During last session.
4662 $user->currentcourseaccess = array(); // During current session.
4663 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4664 foreach ($lastaccesses as $lastaccess) {
4665 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4669 $sql = "SELECT g.id, g.courseid
4670 FROM {groups} g, {groups_members} gm
4671 WHERE gm.groupid=g.id AND gm.userid=?";
4673 // This is a special hack to speedup calendar display.
4674 $user->groupmember = array();
4675 if (!isguestuser($user)) {
4676 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4677 foreach ($groups as $group) {
4678 if (!array_key_exists($group->courseid, $user->groupmember)) {
4679 $user->groupmember[$group->courseid] = array();
4681 $user->groupmember[$group->courseid][$group->id] = $group->id;
4686 // Add the custom profile fields to the user record.
4687 $user->profile = array();
4688 if (!isguestuser($user)) {
4689 require_once($CFG->dirroot.'/user/profile/lib.php');
4690 profile_load_custom_fields($user);
4693 // Rewrite some variables if necessary.
4694 if (!empty($user->description)) {
4695 // No need to cart all of it around.
4696 $user->description = true;
4698 if (isguestuser($user)) {
4699 // Guest language always same as site.
4700 $user->lang = $CFG->lang;
4701 // Name always in current language.
4702 $user->firstname = get_string('guestuser');
4703 $user->lastname = ' ';
4706 return $user;
4710 * Validate a password against the configured password policy
4712 * @param string $password the password to be checked against the password policy
4713 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4714 * @return bool true if the password is valid according to the policy. false otherwise.
4716 function check_password_policy($password, &$errmsg) {
4717 global $CFG;
4719 if (empty($CFG->passwordpolicy)) {
4720 return true;
4723 $errmsg = '';
4724 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4725 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4728 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4729 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4732 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4733 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4736 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4737 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4740 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4741 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4743 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4744 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4747 if ($errmsg == '') {
4748 return true;
4749 } else {
4750 return false;
4756 * When logging in, this function is run to set certain preferences for the current SESSION.
4758 function set_login_session_preferences() {
4759 global $SESSION;
4761 $SESSION->justloggedin = true;
4763 unset($SESSION->lang);
4764 unset($SESSION->forcelang);
4765 unset($SESSION->load_navigation_admin);
4770 * Delete a course, including all related data from the database, and any associated files.
4772 * @param mixed $courseorid The id of the course or course object to delete.
4773 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4774 * @return bool true if all the removals succeeded. false if there were any failures. If this
4775 * method returns false, some of the removals will probably have succeeded, and others
4776 * failed, but you have no way of knowing which.
4778 function delete_course($courseorid, $showfeedback = true) {
4779 global $DB;
4781 if (is_object($courseorid)) {
4782 $courseid = $courseorid->id;
4783 $course = $courseorid;
4784 } else {
4785 $courseid = $courseorid;
4786 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4787 return false;
4790 $context = context_course::instance($courseid);
4792 // Frontpage course can not be deleted!!
4793 if ($courseid == SITEID) {
4794 return false;
4797 // Allow plugins to use this course before we completely delete it.
4798 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
4799 foreach ($pluginsfunction as $plugintype => $plugins) {
4800 foreach ($plugins as $pluginfunction) {
4801 $pluginfunction($course);
4806 // Make the course completely empty.
4807 remove_course_contents($courseid, $showfeedback);
4809 // Delete the course and related context instance.
4810 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4812 $DB->delete_records("course", array("id" => $courseid));
4813 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4815 // Reset all course related caches here.
4816 if (class_exists('format_base', false)) {
4817 format_base::reset_course_cache($courseid);
4820 // Trigger a course deleted event.
4821 $event = \core\event\course_deleted::create(array(
4822 'objectid' => $course->id,
4823 'context' => $context,
4824 'other' => array(
4825 'shortname' => $course->shortname,
4826 'fullname' => $course->fullname,
4827 'idnumber' => $course->idnumber
4830 $event->add_record_snapshot('course', $course);
4831 $event->trigger();
4833 return true;
4837 * Clear a course out completely, deleting all content but don't delete the course itself.
4839 * This function does not verify any permissions.
4841 * Please note this function also deletes all user enrolments,
4842 * enrolment instances and role assignments by default.
4844 * $options:
4845 * - 'keep_roles_and_enrolments' - false by default
4846 * - 'keep_groups_and_groupings' - false by default
4848 * @param int $courseid The id of the course that is being deleted
4849 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4850 * @param array $options extra options
4851 * @return bool true if all the removals succeeded. false if there were any failures. If this
4852 * method returns false, some of the removals will probably have succeeded, and others
4853 * failed, but you have no way of knowing which.
4855 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4856 global $CFG, $DB, $OUTPUT;
4858 require_once($CFG->libdir.'/badgeslib.php');
4859 require_once($CFG->libdir.'/completionlib.php');
4860 require_once($CFG->libdir.'/questionlib.php');
4861 require_once($CFG->libdir.'/gradelib.php');
4862 require_once($CFG->dirroot.'/group/lib.php');
4863 require_once($CFG->dirroot.'/comment/lib.php');
4864 require_once($CFG->dirroot.'/rating/lib.php');
4865 require_once($CFG->dirroot.'/notes/lib.php');
4867 // Handle course badges.
4868 badges_handle_course_deletion($courseid);
4870 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4871 $strdeleted = get_string('deleted').' - ';
4873 // Some crazy wishlist of stuff we should skip during purging of course content.
4874 $options = (array)$options;
4876 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
4877 $coursecontext = context_course::instance($courseid);
4878 $fs = get_file_storage();
4880 // Delete course completion information, this has to be done before grades and enrols.
4881 $cc = new completion_info($course);
4882 $cc->clear_criteria();
4883 if ($showfeedback) {
4884 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4887 // Remove all data from gradebook - this needs to be done before course modules
4888 // because while deleting this information, the system may need to reference
4889 // the course modules that own the grades.
4890 remove_course_grades($courseid, $showfeedback);
4891 remove_grade_letters($coursecontext, $showfeedback);
4893 // Delete course blocks in any all child contexts,
4894 // they may depend on modules so delete them first.
4895 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4896 foreach ($childcontexts as $childcontext) {
4897 blocks_delete_all_for_context($childcontext->id);
4899 unset($childcontexts);
4900 blocks_delete_all_for_context($coursecontext->id);
4901 if ($showfeedback) {
4902 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4905 // Get the list of all modules that are properly installed.
4906 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
4908 // Delete every instance of every module,
4909 // this has to be done before deleting of course level stuff.
4910 $locations = core_component::get_plugin_list('mod');
4911 foreach ($locations as $modname => $moddir) {
4912 if ($modname === 'NEWMODULE') {
4913 continue;
4915 if (array_key_exists($modname, $allmodules)) {
4916 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
4917 FROM {".$modname."} m
4918 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
4919 WHERE m.course = :courseid";
4920 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
4921 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
4923 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
4924 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
4925 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
4927 if ($instances) {
4928 foreach ($instances as $cm) {
4929 if ($cm->id) {
4930 // Delete activity context questions and question categories.
4931 question_delete_activity($cm, $showfeedback);
4932 // Notify the competency subsystem.
4933 \core_competency\api::hook_course_module_deleted($cm);
4935 if (function_exists($moddelete)) {
4936 // This purges all module data in related tables, extra user prefs, settings, etc.
4937 $moddelete($cm->modinstance);
4938 } else {
4939 // NOTE: we should not allow installation of modules with missing delete support!
4940 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
4941 $DB->delete_records($modname, array('id' => $cm->modinstance));
4944 if ($cm->id) {
4945 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
4946 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4947 $DB->delete_records('course_modules', array('id' => $cm->id));
4951 if (function_exists($moddeletecourse)) {
4952 // Execute optional course cleanup callback. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
4953 debugging("Callback delete_course is deprecated. Function $moddeletecourse should be converted " .
4954 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER);
4955 $moddeletecourse($course, $showfeedback);
4957 if ($instances and $showfeedback) {
4958 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
4960 } else {
4961 // Ooops, this module is not properly installed, force-delete it in the next block.
4965 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
4967 // Remove all data from availability and completion tables that is associated
4968 // with course-modules belonging to this course. Note this is done even if the
4969 // features are not enabled now, in case they were enabled previously.
4970 $DB->delete_records_select('course_modules_completion',
4971 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4972 array($courseid));
4974 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
4975 $cms = $DB->get_records('course_modules', array('course' => $course->id));
4976 $allmodulesbyid = array_flip($allmodules);
4977 foreach ($cms as $cm) {
4978 if (array_key_exists($cm->module, $allmodulesbyid)) {
4979 try {
4980 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
4981 } catch (Exception $e) {
4982 // Ignore weird or missing table problems.
4985 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4986 $DB->delete_records('course_modules', array('id' => $cm->id));
4989 if ($showfeedback) {
4990 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
4993 // Cleanup the rest of plugins. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
4994 $cleanuplugintypes = array('report', 'coursereport', 'format');
4995 $callbacks = get_plugins_with_function('delete_course', 'lib.php');
4996 foreach ($cleanuplugintypes as $type) {
4997 if (!empty($callbacks[$type])) {
4998 foreach ($callbacks[$type] as $pluginfunction) {
4999 debugging("Callback delete_course is deprecated. Function $pluginfunction should be converted " .
5000 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER);
5001 $pluginfunction($course->id, $showfeedback);
5003 if ($showfeedback) {
5004 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5009 // Delete questions and question categories.
5010 question_delete_course($course, $showfeedback);
5011 if ($showfeedback) {
5012 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5015 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5016 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5017 foreach ($childcontexts as $childcontext) {
5018 $childcontext->delete();
5020 unset($childcontexts);
5022 // Remove all roles and enrolments by default.
5023 if (empty($options['keep_roles_and_enrolments'])) {
5024 // This hack is used in restore when deleting contents of existing course.
5025 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5026 enrol_course_delete($course);
5027 if ($showfeedback) {
5028 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5032 // Delete any groups, removing members and grouping/course links first.
5033 if (empty($options['keep_groups_and_groupings'])) {
5034 groups_delete_groupings($course->id, $showfeedback);
5035 groups_delete_groups($course->id, $showfeedback);
5038 // Filters be gone!
5039 filter_delete_all_for_context($coursecontext->id);
5041 // Notes, you shall not pass!
5042 note_delete_all($course->id);
5044 // Die comments!
5045 comment::delete_comments($coursecontext->id);
5047 // Ratings are history too.
5048 $delopt = new stdclass();
5049 $delopt->contextid = $coursecontext->id;
5050 $rm = new rating_manager();
5051 $rm->delete_ratings($delopt);
5053 // Delete course tags.
5054 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5056 // Notify the competency subsystem.
5057 \core_competency\api::hook_course_deleted($course);
5059 // Delete calendar events.
5060 $DB->delete_records('event', array('courseid' => $course->id));
5061 $fs->delete_area_files($coursecontext->id, 'calendar');
5063 // Delete all related records in other core tables that may have a courseid
5064 // This array stores the tables that need to be cleared, as
5065 // table_name => column_name that contains the course id.
5066 $tablestoclear = array(
5067 'backup_courses' => 'courseid', // Scheduled backup stuff.
5068 'user_lastaccess' => 'courseid', // User access info.
5070 foreach ($tablestoclear as $table => $col) {
5071 $DB->delete_records($table, array($col => $course->id));
5074 // Delete all course backup files.
5075 $fs->delete_area_files($coursecontext->id, 'backup');
5077 // Cleanup course record - remove links to deleted stuff.
5078 $oldcourse = new stdClass();
5079 $oldcourse->id = $course->id;
5080 $oldcourse->summary = '';
5081 $oldcourse->cacherev = 0;
5082 $oldcourse->legacyfiles = 0;
5083 if (!empty($options['keep_groups_and_groupings'])) {
5084 $oldcourse->defaultgroupingid = 0;
5086 $DB->update_record('course', $oldcourse);
5088 // Delete course sections.
5089 $DB->delete_records('course_sections', array('course' => $course->id));
5091 // Delete legacy, section and any other course files.
5092 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5094 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5095 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5096 // Easy, do not delete the context itself...
5097 $coursecontext->delete_content();
5098 } else {
5099 // Hack alert!!!!
5100 // We can not drop all context stuff because it would bork enrolments and roles,
5101 // there might be also files used by enrol plugins...
5104 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5105 // also some non-standard unsupported plugins may try to store something there.
5106 fulldelete($CFG->dataroot.'/'.$course->id);
5108 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5109 $cachemodinfo = cache::make('core', 'coursemodinfo');
5110 $cachemodinfo->delete($courseid);
5112 // Trigger a course content deleted event.
5113 $event = \core\event\course_content_deleted::create(array(
5114 'objectid' => $course->id,
5115 'context' => $coursecontext,
5116 'other' => array('shortname' => $course->shortname,
5117 'fullname' => $course->fullname,
5118 'options' => $options) // Passing this for legacy reasons.
5120 $event->add_record_snapshot('course', $course);
5121 $event->trigger();
5123 return true;
5127 * Change dates in module - used from course reset.
5129 * @param string $modname forum, assignment, etc
5130 * @param array $fields array of date fields from mod table
5131 * @param int $timeshift time difference
5132 * @param int $courseid
5133 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5134 * @return bool success
5136 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5137 global $CFG, $DB;
5138 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5140 $return = true;
5141 $params = array($timeshift, $courseid);
5142 foreach ($fields as $field) {
5143 $updatesql = "UPDATE {".$modname."}
5144 SET $field = $field + ?
5145 WHERE course=? AND $field<>0";
5146 if ($modid) {
5147 $updatesql .= ' AND id=?';
5148 $params[] = $modid;
5150 $return = $DB->execute($updatesql, $params) && $return;
5153 $refreshfunction = $modname.'_refresh_events';
5154 if (function_exists($refreshfunction)) {
5155 $refreshfunction($courseid);
5158 return $return;
5162 * This function will empty a course of user data.
5163 * It will retain the activities and the structure of the course.
5165 * @param object $data an object containing all the settings including courseid (without magic quotes)
5166 * @return array status array of array component, item, error
5168 function reset_course_userdata($data) {
5169 global $CFG, $DB;
5170 require_once($CFG->libdir.'/gradelib.php');
5171 require_once($CFG->libdir.'/completionlib.php');
5172 require_once($CFG->dirroot.'/group/lib.php');
5174 $data->courseid = $data->id;
5175 $context = context_course::instance($data->courseid);
5177 $eventparams = array(
5178 'context' => $context,
5179 'courseid' => $data->id,
5180 'other' => array(
5181 'reset_options' => (array) $data
5184 $event = \core\event\course_reset_started::create($eventparams);
5185 $event->trigger();
5187 // Calculate the time shift of dates.
5188 if (!empty($data->reset_start_date)) {
5189 // Time part of course startdate should be zero.
5190 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5191 } else {
5192 $data->timeshift = 0;
5195 // Result array: component, item, error.
5196 $status = array();
5198 // Start the resetting.
5199 $componentstr = get_string('general');
5201 // Move the course start time.
5202 if (!empty($data->reset_start_date) and $data->timeshift) {
5203 // Change course start data.
5204 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5205 // Update all course and group events - do not move activity events.
5206 $updatesql = "UPDATE {event}
5207 SET timestart = timestart + ?
5208 WHERE courseid=? AND instance=0";
5209 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5211 // Update any date activity restrictions.
5212 if ($CFG->enableavailability) {
5213 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5216 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5219 if (!empty($data->reset_end_date)) {
5220 // If the user set a end date value respect it.
5221 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5222 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5223 // If there is a time shift apply it to the end date as well.
5224 $enddate = $data->reset_end_date_old + $data->timeshift;
5225 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5228 if (!empty($data->reset_events)) {
5229 $DB->delete_records('event', array('courseid' => $data->courseid));
5230 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5233 if (!empty($data->reset_notes)) {
5234 require_once($CFG->dirroot.'/notes/lib.php');
5235 note_delete_all($data->courseid);
5236 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5239 if (!empty($data->delete_blog_associations)) {
5240 require_once($CFG->dirroot.'/blog/lib.php');
5241 blog_remove_associations_for_course($data->courseid);
5242 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5245 if (!empty($data->reset_completion)) {
5246 // Delete course and activity completion information.
5247 $course = $DB->get_record('course', array('id' => $data->courseid));
5248 $cc = new completion_info($course);
5249 $cc->delete_all_completion_data();
5250 $status[] = array('component' => $componentstr,
5251 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5254 if (!empty($data->reset_competency_ratings)) {
5255 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5256 $status[] = array('component' => $componentstr,
5257 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5260 $componentstr = get_string('roles');
5262 if (!empty($data->reset_roles_overrides)) {
5263 $children = $context->get_child_contexts();
5264 foreach ($children as $child) {
5265 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5267 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5268 // Force refresh for logged in users.
5269 $context->mark_dirty();
5270 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5273 if (!empty($data->reset_roles_local)) {
5274 $children = $context->get_child_contexts();
5275 foreach ($children as $child) {
5276 role_unassign_all(array('contextid' => $child->id));
5278 // Force refresh for logged in users.
5279 $context->mark_dirty();
5280 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5283 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5284 $data->unenrolled = array();
5285 if (!empty($data->unenrol_users)) {
5286 $plugins = enrol_get_plugins(true);
5287 $instances = enrol_get_instances($data->courseid, true);
5288 foreach ($instances as $key => $instance) {
5289 if (!isset($plugins[$instance->enrol])) {
5290 unset($instances[$key]);
5291 continue;
5295 foreach ($data->unenrol_users as $withroleid) {
5296 if ($withroleid) {
5297 $sql = "SELECT ue.*
5298 FROM {user_enrolments} ue
5299 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5300 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5301 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5302 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5304 } else {
5305 // Without any role assigned at course context.
5306 $sql = "SELECT ue.*
5307 FROM {user_enrolments} ue
5308 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5309 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5310 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5311 WHERE ra.id IS null";
5312 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5315 $rs = $DB->get_recordset_sql($sql, $params);
5316 foreach ($rs as $ue) {
5317 if (!isset($instances[$ue->enrolid])) {
5318 continue;
5320 $instance = $instances[$ue->enrolid];
5321 $plugin = $plugins[$instance->enrol];
5322 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5323 continue;
5326 $plugin->unenrol_user($instance, $ue->userid);
5327 $data->unenrolled[$ue->userid] = $ue->userid;
5329 $rs->close();
5332 if (!empty($data->unenrolled)) {
5333 $status[] = array(
5334 'component' => $componentstr,
5335 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5336 'error' => false
5340 $componentstr = get_string('groups');
5342 // Remove all group members.
5343 if (!empty($data->reset_groups_members)) {
5344 groups_delete_group_members($data->courseid);
5345 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5348 // Remove all groups.
5349 if (!empty($data->reset_groups_remove)) {
5350 groups_delete_groups($data->courseid, false);
5351 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5354 // Remove all grouping members.
5355 if (!empty($data->reset_groupings_members)) {
5356 groups_delete_groupings_groups($data->courseid, false);
5357 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5360 // Remove all groupings.
5361 if (!empty($data->reset_groupings_remove)) {
5362 groups_delete_groupings($data->courseid, false);
5363 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5366 // Look in every instance of every module for data to delete.
5367 $unsupportedmods = array();
5368 if ($allmods = $DB->get_records('modules') ) {
5369 foreach ($allmods as $mod) {
5370 $modname = $mod->name;
5371 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5372 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5373 if (file_exists($modfile)) {
5374 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5375 continue; // Skip mods with no instances.
5377 include_once($modfile);
5378 if (function_exists($moddeleteuserdata)) {
5379 $modstatus = $moddeleteuserdata($data);
5380 if (is_array($modstatus)) {
5381 $status = array_merge($status, $modstatus);
5382 } else {
5383 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5385 } else {
5386 $unsupportedmods[] = $mod;
5388 } else {
5389 debugging('Missing lib.php in '.$modname.' module!');
5394 // Mention unsupported mods.
5395 if (!empty($unsupportedmods)) {
5396 foreach ($unsupportedmods as $mod) {
5397 $status[] = array(
5398 'component' => get_string('modulenameplural', $mod->name),
5399 'item' => '',
5400 'error' => get_string('resetnotimplemented')
5405 $componentstr = get_string('gradebook', 'grades');
5406 // Reset gradebook,.
5407 if (!empty($data->reset_gradebook_items)) {
5408 remove_course_grades($data->courseid, false);
5409 grade_grab_course_grades($data->courseid);
5410 grade_regrade_final_grades($data->courseid);
5411 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5413 } else if (!empty($data->reset_gradebook_grades)) {
5414 grade_course_reset($data->courseid);
5415 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5417 // Reset comments.
5418 if (!empty($data->reset_comments)) {
5419 require_once($CFG->dirroot.'/comment/lib.php');
5420 comment::reset_course_page_comments($context);
5423 $event = \core\event\course_reset_ended::create($eventparams);
5424 $event->trigger();
5426 return $status;
5430 * Generate an email processing address.
5432 * @param int $modid
5433 * @param string $modargs
5434 * @return string Returns email processing address
5436 function generate_email_processing_address($modid, $modargs) {
5437 global $CFG;
5439 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5440 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5446 * @todo Finish documenting this function
5448 * @param string $modargs
5449 * @param string $body Currently unused
5451 function moodle_process_email($modargs, $body) {
5452 global $DB;
5454 // The first char should be an unencoded letter. We'll take this as an action.
5455 switch ($modargs{0}) {
5456 case 'B': { // Bounce.
5457 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5458 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5459 // Check the half md5 of their email.
5460 $md5check = substr(md5($user->email), 0, 16);
5461 if ($md5check == substr($modargs, -16)) {
5462 set_bounce_count($user);
5464 // Else maybe they've already changed it?
5467 break;
5468 // Maybe more later?
5472 // CORRESPONDENCE.
5475 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5477 * @param string $action 'get', 'buffer', 'close' or 'flush'
5478 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5480 function get_mailer($action='get') {
5481 global $CFG;
5483 /** @var moodle_phpmailer $mailer */
5484 static $mailer = null;
5485 static $counter = 0;
5487 if (!isset($CFG->smtpmaxbulk)) {
5488 $CFG->smtpmaxbulk = 1;
5491 if ($action == 'get') {
5492 $prevkeepalive = false;
5494 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5495 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5496 $counter++;
5497 // Reset the mailer.
5498 $mailer->Priority = 3;
5499 $mailer->CharSet = 'UTF-8'; // Our default.
5500 $mailer->ContentType = "text/plain";
5501 $mailer->Encoding = "8bit";
5502 $mailer->From = "root@localhost";
5503 $mailer->FromName = "Root User";
5504 $mailer->Sender = "";
5505 $mailer->Subject = "";
5506 $mailer->Body = "";
5507 $mailer->AltBody = "";
5508 $mailer->ConfirmReadingTo = "";
5510 $mailer->clearAllRecipients();
5511 $mailer->clearReplyTos();
5512 $mailer->clearAttachments();
5513 $mailer->clearCustomHeaders();
5514 return $mailer;
5517 $prevkeepalive = $mailer->SMTPKeepAlive;
5518 get_mailer('flush');
5521 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5522 $mailer = new moodle_phpmailer();
5524 $counter = 1;
5526 if ($CFG->smtphosts == 'qmail') {
5527 // Use Qmail system.
5528 $mailer->isQmail();
5530 } else if (empty($CFG->smtphosts)) {
5531 // Use PHP mail() = sendmail.
5532 $mailer->isMail();
5534 } else {
5535 // Use SMTP directly.
5536 $mailer->isSMTP();
5537 if (!empty($CFG->debugsmtp)) {
5538 $mailer->SMTPDebug = true;
5540 // Specify main and backup servers.
5541 $mailer->Host = $CFG->smtphosts;
5542 // Specify secure connection protocol.
5543 $mailer->SMTPSecure = $CFG->smtpsecure;
5544 // Use previous keepalive.
5545 $mailer->SMTPKeepAlive = $prevkeepalive;
5547 if ($CFG->smtpuser) {
5548 // Use SMTP authentication.
5549 $mailer->SMTPAuth = true;
5550 $mailer->Username = $CFG->smtpuser;
5551 $mailer->Password = $CFG->smtppass;
5555 return $mailer;
5558 $nothing = null;
5560 // Keep smtp session open after sending.
5561 if ($action == 'buffer') {
5562 if (!empty($CFG->smtpmaxbulk)) {
5563 get_mailer('flush');
5564 $m = get_mailer();
5565 if ($m->Mailer == 'smtp') {
5566 $m->SMTPKeepAlive = true;
5569 return $nothing;
5572 // Close smtp session, but continue buffering.
5573 if ($action == 'flush') {
5574 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5575 if (!empty($mailer->SMTPDebug)) {
5576 echo '<pre>'."\n";
5578 $mailer->SmtpClose();
5579 if (!empty($mailer->SMTPDebug)) {
5580 echo '</pre>';
5583 return $nothing;
5586 // Close smtp session, do not buffer anymore.
5587 if ($action == 'close') {
5588 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5589 get_mailer('flush');
5590 $mailer->SMTPKeepAlive = false;
5592 $mailer = null; // Better force new instance.
5593 return $nothing;
5598 * A helper function to test for email diversion
5600 * @param string $email
5601 * @return bool Returns true if the email should be diverted
5603 function email_should_be_diverted($email) {
5604 global $CFG;
5606 if (empty($CFG->divertallemailsto)) {
5607 return false;
5610 if (empty($CFG->divertallemailsexcept)) {
5611 return true;
5614 $patterns = array_map('trim', explode(',', $CFG->divertallemailsexcept));
5615 foreach ($patterns as $pattern) {
5616 if (preg_match("/$pattern/", $email)) {
5617 return false;
5621 return true;
5625 * Generate a unique email Message-ID using the moodle domain and install path
5627 * @param string $localpart An optional unique message id prefix.
5628 * @return string The formatted ID ready for appending to the email headers.
5630 function generate_email_messageid($localpart = null) {
5631 global $CFG;
5633 $urlinfo = parse_url($CFG->wwwroot);
5634 $base = '@' . $urlinfo['host'];
5636 // If multiple moodles are on the same domain we want to tell them
5637 // apart so we add the install path to the local part. This means
5638 // that the id local part should never contain a / character so
5639 // we can correctly parse the id to reassemble the wwwroot.
5640 if (isset($urlinfo['path'])) {
5641 $base = $urlinfo['path'] . $base;
5644 if (empty($localpart)) {
5645 $localpart = uniqid('', true);
5648 // Because we may have an option /installpath suffix to the local part
5649 // of the id we need to escape any / chars which are in the $localpart.
5650 $localpart = str_replace('/', '%2F', $localpart);
5652 return '<' . $localpart . $base . '>';
5656 * Send an email to a specified user
5658 * @param stdClass $user A {@link $USER} object
5659 * @param stdClass $from A {@link $USER} object
5660 * @param string $subject plain text subject line of the email
5661 * @param string $messagetext plain text version of the message
5662 * @param string $messagehtml complete html version of the message (optional)
5663 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5664 * @param string $attachname the name of the file (extension indicates MIME)
5665 * @param bool $usetrueaddress determines whether $from email address should
5666 * be sent out. Will be overruled by user profile setting for maildisplay
5667 * @param string $replyto Email address to reply to
5668 * @param string $replytoname Name of reply to recipient
5669 * @param int $wordwrapwidth custom word wrap width, default 79
5670 * @return bool Returns true if mail was sent OK and false if there was an error.
5672 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5673 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5675 global $CFG, $PAGE, $SITE;
5677 if (empty($user) or empty($user->id)) {
5678 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5679 return false;
5682 if (empty($user->email)) {
5683 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5684 return false;
5687 if (!empty($user->deleted)) {
5688 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5689 return false;
5692 if (defined('BEHAT_SITE_RUNNING')) {
5693 // Fake email sending in behat.
5694 return true;
5697 if (!empty($CFG->noemailever)) {
5698 // Hidden setting for development sites, set in config.php if needed.
5699 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5700 return true;
5703 if (email_should_be_diverted($user->email)) {
5704 $subject = "[DIVERTED {$user->email}] $subject";
5705 $user = clone($user);
5706 $user->email = $CFG->divertallemailsto;
5709 // Skip mail to suspended users.
5710 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5711 return true;
5714 if (!validate_email($user->email)) {
5715 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5716 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5717 return false;
5720 if (over_bounce_threshold($user)) {
5721 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5722 return false;
5725 // TLD .invalid is specifically reserved for invalid domain names.
5726 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5727 if (substr($user->email, -8) == '.invalid') {
5728 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5729 return true; // This is not an error.
5732 // If the user is a remote mnet user, parse the email text for URL to the
5733 // wwwroot and modify the url to direct the user's browser to login at their
5734 // home site (identity provider - idp) before hitting the link itself.
5735 if (is_mnet_remote_user($user)) {
5736 require_once($CFG->dirroot.'/mnet/lib.php');
5738 $jumpurl = mnet_get_idp_jump_url($user);
5739 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5741 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5742 $callback,
5743 $messagetext);
5744 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5745 $callback,
5746 $messagehtml);
5748 $mail = get_mailer();
5750 if (!empty($mail->SMTPDebug)) {
5751 echo '<pre>' . "\n";
5754 $temprecipients = array();
5755 $tempreplyto = array();
5757 // Make sure that we fall back onto some reasonable no-reply address.
5758 $noreplyaddress = empty($CFG->noreplyaddress) ? 'noreply@' . get_host_from_url($CFG->wwwroot) : $CFG->noreplyaddress;
5760 // Make up an email address for handling bounces.
5761 if (!empty($CFG->handlebounces)) {
5762 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5763 $mail->Sender = generate_email_processing_address(0, $modargs);
5764 } else {
5765 $mail->Sender = $noreplyaddress;
5768 $alloweddomains = null;
5769 if (!empty($CFG->allowedemaildomains)) {
5770 $alloweddomains = explode(PHP_EOL, $CFG->allowedemaildomains);
5773 // Email will be sent using no reply address.
5774 if (empty($alloweddomains)) {
5775 $usetrueaddress = false;
5778 if (is_string($from)) { // So we can pass whatever we want if there is need.
5779 $mail->From = $noreplyaddress;
5780 $mail->FromName = $from;
5781 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
5782 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
5783 // in a course with the sender.
5784 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user, $alloweddomains)) {
5785 $mail->From = $from->email;
5786 $fromdetails = new stdClass();
5787 $fromdetails->name = fullname($from);
5788 $fromdetails->url = $CFG->wwwroot;
5789 $fromstring = $fromdetails->name;
5790 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
5791 $fromstring = get_string('emailvia', 'core', $fromdetails);
5793 $mail->FromName = $fromstring;
5794 if (empty($replyto)) {
5795 $tempreplyto[] = array($from->email, fullname($from));
5797 } else {
5798 $mail->From = $noreplyaddress;
5799 $fromdetails = new stdClass();
5800 $fromdetails->name = fullname($from);
5801 $fromdetails->url = $CFG->wwwroot;
5802 $fromstring = $fromdetails->name;
5803 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
5804 $fromstring = get_string('emailvia', 'core', $fromdetails);
5806 $mail->FromName = $fromstring;
5807 if (empty($replyto)) {
5808 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
5812 if (!empty($replyto)) {
5813 $tempreplyto[] = array($replyto, $replytoname);
5816 $temprecipients[] = array($user->email, fullname($user));
5818 // Set word wrap.
5819 $mail->WordWrap = $wordwrapwidth;
5821 if (!empty($from->customheaders)) {
5822 // Add custom headers.
5823 if (is_array($from->customheaders)) {
5824 foreach ($from->customheaders as $customheader) {
5825 $mail->addCustomHeader($customheader);
5827 } else {
5828 $mail->addCustomHeader($from->customheaders);
5832 // If the X-PHP-Originating-Script email header is on then also add an additional
5833 // header with details of where exactly in moodle the email was triggered from,
5834 // either a call to message_send() or to email_to_user().
5835 if (ini_get('mail.add_x_header')) {
5837 $stack = debug_backtrace(false);
5838 $origin = $stack[0];
5840 foreach ($stack as $depth => $call) {
5841 if ($call['function'] == 'message_send') {
5842 $origin = $call;
5846 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
5847 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
5848 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
5851 if (!empty($from->priority)) {
5852 $mail->Priority = $from->priority;
5855 $renderer = $PAGE->get_renderer('core');
5856 $context = array(
5857 'sitefullname' => $SITE->fullname,
5858 'siteshortname' => $SITE->shortname,
5859 'sitewwwroot' => $CFG->wwwroot,
5860 'subject' => $subject,
5861 'to' => $user->email,
5862 'toname' => fullname($user),
5863 'from' => $mail->From,
5864 'fromname' => $mail->FromName,
5866 if (!empty($tempreplyto[0])) {
5867 $context['replyto'] = $tempreplyto[0][0];
5868 $context['replytoname'] = $tempreplyto[0][1];
5870 if ($user->id > 0) {
5871 $context['touserid'] = $user->id;
5872 $context['tousername'] = $user->username;
5875 if (!empty($user->mailformat) && $user->mailformat == 1) {
5876 // Only process html templates if the user preferences allow html email.
5878 if ($messagehtml) {
5879 // If html has been given then pass it through the template.
5880 $context['body'] = $messagehtml;
5881 $messagehtml = $renderer->render_from_template('core/email_html', $context);
5883 } else {
5884 // If no html has been given, BUT there is an html wrapping template then
5885 // auto convert the text to html and then wrap it.
5886 $autohtml = trim(text_to_html($messagetext));
5887 $context['body'] = $autohtml;
5888 $temphtml = $renderer->render_from_template('core/email_html', $context);
5889 if ($autohtml != $temphtml) {
5890 $messagehtml = $temphtml;
5895 $context['body'] = $messagetext;
5896 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
5897 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
5898 $messagetext = $renderer->render_from_template('core/email_text', $context);
5900 // Autogenerate a MessageID if it's missing.
5901 if (empty($mail->MessageID)) {
5902 $mail->MessageID = generate_email_messageid();
5905 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5906 // Don't ever send HTML to users who don't want it.
5907 $mail->isHTML(true);
5908 $mail->Encoding = 'quoted-printable';
5909 $mail->Body = $messagehtml;
5910 $mail->AltBody = "\n$messagetext\n";
5911 } else {
5912 $mail->IsHTML(false);
5913 $mail->Body = "\n$messagetext\n";
5916 if ($attachment && $attachname) {
5917 if (preg_match( "~\\.\\.~" , $attachment )) {
5918 // Security check for ".." in dir path.
5919 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5920 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5921 } else {
5922 require_once($CFG->libdir.'/filelib.php');
5923 $mimetype = mimeinfo('type', $attachname);
5925 $attachmentpath = $attachment;
5927 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5928 $attachpath = str_replace('\\', '/', $attachmentpath);
5929 // Make sure both variables are normalised before comparing.
5930 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
5932 // If the attachment is a full path to a file in the tempdir, use it as is,
5933 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5934 if (strpos($attachpath, $temppath) !== 0) {
5935 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
5938 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5942 // Check if the email should be sent in an other charset then the default UTF-8.
5943 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5945 // Use the defined site mail charset or eventually the one preferred by the recipient.
5946 $charset = $CFG->sitemailcharset;
5947 if (!empty($CFG->allowusermailcharset)) {
5948 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5949 $charset = $useremailcharset;
5953 // Convert all the necessary strings if the charset is supported.
5954 $charsets = get_list_of_charsets();
5955 unset($charsets['UTF-8']);
5956 if (in_array($charset, $charsets)) {
5957 $mail->CharSet = $charset;
5958 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
5959 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
5960 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
5961 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
5963 foreach ($temprecipients as $key => $values) {
5964 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5966 foreach ($tempreplyto as $key => $values) {
5967 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5972 foreach ($temprecipients as $values) {
5973 $mail->addAddress($values[0], $values[1]);
5975 foreach ($tempreplyto as $values) {
5976 $mail->addReplyTo($values[0], $values[1]);
5979 if ($mail->send()) {
5980 set_send_count($user);
5981 if (!empty($mail->SMTPDebug)) {
5982 echo '</pre>';
5984 return true;
5985 } else {
5986 // Trigger event for failing to send email.
5987 $event = \core\event\email_failed::create(array(
5988 'context' => context_system::instance(),
5989 'userid' => $from->id,
5990 'relateduserid' => $user->id,
5991 'other' => array(
5992 'subject' => $subject,
5993 'message' => $messagetext,
5994 'errorinfo' => $mail->ErrorInfo
5997 $event->trigger();
5998 if (CLI_SCRIPT) {
5999 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6001 if (!empty($mail->SMTPDebug)) {
6002 echo '</pre>';
6004 return false;
6009 * Check to see if a user's real email address should be used for the "From" field.
6011 * @param object $from The user object for the user we are sending the email from.
6012 * @param object $user The user object that we are sending the email to.
6013 * @param array $alloweddomains An array of allowed domains that we can send email from.
6014 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6016 function can_send_from_real_email_address($from, $user, $alloweddomains) {
6017 // Email is in the list of allowed domains for sending email,
6018 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6019 // in a course with the sender.
6020 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6021 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6022 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6023 && enrol_get_shared_courses($user, $from, false, true)))) {
6024 return true;
6026 return false;
6030 * Generate a signoff for emails based on support settings
6032 * @return string
6034 function generate_email_signoff() {
6035 global $CFG;
6037 $signoff = "\n";
6038 if (!empty($CFG->supportname)) {
6039 $signoff .= $CFG->supportname."\n";
6041 if (!empty($CFG->supportemail)) {
6042 $signoff .= $CFG->supportemail."\n";
6044 if (!empty($CFG->supportpage)) {
6045 $signoff .= $CFG->supportpage."\n";
6047 return $signoff;
6051 * Sets specified user's password and send the new password to the user via email.
6053 * @param stdClass $user A {@link $USER} object
6054 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6055 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6057 function setnew_password_and_mail($user, $fasthash = false) {
6058 global $CFG, $DB;
6060 // We try to send the mail in language the user understands,
6061 // unfortunately the filter_string() does not support alternative langs yet
6062 // so multilang will not work properly for site->fullname.
6063 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6065 $site = get_site();
6067 $supportuser = core_user::get_support_user();
6069 $newpassword = generate_password();
6071 update_internal_user_password($user, $newpassword, $fasthash);
6073 $a = new stdClass();
6074 $a->firstname = fullname($user, true);
6075 $a->sitename = format_string($site->fullname);
6076 $a->username = $user->username;
6077 $a->newpassword = $newpassword;
6078 $a->link = $CFG->wwwroot .'/login/';
6079 $a->signoff = generate_email_signoff();
6081 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6083 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6085 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6086 return email_to_user($user, $supportuser, $subject, $message);
6091 * Resets specified user's password and send the new password to the user via email.
6093 * @param stdClass $user A {@link $USER} object
6094 * @return bool Returns true if mail was sent OK and false if there was an error.
6096 function reset_password_and_mail($user) {
6097 global $CFG;
6099 $site = get_site();
6100 $supportuser = core_user::get_support_user();
6102 $userauth = get_auth_plugin($user->auth);
6103 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6104 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6105 return false;
6108 $newpassword = generate_password();
6110 if (!$userauth->user_update_password($user, $newpassword)) {
6111 print_error("cannotsetpassword");
6114 $a = new stdClass();
6115 $a->firstname = $user->firstname;
6116 $a->lastname = $user->lastname;
6117 $a->sitename = format_string($site->fullname);
6118 $a->username = $user->username;
6119 $a->newpassword = $newpassword;
6120 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
6121 $a->signoff = generate_email_signoff();
6123 $message = get_string('newpasswordtext', '', $a);
6125 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6127 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6129 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6130 return email_to_user($user, $supportuser, $subject, $message);
6134 * Send email to specified user with confirmation text and activation link.
6136 * @param stdClass $user A {@link $USER} object
6137 * @param string $confirmationurl user confirmation URL
6138 * @return bool Returns true if mail was sent OK and false if there was an error.
6140 function send_confirmation_email($user, $confirmationurl = null) {
6141 global $CFG;
6143 $site = get_site();
6144 $supportuser = core_user::get_support_user();
6146 $data = new stdClass();
6147 $data->firstname = fullname($user);
6148 $data->sitename = format_string($site->fullname);
6149 $data->admin = generate_email_signoff();
6151 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6153 $username = urlencode($user->username);
6154 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
6155 if (empty($confirmationurl)) {
6156 $confirmationurl = '/login/confirm.php';
6158 $confirmationurl = new moodle_url($confirmationurl, array('data' => $user->secret .'/'. $username));
6159 $data->link = $confirmationurl->out(false);
6161 $message = get_string('emailconfirmation', '', $data);
6162 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6164 $user->mailformat = 1; // Always send HTML version as well.
6166 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6167 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6171 * Sends a password change confirmation email.
6173 * @param stdClass $user A {@link $USER} object
6174 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6175 * @return bool Returns true if mail was sent OK and false if there was an error.
6177 function send_password_change_confirmation_email($user, $resetrecord) {
6178 global $CFG;
6180 $site = get_site();
6181 $supportuser = core_user::get_support_user();
6182 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6184 $data = new stdClass();
6185 $data->firstname = $user->firstname;
6186 $data->lastname = $user->lastname;
6187 $data->username = $user->username;
6188 $data->sitename = format_string($site->fullname);
6189 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6190 $data->admin = generate_email_signoff();
6191 $data->resetminutes = $pwresetmins;
6193 $message = get_string('emailresetconfirmation', '', $data);
6194 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6196 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6197 return email_to_user($user, $supportuser, $subject, $message);
6202 * Sends an email containinginformation on how to change your password.
6204 * @param stdClass $user A {@link $USER} object
6205 * @return bool Returns true if mail was sent OK and false if there was an error.
6207 function send_password_change_info($user) {
6208 global $CFG;
6210 $site = get_site();
6211 $supportuser = core_user::get_support_user();
6212 $systemcontext = context_system::instance();
6214 $data = new stdClass();
6215 $data->firstname = $user->firstname;
6216 $data->lastname = $user->lastname;
6217 $data->sitename = format_string($site->fullname);
6218 $data->admin = generate_email_signoff();
6220 $userauth = get_auth_plugin($user->auth);
6222 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6223 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6224 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6225 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6226 return email_to_user($user, $supportuser, $subject, $message);
6229 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6230 // We have some external url for password changing.
6231 $data->link .= $userauth->change_password_url();
6233 } else {
6234 // No way to change password, sorry.
6235 $data->link = '';
6238 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6239 $message = get_string('emailpasswordchangeinfo', '', $data);
6240 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6241 } else {
6242 $message = get_string('emailpasswordchangeinfofail', '', $data);
6243 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6246 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6247 return email_to_user($user, $supportuser, $subject, $message);
6252 * Check that an email is allowed. It returns an error message if there was a problem.
6254 * @param string $email Content of email
6255 * @return string|false
6257 function email_is_not_allowed($email) {
6258 global $CFG;
6260 if (!empty($CFG->allowemailaddresses)) {
6261 $allowed = explode(' ', $CFG->allowemailaddresses);
6262 foreach ($allowed as $allowedpattern) {
6263 $allowedpattern = trim($allowedpattern);
6264 if (!$allowedpattern) {
6265 continue;
6267 if (strpos($allowedpattern, '.') === 0) {
6268 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6269 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6270 return false;
6273 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6274 return false;
6277 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6279 } else if (!empty($CFG->denyemailaddresses)) {
6280 $denied = explode(' ', $CFG->denyemailaddresses);
6281 foreach ($denied as $deniedpattern) {
6282 $deniedpattern = trim($deniedpattern);
6283 if (!$deniedpattern) {
6284 continue;
6286 if (strpos($deniedpattern, '.') === 0) {
6287 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6288 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6289 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6292 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6293 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6298 return false;
6301 // FILE HANDLING.
6304 * Returns local file storage instance
6306 * @return file_storage
6308 function get_file_storage() {
6309 global $CFG;
6311 static $fs = null;
6313 if ($fs) {
6314 return $fs;
6317 require_once("$CFG->libdir/filelib.php");
6319 if (isset($CFG->filedir)) {
6320 $filedir = $CFG->filedir;
6321 } else {
6322 $filedir = $CFG->dataroot.'/filedir';
6325 if (isset($CFG->trashdir)) {
6326 $trashdirdir = $CFG->trashdir;
6327 } else {
6328 $trashdirdir = $CFG->dataroot.'/trashdir';
6331 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
6333 return $fs;
6337 * Returns local file storage instance
6339 * @return file_browser
6341 function get_file_browser() {
6342 global $CFG;
6344 static $fb = null;
6346 if ($fb) {
6347 return $fb;
6350 require_once("$CFG->libdir/filelib.php");
6352 $fb = new file_browser();
6354 return $fb;
6358 * Returns file packer
6360 * @param string $mimetype default application/zip
6361 * @return file_packer
6363 function get_file_packer($mimetype='application/zip') {
6364 global $CFG;
6366 static $fp = array();
6368 if (isset($fp[$mimetype])) {
6369 return $fp[$mimetype];
6372 switch ($mimetype) {
6373 case 'application/zip':
6374 case 'application/vnd.moodle.profiling':
6375 $classname = 'zip_packer';
6376 break;
6378 case 'application/x-gzip' :
6379 $classname = 'tgz_packer';
6380 break;
6382 case 'application/vnd.moodle.backup':
6383 $classname = 'mbz_packer';
6384 break;
6386 default:
6387 return false;
6390 require_once("$CFG->libdir/filestorage/$classname.php");
6391 $fp[$mimetype] = new $classname();
6393 return $fp[$mimetype];
6397 * Returns current name of file on disk if it exists.
6399 * @param string $newfile File to be verified
6400 * @return string Current name of file on disk if true
6402 function valid_uploaded_file($newfile) {
6403 if (empty($newfile)) {
6404 return '';
6406 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6407 return $newfile['tmp_name'];
6408 } else {
6409 return '';
6414 * Returns the maximum size for uploading files.
6416 * There are seven possible upload limits:
6417 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6418 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6419 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6420 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6421 * 5. by the Moodle admin in $CFG->maxbytes
6422 * 6. by the teacher in the current course $course->maxbytes
6423 * 7. by the teacher for the current module, eg $assignment->maxbytes
6425 * These last two are passed to this function as arguments (in bytes).
6426 * Anything defined as 0 is ignored.
6427 * The smallest of all the non-zero numbers is returned.
6429 * @todo Finish documenting this function
6431 * @param int $sitebytes Set maximum size
6432 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6433 * @param int $modulebytes Current module ->maxbytes (in bytes)
6434 * @param bool $unused This parameter has been deprecated and is not used any more.
6435 * @return int The maximum size for uploading files.
6437 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6439 if (! $filesize = ini_get('upload_max_filesize')) {
6440 $filesize = '5M';
6442 $minimumsize = get_real_size($filesize);
6444 if ($postsize = ini_get('post_max_size')) {
6445 $postsize = get_real_size($postsize);
6446 if ($postsize < $minimumsize) {
6447 $minimumsize = $postsize;
6451 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6452 $minimumsize = $sitebytes;
6455 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6456 $minimumsize = $coursebytes;
6459 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6460 $minimumsize = $modulebytes;
6463 return $minimumsize;
6467 * Returns the maximum size for uploading files for the current user
6469 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6471 * @param context $context The context in which to check user capabilities
6472 * @param int $sitebytes Set maximum size
6473 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6474 * @param int $modulebytes Current module ->maxbytes (in bytes)
6475 * @param stdClass $user The user
6476 * @param bool $unused This parameter has been deprecated and is not used any more.
6477 * @return int The maximum size for uploading files.
6479 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6480 $unused = false) {
6481 global $USER;
6483 if (empty($user)) {
6484 $user = $USER;
6487 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6488 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6491 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6495 * Returns an array of possible sizes in local language
6497 * Related to {@link get_max_upload_file_size()} - this function returns an
6498 * array of possible sizes in an array, translated to the
6499 * local language.
6501 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6503 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6504 * with the value set to 0. This option will be the first in the list.
6506 * @uses SORT_NUMERIC
6507 * @param int $sitebytes Set maximum size
6508 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6509 * @param int $modulebytes Current module ->maxbytes (in bytes)
6510 * @param int|array $custombytes custom upload size/s which will be added to list,
6511 * Only value/s smaller then maxsize will be added to list.
6512 * @return array
6514 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6515 global $CFG;
6517 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6518 return array();
6521 if ($sitebytes == 0) {
6522 // Will get the minimum of upload_max_filesize or post_max_size.
6523 $sitebytes = get_max_upload_file_size();
6526 $filesize = array();
6527 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6528 5242880, 10485760, 20971520, 52428800, 104857600);
6530 // If custombytes is given and is valid then add it to the list.
6531 if (is_number($custombytes) and $custombytes > 0) {
6532 $custombytes = (int)$custombytes;
6533 if (!in_array($custombytes, $sizelist)) {
6534 $sizelist[] = $custombytes;
6536 } else if (is_array($custombytes)) {
6537 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6540 // Allow maxbytes to be selected if it falls outside the above boundaries.
6541 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6542 // Note: get_real_size() is used in order to prevent problems with invalid values.
6543 $sizelist[] = get_real_size($CFG->maxbytes);
6546 foreach ($sizelist as $sizebytes) {
6547 if ($sizebytes < $maxsize && $sizebytes > 0) {
6548 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6552 $limitlevel = '';
6553 $displaysize = '';
6554 if ($modulebytes &&
6555 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6556 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6557 $limitlevel = get_string('activity', 'core');
6558 $displaysize = display_size($modulebytes);
6559 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6561 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6562 $limitlevel = get_string('course', 'core');
6563 $displaysize = display_size($coursebytes);
6564 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6566 } else if ($sitebytes) {
6567 $limitlevel = get_string('site', 'core');
6568 $displaysize = display_size($sitebytes);
6569 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6572 krsort($filesize, SORT_NUMERIC);
6573 if ($limitlevel) {
6574 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6575 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6578 return $filesize;
6582 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6584 * If excludefiles is defined, then that file/directory is ignored
6585 * If getdirs is true, then (sub)directories are included in the output
6586 * If getfiles is true, then files are included in the output
6587 * (at least one of these must be true!)
6589 * @todo Finish documenting this function. Add examples of $excludefile usage.
6591 * @param string $rootdir A given root directory to start from
6592 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6593 * @param bool $descend If true then subdirectories are recursed as well
6594 * @param bool $getdirs If true then (sub)directories are included in the output
6595 * @param bool $getfiles If true then files are included in the output
6596 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6598 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6600 $dirs = array();
6602 if (!$getdirs and !$getfiles) { // Nothing to show.
6603 return $dirs;
6606 if (!is_dir($rootdir)) { // Must be a directory.
6607 return $dirs;
6610 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6611 return $dirs;
6614 if (!is_array($excludefiles)) {
6615 $excludefiles = array($excludefiles);
6618 while (false !== ($file = readdir($dir))) {
6619 $firstchar = substr($file, 0, 1);
6620 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6621 continue;
6623 $fullfile = $rootdir .'/'. $file;
6624 if (filetype($fullfile) == 'dir') {
6625 if ($getdirs) {
6626 $dirs[] = $file;
6628 if ($descend) {
6629 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6630 foreach ($subdirs as $subdir) {
6631 $dirs[] = $file .'/'. $subdir;
6634 } else if ($getfiles) {
6635 $dirs[] = $file;
6638 closedir($dir);
6640 asort($dirs);
6642 return $dirs;
6647 * Adds up all the files in a directory and works out the size.
6649 * @param string $rootdir The directory to start from
6650 * @param string $excludefile A file to exclude when summing directory size
6651 * @return int The summed size of all files and subfiles within the root directory
6653 function get_directory_size($rootdir, $excludefile='') {
6654 global $CFG;
6656 // Do it this way if we can, it's much faster.
6657 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6658 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6659 $output = null;
6660 $return = null;
6661 exec($command, $output, $return);
6662 if (is_array($output)) {
6663 // We told it to return k.
6664 return get_real_size(intval($output[0]).'k');
6668 if (!is_dir($rootdir)) {
6669 // Must be a directory.
6670 return 0;
6673 if (!$dir = @opendir($rootdir)) {
6674 // Can't open it for some reason.
6675 return 0;
6678 $size = 0;
6680 while (false !== ($file = readdir($dir))) {
6681 $firstchar = substr($file, 0, 1);
6682 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6683 continue;
6685 $fullfile = $rootdir .'/'. $file;
6686 if (filetype($fullfile) == 'dir') {
6687 $size += get_directory_size($fullfile, $excludefile);
6688 } else {
6689 $size += filesize($fullfile);
6692 closedir($dir);
6694 return $size;
6698 * Converts bytes into display form
6700 * @static string $gb Localized string for size in gigabytes
6701 * @static string $mb Localized string for size in megabytes
6702 * @static string $kb Localized string for size in kilobytes
6703 * @static string $b Localized string for size in bytes
6704 * @param int $size The size to convert to human readable form
6705 * @return string
6707 function display_size($size) {
6709 static $gb, $mb, $kb, $b;
6711 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6712 return get_string('unlimited');
6715 if (empty($gb)) {
6716 $gb = get_string('sizegb');
6717 $mb = get_string('sizemb');
6718 $kb = get_string('sizekb');
6719 $b = get_string('sizeb');
6722 if ($size >= 1073741824) {
6723 $size = round($size / 1073741824 * 10) / 10 . $gb;
6724 } else if ($size >= 1048576) {
6725 $size = round($size / 1048576 * 10) / 10 . $mb;
6726 } else if ($size >= 1024) {
6727 $size = round($size / 1024 * 10) / 10 . $kb;
6728 } else {
6729 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6731 return $size;
6735 * Cleans a given filename by removing suspicious or troublesome characters
6737 * @see clean_param()
6738 * @param string $string file name
6739 * @return string cleaned file name
6741 function clean_filename($string) {
6742 return clean_param($string, PARAM_FILE);
6746 // STRING TRANSLATION.
6749 * Returns the code for the current language
6751 * @category string
6752 * @return string
6754 function current_language() {
6755 global $CFG, $USER, $SESSION, $COURSE;
6757 if (!empty($SESSION->forcelang)) {
6758 // Allows overriding course-forced language (useful for admins to check
6759 // issues in courses whose language they don't understand).
6760 // Also used by some code to temporarily get language-related information in a
6761 // specific language (see force_current_language()).
6762 $return = $SESSION->forcelang;
6764 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6765 // Course language can override all other settings for this page.
6766 $return = $COURSE->lang;
6768 } else if (!empty($SESSION->lang)) {
6769 // Session language can override other settings.
6770 $return = $SESSION->lang;
6772 } else if (!empty($USER->lang)) {
6773 $return = $USER->lang;
6775 } else if (isset($CFG->lang)) {
6776 $return = $CFG->lang;
6778 } else {
6779 $return = 'en';
6782 // Just in case this slipped in from somewhere by accident.
6783 $return = str_replace('_utf8', '', $return);
6785 return $return;
6789 * Returns parent language of current active language if defined
6791 * @category string
6792 * @param string $lang null means current language
6793 * @return string
6795 function get_parent_language($lang=null) {
6797 // Let's hack around the current language.
6798 if (!empty($lang)) {
6799 $oldforcelang = force_current_language($lang);
6802 $parentlang = get_string('parentlanguage', 'langconfig');
6803 if ($parentlang === 'en') {
6804 $parentlang = '';
6807 // Let's hack around the current language.
6808 if (!empty($lang)) {
6809 force_current_language($oldforcelang);
6812 return $parentlang;
6816 * Force the current language to get strings and dates localised in the given language.
6818 * After calling this function, all strings will be provided in the given language
6819 * until this function is called again, or equivalent code is run.
6821 * @param string $language
6822 * @return string previous $SESSION->forcelang value
6824 function force_current_language($language) {
6825 global $SESSION;
6826 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6827 if ($language !== $sessionforcelang) {
6828 // Seting forcelang to null or an empty string disables it's effect.
6829 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6830 $SESSION->forcelang = $language;
6831 moodle_setlocale();
6834 return $sessionforcelang;
6838 * Returns current string_manager instance.
6840 * The param $forcereload is needed for CLI installer only where the string_manager instance
6841 * must be replaced during the install.php script life time.
6843 * @category string
6844 * @param bool $forcereload shall the singleton be released and new instance created instead?
6845 * @return core_string_manager
6847 function get_string_manager($forcereload=false) {
6848 global $CFG;
6850 static $singleton = null;
6852 if ($forcereload) {
6853 $singleton = null;
6855 if ($singleton === null) {
6856 if (empty($CFG->early_install_lang)) {
6858 if (empty($CFG->langlist)) {
6859 $translist = array();
6860 } else {
6861 $translist = explode(',', $CFG->langlist);
6864 if (!empty($CFG->config_php_settings['customstringmanager'])) {
6865 $classname = $CFG->config_php_settings['customstringmanager'];
6867 if (class_exists($classname)) {
6868 $implements = class_implements($classname);
6870 if (isset($implements['core_string_manager'])) {
6871 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist);
6872 return $singleton;
6874 } else {
6875 debugging('Unable to instantiate custom string manager: class '.$classname.
6876 ' does not implement the core_string_manager interface.');
6879 } else {
6880 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
6884 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6886 } else {
6887 $singleton = new core_string_manager_install();
6891 return $singleton;
6895 * Returns a localized string.
6897 * Returns the translated string specified by $identifier as
6898 * for $module. Uses the same format files as STphp.
6899 * $a is an object, string or number that can be used
6900 * within translation strings
6902 * eg 'hello {$a->firstname} {$a->lastname}'
6903 * or 'hello {$a}'
6905 * If you would like to directly echo the localized string use
6906 * the function {@link print_string()}
6908 * Example usage of this function involves finding the string you would
6909 * like a local equivalent of and using its identifier and module information
6910 * to retrieve it.<br/>
6911 * If you open moodle/lang/en/moodle.php and look near line 278
6912 * you will find a string to prompt a user for their word for 'course'
6913 * <code>
6914 * $string['course'] = 'Course';
6915 * </code>
6916 * So if you want to display the string 'Course'
6917 * in any language that supports it on your site
6918 * you just need to use the identifier 'course'
6919 * <code>
6920 * $mystring = '<strong>'. get_string('course') .'</strong>';
6921 * or
6922 * </code>
6923 * If the string you want is in another file you'd take a slightly
6924 * different approach. Looking in moodle/lang/en/calendar.php you find
6925 * around line 75:
6926 * <code>
6927 * $string['typecourse'] = 'Course event';
6928 * </code>
6929 * If you want to display the string "Course event" in any language
6930 * supported you would use the identifier 'typecourse' and the module 'calendar'
6931 * (because it is in the file calendar.php):
6932 * <code>
6933 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6934 * </code>
6936 * As a last resort, should the identifier fail to map to a string
6937 * the returned string will be [[ $identifier ]]
6939 * In Moodle 2.3 there is a new argument to this function $lazyload.
6940 * Setting $lazyload to true causes get_string to return a lang_string object
6941 * rather than the string itself. The fetching of the string is then put off until
6942 * the string object is first used. The object can be used by calling it's out
6943 * method or by casting the object to a string, either directly e.g.
6944 * (string)$stringobject
6945 * or indirectly by using the string within another string or echoing it out e.g.
6946 * echo $stringobject
6947 * return "<p>{$stringobject}</p>";
6948 * It is worth noting that using $lazyload and attempting to use the string as an
6949 * array key will cause a fatal error as objects cannot be used as array keys.
6950 * But you should never do that anyway!
6951 * For more information {@link lang_string}
6953 * @category string
6954 * @param string $identifier The key identifier for the localized string
6955 * @param string $component The module where the key identifier is stored,
6956 * usually expressed as the filename in the language pack without the
6957 * .php on the end but can also be written as mod/forum or grade/export/xls.
6958 * If none is specified then moodle.php is used.
6959 * @param string|object|array $a An object, string or number that can be used
6960 * within translation strings
6961 * @param bool $lazyload If set to true a string object is returned instead of
6962 * the string itself. The string then isn't calculated until it is first used.
6963 * @return string The localized string.
6964 * @throws coding_exception
6966 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6967 global $CFG;
6969 // If the lazy load argument has been supplied return a lang_string object
6970 // instead.
6971 // We need to make sure it is true (and a bool) as you will see below there
6972 // used to be a forth argument at one point.
6973 if ($lazyload === true) {
6974 return new lang_string($identifier, $component, $a);
6977 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
6978 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
6981 // There is now a forth argument again, this time it is a boolean however so
6982 // we can still check for the old extralocations parameter.
6983 if (!is_bool($lazyload) && !empty($lazyload)) {
6984 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6987 if (strpos($component, '/') !== false) {
6988 debugging('The module name you passed to get_string is the deprecated format ' .
6989 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
6990 $componentpath = explode('/', $component);
6992 switch ($componentpath[0]) {
6993 case 'mod':
6994 $component = $componentpath[1];
6995 break;
6996 case 'blocks':
6997 case 'block':
6998 $component = 'block_'.$componentpath[1];
6999 break;
7000 case 'enrol':
7001 $component = 'enrol_'.$componentpath[1];
7002 break;
7003 case 'format':
7004 $component = 'format_'.$componentpath[1];
7005 break;
7006 case 'grade':
7007 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7008 break;
7012 $result = get_string_manager()->get_string($identifier, $component, $a);
7014 // Debugging feature lets you display string identifier and component.
7015 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7016 $result .= ' {' . $identifier . '/' . $component . '}';
7018 return $result;
7022 * Converts an array of strings to their localized value.
7024 * @param array $array An array of strings
7025 * @param string $component The language module that these strings can be found in.
7026 * @return stdClass translated strings.
7028 function get_strings($array, $component = '') {
7029 $string = new stdClass;
7030 foreach ($array as $item) {
7031 $string->$item = get_string($item, $component);
7033 return $string;
7037 * Prints out a translated string.
7039 * Prints out a translated string using the return value from the {@link get_string()} function.
7041 * Example usage of this function when the string is in the moodle.php file:<br/>
7042 * <code>
7043 * echo '<strong>';
7044 * print_string('course');
7045 * echo '</strong>';
7046 * </code>
7048 * Example usage of this function when the string is not in the moodle.php file:<br/>
7049 * <code>
7050 * echo '<h1>';
7051 * print_string('typecourse', 'calendar');
7052 * echo '</h1>';
7053 * </code>
7055 * @category string
7056 * @param string $identifier The key identifier for the localized string
7057 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7058 * @param string|object|array $a An object, string or number that can be used within translation strings
7060 function print_string($identifier, $component = '', $a = null) {
7061 echo get_string($identifier, $component, $a);
7065 * Returns a list of charset codes
7067 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7068 * (checking that such charset is supported by the texlib library!)
7070 * @return array And associative array with contents in the form of charset => charset
7072 function get_list_of_charsets() {
7074 $charsets = array(
7075 'EUC-JP' => 'EUC-JP',
7076 'ISO-2022-JP'=> 'ISO-2022-JP',
7077 'ISO-8859-1' => 'ISO-8859-1',
7078 'SHIFT-JIS' => 'SHIFT-JIS',
7079 'GB2312' => 'GB2312',
7080 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7081 'UTF-8' => 'UTF-8');
7083 asort($charsets);
7085 return $charsets;
7089 * Returns a list of valid and compatible themes
7091 * @return array
7093 function get_list_of_themes() {
7094 global $CFG;
7096 $themes = array();
7098 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7099 $themelist = explode(',', $CFG->themelist);
7100 } else {
7101 $themelist = array_keys(core_component::get_plugin_list("theme"));
7104 foreach ($themelist as $key => $themename) {
7105 $theme = theme_config::load($themename);
7106 $themes[$themename] = $theme;
7109 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7111 return $themes;
7115 * Factory function for emoticon_manager
7117 * @return emoticon_manager singleton
7119 function get_emoticon_manager() {
7120 static $singleton = null;
7122 if (is_null($singleton)) {
7123 $singleton = new emoticon_manager();
7126 return $singleton;
7130 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7132 * Whenever this manager mentiones 'emoticon object', the following data
7133 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7134 * altidentifier and altcomponent
7136 * @see admin_setting_emoticons
7138 * @copyright 2010 David Mudrak
7139 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7141 class emoticon_manager {
7144 * Returns the currently enabled emoticons
7146 * @return array of emoticon objects
7148 public function get_emoticons() {
7149 global $CFG;
7151 if (empty($CFG->emoticons)) {
7152 return array();
7155 $emoticons = $this->decode_stored_config($CFG->emoticons);
7157 if (!is_array($emoticons)) {
7158 // Something is wrong with the format of stored setting.
7159 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7160 return array();
7163 return $emoticons;
7167 * Converts emoticon object into renderable pix_emoticon object
7169 * @param stdClass $emoticon emoticon object
7170 * @param array $attributes explicit HTML attributes to set
7171 * @return pix_emoticon
7173 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7174 $stringmanager = get_string_manager();
7175 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7176 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7177 } else {
7178 $alt = s($emoticon->text);
7180 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7184 * Encodes the array of emoticon objects into a string storable in config table
7186 * @see self::decode_stored_config()
7187 * @param array $emoticons array of emtocion objects
7188 * @return string
7190 public function encode_stored_config(array $emoticons) {
7191 return json_encode($emoticons);
7195 * Decodes the string into an array of emoticon objects
7197 * @see self::encode_stored_config()
7198 * @param string $encoded
7199 * @return string|null
7201 public function decode_stored_config($encoded) {
7202 $decoded = json_decode($encoded);
7203 if (!is_array($decoded)) {
7204 return null;
7206 return $decoded;
7210 * Returns default set of emoticons supported by Moodle
7212 * @return array of sdtClasses
7214 public function default_emoticons() {
7215 return array(
7216 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7217 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7218 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7219 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7220 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7221 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7222 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7223 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7224 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7225 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7226 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7227 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7228 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7229 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7230 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7231 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7232 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7233 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7234 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7235 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7236 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7237 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7238 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7239 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7240 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7241 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7242 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7243 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7244 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7245 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7250 * Helper method preparing the stdClass with the emoticon properties
7252 * @param string|array $text or array of strings
7253 * @param string $imagename to be used by {@link pix_emoticon}
7254 * @param string $altidentifier alternative string identifier, null for no alt
7255 * @param string $altcomponent where the alternative string is defined
7256 * @param string $imagecomponent to be used by {@link pix_emoticon}
7257 * @return stdClass
7259 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7260 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7261 return (object)array(
7262 'text' => $text,
7263 'imagename' => $imagename,
7264 'imagecomponent' => $imagecomponent,
7265 'altidentifier' => $altidentifier,
7266 'altcomponent' => $altcomponent,
7271 // ENCRYPTION.
7274 * rc4encrypt
7276 * @param string $data Data to encrypt.
7277 * @return string The now encrypted data.
7279 function rc4encrypt($data) {
7280 return endecrypt(get_site_identifier(), $data, '');
7284 * rc4decrypt
7286 * @param string $data Data to decrypt.
7287 * @return string The now decrypted data.
7289 function rc4decrypt($data) {
7290 return endecrypt(get_site_identifier(), $data, 'de');
7294 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7296 * @todo Finish documenting this function
7298 * @param string $pwd The password to use when encrypting or decrypting
7299 * @param string $data The data to be decrypted/encrypted
7300 * @param string $case Either 'de' for decrypt or '' for encrypt
7301 * @return string
7303 function endecrypt ($pwd, $data, $case) {
7305 if ($case == 'de') {
7306 $data = urldecode($data);
7309 $key[] = '';
7310 $box[] = '';
7311 $pwdlength = strlen($pwd);
7313 for ($i = 0; $i <= 255; $i++) {
7314 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7315 $box[$i] = $i;
7318 $x = 0;
7320 for ($i = 0; $i <= 255; $i++) {
7321 $x = ($x + $box[$i] + $key[$i]) % 256;
7322 $tempswap = $box[$i];
7323 $box[$i] = $box[$x];
7324 $box[$x] = $tempswap;
7327 $cipher = '';
7329 $a = 0;
7330 $j = 0;
7332 for ($i = 0; $i < strlen($data); $i++) {
7333 $a = ($a + 1) % 256;
7334 $j = ($j + $box[$a]) % 256;
7335 $temp = $box[$a];
7336 $box[$a] = $box[$j];
7337 $box[$j] = $temp;
7338 $k = $box[(($box[$a] + $box[$j]) % 256)];
7339 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7340 $cipher .= chr($cipherby);
7343 if ($case == 'de') {
7344 $cipher = urldecode(urlencode($cipher));
7345 } else {
7346 $cipher = urlencode($cipher);
7349 return $cipher;
7352 // ENVIRONMENT CHECKING.
7355 * This method validates a plug name. It is much faster than calling clean_param.
7357 * @param string $name a string that might be a plugin name.
7358 * @return bool if this string is a valid plugin name.
7360 function is_valid_plugin_name($name) {
7361 // This does not work for 'mod', bad luck, use any other type.
7362 return core_component::is_valid_plugin_name('tool', $name);
7366 * Get a list of all the plugins of a given type that define a certain API function
7367 * in a certain file. The plugin component names and function names are returned.
7369 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7370 * @param string $function the part of the name of the function after the
7371 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7372 * names like report_courselist_hook.
7373 * @param string $file the name of file within the plugin that defines the
7374 * function. Defaults to lib.php.
7375 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7376 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7378 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7379 global $CFG;
7381 // We don't include here as all plugin types files would be included.
7382 $plugins = get_plugins_with_function($function, $file, false);
7384 if (empty($plugins[$plugintype])) {
7385 return array();
7388 $allplugins = core_component::get_plugin_list($plugintype);
7390 // Reformat the array and include the files.
7391 $pluginfunctions = array();
7392 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7394 // Check that it has not been removed and the file is still available.
7395 if (!empty($allplugins[$pluginname])) {
7397 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7398 if (file_exists($filepath)) {
7399 include_once($filepath);
7400 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7405 return $pluginfunctions;
7409 * Get a list of all the plugins that define a certain API function in a certain file.
7411 * @param string $function the part of the name of the function after the
7412 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7413 * names like report_courselist_hook.
7414 * @param string $file the name of file within the plugin that defines the
7415 * function. Defaults to lib.php.
7416 * @param bool $include Whether to include the files that contain the functions or not.
7417 * @return array with [plugintype][plugin] = functionname
7419 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7420 global $CFG;
7422 $cache = \cache::make('core', 'plugin_functions');
7424 // Including both although I doubt that we will find two functions definitions with the same name.
7425 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7426 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7428 if ($pluginfunctions = $cache->get($key)) {
7430 // Checking that the files are still available.
7431 foreach ($pluginfunctions as $plugintype => $plugins) {
7433 $allplugins = \core_component::get_plugin_list($plugintype);
7434 foreach ($plugins as $plugin => $fullpath) {
7436 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7437 if (empty($allplugins[$plugin])) {
7438 unset($pluginfunctions[$plugintype][$plugin]);
7439 continue;
7442 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7443 if ($include && $fileexists) {
7444 // Include the files if it was requested.
7445 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7446 } else if (!$fileexists) {
7447 // If the file is not available any more it should not be returned.
7448 unset($pluginfunctions[$plugintype][$plugin]);
7452 return $pluginfunctions;
7455 $pluginfunctions = array();
7457 // To fill the cached. Also, everything should continue working with cache disabled.
7458 $plugintypes = \core_component::get_plugin_types();
7459 foreach ($plugintypes as $plugintype => $unused) {
7461 // We need to include files here.
7462 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7463 foreach ($pluginswithfile as $plugin => $notused) {
7465 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7467 $pluginfunction = false;
7468 if (function_exists($fullfunction)) {
7469 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7470 $pluginfunction = $fullfunction;
7472 } else if ($plugintype === 'mod') {
7473 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7474 $shortfunction = $plugin . '_' . $function;
7475 if (function_exists($shortfunction)) {
7476 $pluginfunction = $shortfunction;
7480 if ($pluginfunction) {
7481 if (empty($pluginfunctions[$plugintype])) {
7482 $pluginfunctions[$plugintype] = array();
7484 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7489 $cache->set($key, $pluginfunctions);
7491 return $pluginfunctions;
7496 * Lists plugin-like directories within specified directory
7498 * This function was originally used for standard Moodle plugins, please use
7499 * new core_component::get_plugin_list() now.
7501 * This function is used for general directory listing and backwards compatility.
7503 * @param string $directory relative directory from root
7504 * @param string $exclude dir name to exclude from the list (defaults to none)
7505 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7506 * @return array Sorted array of directory names found under the requested parameters
7508 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7509 global $CFG;
7511 $plugins = array();
7513 if (empty($basedir)) {
7514 $basedir = $CFG->dirroot .'/'. $directory;
7516 } else {
7517 $basedir = $basedir .'/'. $directory;
7520 if ($CFG->debugdeveloper and empty($exclude)) {
7521 // Make sure devs do not use this to list normal plugins,
7522 // this is intended for general directories that are not plugins!
7524 $subtypes = core_component::get_plugin_types();
7525 if (in_array($basedir, $subtypes)) {
7526 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7528 unset($subtypes);
7531 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7532 if (!$dirhandle = opendir($basedir)) {
7533 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7534 return array();
7536 while (false !== ($dir = readdir($dirhandle))) {
7537 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7538 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7539 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7540 continue;
7542 if (filetype($basedir .'/'. $dir) != 'dir') {
7543 continue;
7545 $plugins[] = $dir;
7547 closedir($dirhandle);
7549 if ($plugins) {
7550 asort($plugins);
7552 return $plugins;
7556 * Invoke plugin's callback functions
7558 * @param string $type plugin type e.g. 'mod'
7559 * @param string $name plugin name
7560 * @param string $feature feature name
7561 * @param string $action feature's action
7562 * @param array $params parameters of callback function, should be an array
7563 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7564 * @return mixed
7566 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7568 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7569 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7573 * Invoke component's callback functions
7575 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7576 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7577 * @param array $params parameters of callback function
7578 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7579 * @return mixed
7581 function component_callback($component, $function, array $params = array(), $default = null) {
7583 $functionname = component_callback_exists($component, $function);
7585 if ($functionname) {
7586 // Function exists, so just return function result.
7587 $ret = call_user_func_array($functionname, $params);
7588 if (is_null($ret)) {
7589 return $default;
7590 } else {
7591 return $ret;
7594 return $default;
7598 * Determine if a component callback exists and return the function name to call. Note that this
7599 * function will include the required library files so that the functioname returned can be
7600 * called directly.
7602 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7603 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7604 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7605 * @throws coding_exception if invalid component specfied
7607 function component_callback_exists($component, $function) {
7608 global $CFG; // This is needed for the inclusions.
7610 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7611 if (empty($cleancomponent)) {
7612 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7614 $component = $cleancomponent;
7616 list($type, $name) = core_component::normalize_component($component);
7617 $component = $type . '_' . $name;
7619 $oldfunction = $name.'_'.$function;
7620 $function = $component.'_'.$function;
7622 $dir = core_component::get_component_directory($component);
7623 if (empty($dir)) {
7624 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7627 // Load library and look for function.
7628 if (file_exists($dir.'/lib.php')) {
7629 require_once($dir.'/lib.php');
7632 if (!function_exists($function) and function_exists($oldfunction)) {
7633 if ($type !== 'mod' and $type !== 'core') {
7634 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7636 $function = $oldfunction;
7639 if (function_exists($function)) {
7640 return $function;
7642 return false;
7646 * Checks whether a plugin supports a specified feature.
7648 * @param string $type Plugin type e.g. 'mod'
7649 * @param string $name Plugin name e.g. 'forum'
7650 * @param string $feature Feature code (FEATURE_xx constant)
7651 * @param mixed $default default value if feature support unknown
7652 * @return mixed Feature result (false if not supported, null if feature is unknown,
7653 * otherwise usually true but may have other feature-specific value such as array)
7654 * @throws coding_exception
7656 function plugin_supports($type, $name, $feature, $default = null) {
7657 global $CFG;
7659 if ($type === 'mod' and $name === 'NEWMODULE') {
7660 // Somebody forgot to rename the module template.
7661 return false;
7664 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7665 if (empty($component)) {
7666 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7669 $function = null;
7671 if ($type === 'mod') {
7672 // We need this special case because we support subplugins in modules,
7673 // otherwise it would end up in infinite loop.
7674 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7675 include_once("$CFG->dirroot/mod/$name/lib.php");
7676 $function = $component.'_supports';
7677 if (!function_exists($function)) {
7678 // Legacy non-frankenstyle function name.
7679 $function = $name.'_supports';
7683 } else {
7684 if (!$path = core_component::get_plugin_directory($type, $name)) {
7685 // Non existent plugin type.
7686 return false;
7688 if (file_exists("$path/lib.php")) {
7689 include_once("$path/lib.php");
7690 $function = $component.'_supports';
7694 if ($function and function_exists($function)) {
7695 $supports = $function($feature);
7696 if (is_null($supports)) {
7697 // Plugin does not know - use default.
7698 return $default;
7699 } else {
7700 return $supports;
7704 // Plugin does not care, so use default.
7705 return $default;
7709 * Returns true if the current version of PHP is greater that the specified one.
7711 * @todo Check PHP version being required here is it too low?
7713 * @param string $version The version of php being tested.
7714 * @return bool
7716 function check_php_version($version='5.2.4') {
7717 return (version_compare(phpversion(), $version) >= 0);
7721 * Determine if moodle installation requires update.
7723 * Checks version numbers of main code and all plugins to see
7724 * if there are any mismatches.
7726 * @return bool
7728 function moodle_needs_upgrading() {
7729 global $CFG;
7731 if (empty($CFG->version)) {
7732 return true;
7735 // There is no need to purge plugininfo caches here because
7736 // these caches are not used during upgrade and they are purged after
7737 // every upgrade.
7739 if (empty($CFG->allversionshash)) {
7740 return true;
7743 $hash = core_component::get_all_versions_hash();
7745 return ($hash !== $CFG->allversionshash);
7749 * Returns the major version of this site
7751 * Moodle version numbers consist of three numbers separated by a dot, for
7752 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7753 * called major version. This function extracts the major version from either
7754 * $CFG->release (default) or eventually from the $release variable defined in
7755 * the main version.php.
7757 * @param bool $fromdisk should the version if source code files be used
7758 * @return string|false the major version like '2.3', false if could not be determined
7760 function moodle_major_version($fromdisk = false) {
7761 global $CFG;
7763 if ($fromdisk) {
7764 $release = null;
7765 require($CFG->dirroot.'/version.php');
7766 if (empty($release)) {
7767 return false;
7770 } else {
7771 if (empty($CFG->release)) {
7772 return false;
7774 $release = $CFG->release;
7777 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7778 return $matches[0];
7779 } else {
7780 return false;
7784 // MISCELLANEOUS.
7787 * Sets the system locale
7789 * @category string
7790 * @param string $locale Can be used to force a locale
7792 function moodle_setlocale($locale='') {
7793 global $CFG;
7795 static $currentlocale = ''; // Last locale caching.
7797 $oldlocale = $currentlocale;
7799 // Fetch the correct locale based on ostype.
7800 if ($CFG->ostype == 'WINDOWS') {
7801 $stringtofetch = 'localewin';
7802 } else {
7803 $stringtofetch = 'locale';
7806 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7807 if (!empty($locale)) {
7808 $currentlocale = $locale;
7809 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7810 $currentlocale = $CFG->locale;
7811 } else {
7812 $currentlocale = get_string($stringtofetch, 'langconfig');
7815 // Do nothing if locale already set up.
7816 if ($oldlocale == $currentlocale) {
7817 return;
7820 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7821 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7822 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7824 // Get current values.
7825 $monetary= setlocale (LC_MONETARY, 0);
7826 $numeric = setlocale (LC_NUMERIC, 0);
7827 $ctype = setlocale (LC_CTYPE, 0);
7828 if ($CFG->ostype != 'WINDOWS') {
7829 $messages= setlocale (LC_MESSAGES, 0);
7831 // Set locale to all.
7832 $result = setlocale (LC_ALL, $currentlocale);
7833 // If setting of locale fails try the other utf8 or utf-8 variant,
7834 // some operating systems support both (Debian), others just one (OSX).
7835 if ($result === false) {
7836 if (stripos($currentlocale, '.UTF-8') !== false) {
7837 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7838 setlocale (LC_ALL, $newlocale);
7839 } else if (stripos($currentlocale, '.UTF8') !== false) {
7840 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7841 setlocale (LC_ALL, $newlocale);
7844 // Set old values.
7845 setlocale (LC_MONETARY, $monetary);
7846 setlocale (LC_NUMERIC, $numeric);
7847 if ($CFG->ostype != 'WINDOWS') {
7848 setlocale (LC_MESSAGES, $messages);
7850 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7851 // To workaround a well-known PHP problem with Turkish letter Ii.
7852 setlocale (LC_CTYPE, $ctype);
7857 * Count words in a string.
7859 * Words are defined as things between whitespace.
7861 * @category string
7862 * @param string $string The text to be searched for words.
7863 * @return int The count of words in the specified string
7865 function count_words($string) {
7866 $string = strip_tags($string);
7867 // Decode HTML entities.
7868 $string = html_entity_decode($string);
7869 // Replace underscores (which are classed as word characters) with spaces.
7870 $string = preg_replace('/_/u', ' ', $string);
7871 // Remove any characters that shouldn't be treated as word boundaries.
7872 $string = preg_replace('/[\'"’-]/u', '', $string);
7873 // Remove dots and commas from within numbers only.
7874 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7876 return count(preg_split('/\w\b/u', $string)) - 1;
7880 * Count letters in a string.
7882 * Letters are defined as chars not in tags and different from whitespace.
7884 * @category string
7885 * @param string $string The text to be searched for letters.
7886 * @return int The count of letters in the specified text.
7888 function count_letters($string) {
7889 $string = strip_tags($string); // Tags are out now.
7890 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7892 return core_text::strlen($string);
7896 * Generate and return a random string of the specified length.
7898 * @param int $length The length of the string to be created.
7899 * @return string
7901 function random_string($length=15) {
7902 $randombytes = random_bytes_emulate($length);
7903 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7904 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7905 $pool .= '0123456789';
7906 $poollen = strlen($pool);
7907 $string = '';
7908 for ($i = 0; $i < $length; $i++) {
7909 $rand = ord($randombytes[$i]);
7910 $string .= substr($pool, ($rand%($poollen)), 1);
7912 return $string;
7916 * Generate a complex random string (useful for md5 salts)
7918 * This function is based on the above {@link random_string()} however it uses a
7919 * larger pool of characters and generates a string between 24 and 32 characters
7921 * @param int $length Optional if set generates a string to exactly this length
7922 * @return string
7924 function complex_random_string($length=null) {
7925 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7926 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7927 $poollen = strlen($pool);
7928 if ($length===null) {
7929 $length = floor(rand(24, 32));
7931 $randombytes = random_bytes_emulate($length);
7932 $string = '';
7933 for ($i = 0; $i < $length; $i++) {
7934 $rand = ord($randombytes[$i]);
7935 $string .= $pool[($rand%$poollen)];
7937 return $string;
7941 * Try to generates cryptographically secure pseudo-random bytes.
7943 * Note this is achieved by fallbacking between:
7944 * - PHP 7 random_bytes().
7945 * - OpenSSL openssl_random_pseudo_bytes().
7946 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
7948 * @param int $length requested length in bytes
7949 * @return string binary data
7951 function random_bytes_emulate($length) {
7952 global $CFG;
7953 if ($length <= 0) {
7954 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
7955 return '';
7957 if (function_exists('random_bytes')) {
7958 // Use PHP 7 goodness.
7959 $hash = @random_bytes($length);
7960 if ($hash !== false) {
7961 return $hash;
7964 if (function_exists('openssl_random_pseudo_bytes')) {
7965 // If you have the openssl extension enabled.
7966 $hash = openssl_random_pseudo_bytes($length);
7967 if ($hash !== false) {
7968 return $hash;
7972 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
7973 $staticdata = serialize($CFG) . serialize($_SERVER);
7974 $hash = '';
7975 do {
7976 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
7977 } while (strlen($hash) < $length);
7979 return substr($hash, 0, $length);
7983 * Given some text (which may contain HTML) and an ideal length,
7984 * this function truncates the text neatly on a word boundary if possible
7986 * @category string
7987 * @param string $text text to be shortened
7988 * @param int $ideal ideal string length
7989 * @param boolean $exact if false, $text will not be cut mid-word
7990 * @param string $ending The string to append if the passed string is truncated
7991 * @return string $truncate shortened string
7993 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7994 // If the plain text is shorter than the maximum length, return the whole text.
7995 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7996 return $text;
7999 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8000 // and only tag in its 'line'.
8001 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8003 $totallength = core_text::strlen($ending);
8004 $truncate = '';
8006 // This array stores information about open and close tags and their position
8007 // in the truncated string. Each item in the array is an object with fields
8008 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8009 // (byte position in truncated text).
8010 $tagdetails = array();
8012 foreach ($lines as $linematchings) {
8013 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8014 if (!empty($linematchings[1])) {
8015 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8016 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8017 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8018 // Record closing tag.
8019 $tagdetails[] = (object) array(
8020 'open' => false,
8021 'tag' => core_text::strtolower($tagmatchings[1]),
8022 'pos' => core_text::strlen($truncate),
8025 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8026 // Record opening tag.
8027 $tagdetails[] = (object) array(
8028 'open' => true,
8029 'tag' => core_text::strtolower($tagmatchings[1]),
8030 'pos' => core_text::strlen($truncate),
8032 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8033 $tagdetails[] = (object) array(
8034 'open' => true,
8035 'tag' => core_text::strtolower('if'),
8036 'pos' => core_text::strlen($truncate),
8038 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8039 $tagdetails[] = (object) array(
8040 'open' => false,
8041 'tag' => core_text::strtolower('if'),
8042 'pos' => core_text::strlen($truncate),
8046 // Add html-tag to $truncate'd text.
8047 $truncate .= $linematchings[1];
8050 // Calculate the length of the plain text part of the line; handle entities as one character.
8051 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8052 if ($totallength + $contentlength > $ideal) {
8053 // The number of characters which are left.
8054 $left = $ideal - $totallength;
8055 $entitieslength = 0;
8056 // Search for html entities.
8057 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)) {
8058 // Calculate the real length of all entities in the legal range.
8059 foreach ($entities[0] as $entity) {
8060 if ($entity[1]+1-$entitieslength <= $left) {
8061 $left--;
8062 $entitieslength += core_text::strlen($entity[0]);
8063 } else {
8064 // No more characters left.
8065 break;
8069 $breakpos = $left + $entitieslength;
8071 // If the words shouldn't be cut in the middle...
8072 if (!$exact) {
8073 // Search the last occurence of a space.
8074 for (; $breakpos > 0; $breakpos--) {
8075 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8076 if ($char === '.' or $char === ' ') {
8077 $breakpos += 1;
8078 break;
8079 } else if (strlen($char) > 2) {
8080 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8081 $breakpos += 1;
8082 break;
8087 if ($breakpos == 0) {
8088 // This deals with the test_shorten_text_no_spaces case.
8089 $breakpos = $left + $entitieslength;
8090 } else if ($breakpos > $left + $entitieslength) {
8091 // This deals with the previous for loop breaking on the first char.
8092 $breakpos = $left + $entitieslength;
8095 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8096 // Maximum length is reached, so get off the loop.
8097 break;
8098 } else {
8099 $truncate .= $linematchings[2];
8100 $totallength += $contentlength;
8103 // If the maximum length is reached, get off the loop.
8104 if ($totallength >= $ideal) {
8105 break;
8109 // Add the defined ending to the text.
8110 $truncate .= $ending;
8112 // Now calculate the list of open html tags based on the truncate position.
8113 $opentags = array();
8114 foreach ($tagdetails as $taginfo) {
8115 if ($taginfo->open) {
8116 // Add tag to the beginning of $opentags list.
8117 array_unshift($opentags, $taginfo->tag);
8118 } else {
8119 // Can have multiple exact same open tags, close the last one.
8120 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8121 if ($pos !== false) {
8122 unset($opentags[$pos]);
8127 // Close all unclosed html-tags.
8128 foreach ($opentags as $tag) {
8129 if ($tag === 'if') {
8130 $truncate .= '<!--<![endif]-->';
8131 } else {
8132 $truncate .= '</' . $tag . '>';
8136 return $truncate;
8141 * Given dates in seconds, how many weeks is the date from startdate
8142 * The first week is 1, the second 2 etc ...
8144 * @param int $startdate Timestamp for the start date
8145 * @param int $thedate Timestamp for the end date
8146 * @return string
8148 function getweek ($startdate, $thedate) {
8149 if ($thedate < $startdate) {
8150 return 0;
8153 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8157 * Returns a randomly generated password of length $maxlen. inspired by
8159 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8160 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8162 * @param int $maxlen The maximum size of the password being generated.
8163 * @return string
8165 function generate_password($maxlen=10) {
8166 global $CFG;
8168 if (empty($CFG->passwordpolicy)) {
8169 $fillers = PASSWORD_DIGITS;
8170 $wordlist = file($CFG->wordlist);
8171 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8172 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8173 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8174 $password = $word1 . $filler1 . $word2;
8175 } else {
8176 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8177 $digits = $CFG->minpassworddigits;
8178 $lower = $CFG->minpasswordlower;
8179 $upper = $CFG->minpasswordupper;
8180 $nonalphanum = $CFG->minpasswordnonalphanum;
8181 $total = $lower + $upper + $digits + $nonalphanum;
8182 // Var minlength should be the greater one of the two ( $minlen and $total ).
8183 $minlen = $minlen < $total ? $total : $minlen;
8184 // Var maxlen can never be smaller than minlen.
8185 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8186 $additional = $maxlen - $total;
8188 // Make sure we have enough characters to fulfill
8189 // complexity requirements.
8190 $passworddigits = PASSWORD_DIGITS;
8191 while ($digits > strlen($passworddigits)) {
8192 $passworddigits .= PASSWORD_DIGITS;
8194 $passwordlower = PASSWORD_LOWER;
8195 while ($lower > strlen($passwordlower)) {
8196 $passwordlower .= PASSWORD_LOWER;
8198 $passwordupper = PASSWORD_UPPER;
8199 while ($upper > strlen($passwordupper)) {
8200 $passwordupper .= PASSWORD_UPPER;
8202 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8203 while ($nonalphanum > strlen($passwordnonalphanum)) {
8204 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8207 // Now mix and shuffle it all.
8208 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8209 substr(str_shuffle ($passwordupper), 0, $upper) .
8210 substr(str_shuffle ($passworddigits), 0, $digits) .
8211 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8212 substr(str_shuffle ($passwordlower .
8213 $passwordupper .
8214 $passworddigits .
8215 $passwordnonalphanum), 0 , $additional));
8218 return substr ($password, 0, $maxlen);
8222 * Given a float, prints it nicely.
8223 * Localized floats must not be used in calculations!
8225 * The stripzeros feature is intended for making numbers look nicer in small
8226 * areas where it is not necessary to indicate the degree of accuracy by showing
8227 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8228 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8230 * @param float $float The float to print
8231 * @param int $decimalpoints The number of decimal places to print.
8232 * @param bool $localized use localized decimal separator
8233 * @param bool $stripzeros If true, removes final zeros after decimal point
8234 * @return string locale float
8236 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8237 if (is_null($float)) {
8238 return '';
8240 if ($localized) {
8241 $separator = get_string('decsep', 'langconfig');
8242 } else {
8243 $separator = '.';
8245 $result = number_format($float, $decimalpoints, $separator, '');
8246 if ($stripzeros) {
8247 // Remove zeros and final dot if not needed.
8248 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8250 return $result;
8254 * Converts locale specific floating point/comma number back to standard PHP float value
8255 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8257 * @param string $localefloat locale aware float representation
8258 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8259 * @return mixed float|bool - false or the parsed float.
8261 function unformat_float($localefloat, $strict = false) {
8262 $localefloat = trim($localefloat);
8264 if ($localefloat == '') {
8265 return null;
8268 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8269 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8271 if ($strict && !is_numeric($localefloat)) {
8272 return false;
8275 return (float)$localefloat;
8279 * Given a simple array, this shuffles it up just like shuffle()
8280 * Unlike PHP's shuffle() this function works on any machine.
8282 * @param array $array The array to be rearranged
8283 * @return array
8285 function swapshuffle($array) {
8287 $last = count($array) - 1;
8288 for ($i = 0; $i <= $last; $i++) {
8289 $from = rand(0, $last);
8290 $curr = $array[$i];
8291 $array[$i] = $array[$from];
8292 $array[$from] = $curr;
8294 return $array;
8298 * Like {@link swapshuffle()}, but works on associative arrays
8300 * @param array $array The associative array to be rearranged
8301 * @return array
8303 function swapshuffle_assoc($array) {
8305 $newarray = array();
8306 $newkeys = swapshuffle(array_keys($array));
8308 foreach ($newkeys as $newkey) {
8309 $newarray[$newkey] = $array[$newkey];
8311 return $newarray;
8315 * Given an arbitrary array, and a number of draws,
8316 * this function returns an array with that amount
8317 * of items. The indexes are retained.
8319 * @todo Finish documenting this function
8321 * @param array $array
8322 * @param int $draws
8323 * @return array
8325 function draw_rand_array($array, $draws) {
8327 $return = array();
8329 $last = count($array);
8331 if ($draws > $last) {
8332 $draws = $last;
8335 while ($draws > 0) {
8336 $last--;
8338 $keys = array_keys($array);
8339 $rand = rand(0, $last);
8341 $return[$keys[$rand]] = $array[$keys[$rand]];
8342 unset($array[$keys[$rand]]);
8344 $draws--;
8347 return $return;
8351 * Calculate the difference between two microtimes
8353 * @param string $a The first Microtime
8354 * @param string $b The second Microtime
8355 * @return string
8357 function microtime_diff($a, $b) {
8358 list($adec, $asec) = explode(' ', $a);
8359 list($bdec, $bsec) = explode(' ', $b);
8360 return $bsec - $asec + $bdec - $adec;
8364 * Given a list (eg a,b,c,d,e) this function returns
8365 * an array of 1->a, 2->b, 3->c etc
8367 * @param string $list The string to explode into array bits
8368 * @param string $separator The separator used within the list string
8369 * @return array The now assembled array
8371 function make_menu_from_list($list, $separator=',') {
8373 $array = array_reverse(explode($separator, $list), true);
8374 foreach ($array as $key => $item) {
8375 $outarray[$key+1] = trim($item);
8377 return $outarray;
8381 * Creates an array that represents all the current grades that
8382 * can be chosen using the given grading type.
8384 * Negative numbers
8385 * are scales, zero is no grade, and positive numbers are maximum
8386 * grades.
8388 * @todo Finish documenting this function or better deprecated this completely!
8390 * @param int $gradingtype
8391 * @return array
8393 function make_grades_menu($gradingtype) {
8394 global $DB;
8396 $grades = array();
8397 if ($gradingtype < 0) {
8398 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8399 return make_menu_from_list($scale->scale);
8401 } else if ($gradingtype > 0) {
8402 for ($i=$gradingtype; $i>=0; $i--) {
8403 $grades[$i] = $i .' / '. $gradingtype;
8405 return $grades;
8407 return $grades;
8411 * make_unique_id_code
8413 * @todo Finish documenting this function
8415 * @uses $_SERVER
8416 * @param string $extra Extra string to append to the end of the code
8417 * @return string
8419 function make_unique_id_code($extra = '') {
8421 $hostname = 'unknownhost';
8422 if (!empty($_SERVER['HTTP_HOST'])) {
8423 $hostname = $_SERVER['HTTP_HOST'];
8424 } else if (!empty($_ENV['HTTP_HOST'])) {
8425 $hostname = $_ENV['HTTP_HOST'];
8426 } else if (!empty($_SERVER['SERVER_NAME'])) {
8427 $hostname = $_SERVER['SERVER_NAME'];
8428 } else if (!empty($_ENV['SERVER_NAME'])) {
8429 $hostname = $_ENV['SERVER_NAME'];
8432 $date = gmdate("ymdHis");
8434 $random = random_string(6);
8436 if ($extra) {
8437 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8438 } else {
8439 return $hostname .'+'. $date .'+'. $random;
8445 * Function to check the passed address is within the passed subnet
8447 * The parameter is a comma separated string of subnet definitions.
8448 * Subnet strings can be in one of three formats:
8449 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8450 * 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)
8451 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8452 * Code for type 1 modified from user posted comments by mediator at
8453 * {@link http://au.php.net/manual/en/function.ip2long.php}
8455 * @param string $addr The address you are checking
8456 * @param string $subnetstr The string of subnet addresses
8457 * @return bool
8459 function address_in_subnet($addr, $subnetstr) {
8461 if ($addr == '0.0.0.0') {
8462 return false;
8464 $subnets = explode(',', $subnetstr);
8465 $found = false;
8466 $addr = trim($addr);
8467 $addr = cleanremoteaddr($addr, false); // Normalise.
8468 if ($addr === null) {
8469 return false;
8471 $addrparts = explode(':', $addr);
8473 $ipv6 = strpos($addr, ':');
8475 foreach ($subnets as $subnet) {
8476 $subnet = trim($subnet);
8477 if ($subnet === '') {
8478 continue;
8481 if (strpos($subnet, '/') !== false) {
8482 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8483 list($ip, $mask) = explode('/', $subnet);
8484 $mask = trim($mask);
8485 if (!is_number($mask)) {
8486 continue; // Incorect mask number, eh?
8488 $ip = cleanremoteaddr($ip, false); // Normalise.
8489 if ($ip === null) {
8490 continue;
8492 if (strpos($ip, ':') !== false) {
8493 // IPv6.
8494 if (!$ipv6) {
8495 continue;
8497 if ($mask > 128 or $mask < 0) {
8498 continue; // Nonsense.
8500 if ($mask == 0) {
8501 return true; // Any address.
8503 if ($mask == 128) {
8504 if ($ip === $addr) {
8505 return true;
8507 continue;
8509 $ipparts = explode(':', $ip);
8510 $modulo = $mask % 16;
8511 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8512 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8513 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8514 if ($modulo == 0) {
8515 return true;
8517 $pos = ($mask-$modulo)/16;
8518 $ipnet = hexdec($ipparts[$pos]);
8519 $addrnet = hexdec($addrparts[$pos]);
8520 $mask = 0xffff << (16 - $modulo);
8521 if (($addrnet & $mask) == ($ipnet & $mask)) {
8522 return true;
8526 } else {
8527 // IPv4.
8528 if ($ipv6) {
8529 continue;
8531 if ($mask > 32 or $mask < 0) {
8532 continue; // Nonsense.
8534 if ($mask == 0) {
8535 return true;
8537 if ($mask == 32) {
8538 if ($ip === $addr) {
8539 return true;
8541 continue;
8543 $mask = 0xffffffff << (32 - $mask);
8544 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8545 return true;
8549 } else if (strpos($subnet, '-') !== false) {
8550 // 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.
8551 $parts = explode('-', $subnet);
8552 if (count($parts) != 2) {
8553 continue;
8556 if (strpos($subnet, ':') !== false) {
8557 // IPv6.
8558 if (!$ipv6) {
8559 continue;
8561 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8562 if ($ipstart === null) {
8563 continue;
8565 $ipparts = explode(':', $ipstart);
8566 $start = hexdec(array_pop($ipparts));
8567 $ipparts[] = trim($parts[1]);
8568 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8569 if ($ipend === null) {
8570 continue;
8572 $ipparts[7] = '';
8573 $ipnet = implode(':', $ipparts);
8574 if (strpos($addr, $ipnet) !== 0) {
8575 continue;
8577 $ipparts = explode(':', $ipend);
8578 $end = hexdec($ipparts[7]);
8580 $addrend = hexdec($addrparts[7]);
8582 if (($addrend >= $start) and ($addrend <= $end)) {
8583 return true;
8586 } else {
8587 // IPv4.
8588 if ($ipv6) {
8589 continue;
8591 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8592 if ($ipstart === null) {
8593 continue;
8595 $ipparts = explode('.', $ipstart);
8596 $ipparts[3] = trim($parts[1]);
8597 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8598 if ($ipend === null) {
8599 continue;
8602 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8603 return true;
8607 } else {
8608 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8609 if (strpos($subnet, ':') !== false) {
8610 // IPv6.
8611 if (!$ipv6) {
8612 continue;
8614 $parts = explode(':', $subnet);
8615 $count = count($parts);
8616 if ($parts[$count-1] === '') {
8617 unset($parts[$count-1]); // Trim trailing :'s.
8618 $count--;
8619 $subnet = implode('.', $parts);
8621 $isip = cleanremoteaddr($subnet, false); // Normalise.
8622 if ($isip !== null) {
8623 if ($isip === $addr) {
8624 return true;
8626 continue;
8627 } else if ($count > 8) {
8628 continue;
8630 $zeros = array_fill(0, 8-$count, '0');
8631 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8632 if (address_in_subnet($addr, $subnet)) {
8633 return true;
8636 } else {
8637 // IPv4.
8638 if ($ipv6) {
8639 continue;
8641 $parts = explode('.', $subnet);
8642 $count = count($parts);
8643 if ($parts[$count-1] === '') {
8644 unset($parts[$count-1]); // Trim trailing .
8645 $count--;
8646 $subnet = implode('.', $parts);
8648 if ($count == 4) {
8649 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8650 if ($subnet === $addr) {
8651 return true;
8653 continue;
8654 } else if ($count > 4) {
8655 continue;
8657 $zeros = array_fill(0, 4-$count, '0');
8658 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8659 if (address_in_subnet($addr, $subnet)) {
8660 return true;
8666 return false;
8670 * For outputting debugging info
8672 * @param string $string The string to write
8673 * @param string $eol The end of line char(s) to use
8674 * @param string $sleep Period to make the application sleep
8675 * This ensures any messages have time to display before redirect
8677 function mtrace($string, $eol="\n", $sleep=0) {
8679 if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
8680 fwrite(STDOUT, $string.$eol);
8681 } else {
8682 echo $string . $eol;
8685 flush();
8687 // Delay to keep message on user's screen in case of subsequent redirect.
8688 if ($sleep) {
8689 sleep($sleep);
8694 * Replace 1 or more slashes or backslashes to 1 slash
8696 * @param string $path The path to strip
8697 * @return string the path with double slashes removed
8699 function cleardoubleslashes ($path) {
8700 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8704 * Is current ip in give list?
8706 * @param string $list
8707 * @return bool
8709 function remoteip_in_list($list) {
8710 $inlist = false;
8711 $clientip = getremoteaddr(null);
8713 if (!$clientip) {
8714 // Ensure access on cli.
8715 return true;
8718 $list = explode("\n", $list);
8719 foreach ($list as $subnet) {
8720 $subnet = trim($subnet);
8721 if (address_in_subnet($clientip, $subnet)) {
8722 $inlist = true;
8723 break;
8726 return $inlist;
8730 * Returns most reliable client address
8732 * @param string $default If an address can't be determined, then return this
8733 * @return string The remote IP address
8735 function getremoteaddr($default='0.0.0.0') {
8736 global $CFG;
8738 if (empty($CFG->getremoteaddrconf)) {
8739 // This will happen, for example, before just after the upgrade, as the
8740 // user is redirected to the admin screen.
8741 $variablestoskip = 0;
8742 } else {
8743 $variablestoskip = $CFG->getremoteaddrconf;
8745 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8746 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8747 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8748 return $address ? $address : $default;
8751 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8752 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8753 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8754 $address = $forwardedaddresses[0];
8756 if (substr_count($address, ":") > 1) {
8757 // Remove port and brackets from IPv6.
8758 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8759 $address = $matches[1];
8761 } else {
8762 // Remove port from IPv4.
8763 if (substr_count($address, ":") == 1) {
8764 $parts = explode(":", $address);
8765 $address = $parts[0];
8769 $address = cleanremoteaddr($address);
8770 return $address ? $address : $default;
8773 if (!empty($_SERVER['REMOTE_ADDR'])) {
8774 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8775 return $address ? $address : $default;
8776 } else {
8777 return $default;
8782 * Cleans an ip address. Internal addresses are now allowed.
8783 * (Originally local addresses were not allowed.)
8785 * @param string $addr IPv4 or IPv6 address
8786 * @param bool $compress use IPv6 address compression
8787 * @return string normalised ip address string, null if error
8789 function cleanremoteaddr($addr, $compress=false) {
8790 $addr = trim($addr);
8792 if (strpos($addr, ':') !== false) {
8793 // Can be only IPv6.
8794 $parts = explode(':', $addr);
8795 $count = count($parts);
8797 if (strpos($parts[$count-1], '.') !== false) {
8798 // Legacy ipv4 notation.
8799 $last = array_pop($parts);
8800 $ipv4 = cleanremoteaddr($last, true);
8801 if ($ipv4 === null) {
8802 return null;
8804 $bits = explode('.', $ipv4);
8805 $parts[] = dechex($bits[0]).dechex($bits[1]);
8806 $parts[] = dechex($bits[2]).dechex($bits[3]);
8807 $count = count($parts);
8808 $addr = implode(':', $parts);
8811 if ($count < 3 or $count > 8) {
8812 return null; // Severly malformed.
8815 if ($count != 8) {
8816 if (strpos($addr, '::') === false) {
8817 return null; // Malformed.
8819 // Uncompress.
8820 $insertat = array_search('', $parts, true);
8821 $missing = array_fill(0, 1 + 8 - $count, '0');
8822 array_splice($parts, $insertat, 1, $missing);
8823 foreach ($parts as $key => $part) {
8824 if ($part === '') {
8825 $parts[$key] = '0';
8830 $adr = implode(':', $parts);
8831 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8832 return null; // Incorrect format - sorry.
8835 // Normalise 0s and case.
8836 $parts = array_map('hexdec', $parts);
8837 $parts = array_map('dechex', $parts);
8839 $result = implode(':', $parts);
8841 if (!$compress) {
8842 return $result;
8845 if ($result === '0:0:0:0:0:0:0:0') {
8846 return '::'; // All addresses.
8849 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8850 if ($compressed !== $result) {
8851 return $compressed;
8854 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8855 if ($compressed !== $result) {
8856 return $compressed;
8859 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8860 if ($compressed !== $result) {
8861 return $compressed;
8864 return $result;
8867 // First get all things that look like IPv4 addresses.
8868 $parts = array();
8869 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8870 return null;
8872 unset($parts[0]);
8874 foreach ($parts as $key => $match) {
8875 if ($match > 255) {
8876 return null;
8878 $parts[$key] = (int)$match; // Normalise 0s.
8881 return implode('.', $parts);
8886 * Is IP address a public address?
8888 * @param string $ip The ip to check
8889 * @return bool true if the ip is public
8891 function ip_is_public($ip) {
8892 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
8896 * This function will make a complete copy of anything it's given,
8897 * regardless of whether it's an object or not.
8899 * @param mixed $thing Something you want cloned
8900 * @return mixed What ever it is you passed it
8902 function fullclone($thing) {
8903 return unserialize(serialize($thing));
8907 * Used to make sure that $min <= $value <= $max
8909 * Make sure that value is between min, and max
8911 * @param int $min The minimum value
8912 * @param int $value The value to check
8913 * @param int $max The maximum value
8914 * @return int
8916 function bounded_number($min, $value, $max) {
8917 if ($value < $min) {
8918 return $min;
8920 if ($value > $max) {
8921 return $max;
8923 return $value;
8927 * Check if there is a nested array within the passed array
8929 * @param array $array
8930 * @return bool true if there is a nested array false otherwise
8932 function array_is_nested($array) {
8933 foreach ($array as $value) {
8934 if (is_array($value)) {
8935 return true;
8938 return false;
8942 * get_performance_info() pairs up with init_performance_info()
8943 * loaded in setup.php. Returns an array with 'html' and 'txt'
8944 * values ready for use, and each of the individual stats provided
8945 * separately as well.
8947 * @return array
8949 function get_performance_info() {
8950 global $CFG, $PERF, $DB, $PAGE;
8952 $info = array();
8953 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8955 $info['html'] = '';
8956 if (!empty($CFG->themedesignermode)) {
8957 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
8958 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
8960 $info['html'] .= '<ul class="list-unstyled m-l-1">'; // Holds userfriendly HTML representation.
8962 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
8964 $info['html'] .= '<li class="timeused">'.$info['realtime'].' secs</li> ';
8965 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8967 if (function_exists('memory_get_usage')) {
8968 $info['memory_total'] = memory_get_usage();
8969 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
8970 $info['html'] .= '<li class="memoryused">RAM: '.display_size($info['memory_total']).'</li> ';
8971 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8972 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8975 if (function_exists('memory_get_peak_usage')) {
8976 $info['memory_peak'] = memory_get_peak_usage();
8977 $info['html'] .= '<li class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</li> ';
8978 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8981 $inc = get_included_files();
8982 $info['includecount'] = count($inc);
8983 $info['html'] .= '<li class="included">Included '.$info['includecount'].' files</li> ';
8984 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8986 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
8987 // We can not track more performance before installation or before PAGE init, sorry.
8988 return $info;
8991 $filtermanager = filter_manager::instance();
8992 if (method_exists($filtermanager, 'get_performance_summary')) {
8993 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8994 $info = array_merge($filterinfo, $info);
8995 foreach ($filterinfo as $key => $value) {
8996 $info['html'] .= "<li class='$key'>$nicenames[$key]: $value </li> ";
8997 $info['txt'] .= "$key: $value ";
9001 $stringmanager = get_string_manager();
9002 if (method_exists($stringmanager, 'get_performance_summary')) {
9003 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9004 $info = array_merge($filterinfo, $info);
9005 foreach ($filterinfo as $key => $value) {
9006 $info['html'] .= "<li class='$key'>$nicenames[$key]: $value </li> ";
9007 $info['txt'] .= "$key: $value ";
9011 if (!empty($PERF->logwrites)) {
9012 $info['logwrites'] = $PERF->logwrites;
9013 $info['html'] .= '<li class="logwrites">Log DB writes '.$info['logwrites'].'</li> ';
9014 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9017 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9018 $info['html'] .= '<li class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</li> ';
9019 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9021 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9022 $info['html'] .= '<li class="dbtime">DB queries time: '.$info['dbtime'].' secs</li> ';
9023 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9025 if (function_exists('posix_times')) {
9026 $ptimes = posix_times();
9027 if (is_array($ptimes)) {
9028 foreach ($ptimes as $key => $val) {
9029 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9031 $info['html'] .= "<li class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9032 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9036 // Grab the load average for the last minute.
9037 // /proc will only work under some linux configurations
9038 // while uptime is there under MacOSX/Darwin and other unices.
9039 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9040 list($serverload) = explode(' ', $loadavg[0]);
9041 unset($loadavg);
9042 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9043 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9044 $serverload = $matches[1];
9045 } else {
9046 trigger_error('Could not parse uptime output!');
9049 if (!empty($serverload)) {
9050 $info['serverload'] = $serverload;
9051 $info['html'] .= '<li class="serverload">Load average: '.$info['serverload'].'</li> ';
9052 $info['txt'] .= "serverload: {$info['serverload']} ";
9055 // Display size of session if session started.
9056 if ($si = \core\session\manager::get_performance_info()) {
9057 $info['sessionsize'] = $si['size'];
9058 $info['html'] .= $si['html'];
9059 $info['txt'] .= $si['txt'];
9062 if ($stats = cache_helper::get_stats()) {
9063 $html = '<ul class="cachesused list-unstyled m-l-1">';
9064 $html .= '<li class="cache-stats-heading">Caches used (hits/misses/sets)</li>';
9065 $text = 'Caches used (hits/misses/sets): ';
9066 $hits = 0;
9067 $misses = 0;
9068 $sets = 0;
9069 foreach ($stats as $definition => $details) {
9070 switch ($details['mode']) {
9071 case cache_store::MODE_APPLICATION:
9072 $modeclass = 'application';
9073 $mode = ' <span title="application cache">[a]</span>';
9074 break;
9075 case cache_store::MODE_SESSION:
9076 $modeclass = 'session';
9077 $mode = ' <span title="session cache">[s]</span>';
9078 break;
9079 case cache_store::MODE_REQUEST:
9080 $modeclass = 'request';
9081 $mode = ' <span title="request cache">[r]</span>';
9082 break;
9084 $html .= '<ul class="cache-definition-stats list-unstyled m-l-1 cache-mode-'.$modeclass.'">';
9085 $html .= '<li class="cache-definition-stats-heading p-t-1">'.$definition.$mode.'</li>';
9086 $text .= "$definition {";
9087 foreach ($details['stores'] as $store => $data) {
9088 $hits += $data['hits'];
9089 $misses += $data['misses'];
9090 $sets += $data['sets'];
9091 if ($data['hits'] == 0 and $data['misses'] > 0) {
9092 $cachestoreclass = 'nohits text-danger';
9093 } else if ($data['hits'] < $data['misses']) {
9094 $cachestoreclass = 'lowhits text-warning';
9095 } else {
9096 $cachestoreclass = 'hihits text-success';
9098 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9099 $html .= "<li class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</li>";
9101 $html .= '</ul>';
9102 $text .= '} ';
9104 $html .= '</ul> ';
9105 $html .= "<div class='cache-total-stats row'>Total: $hits / $misses / $sets</div>";
9106 $info['cachesused'] = "$hits / $misses / $sets";
9107 $info['html'] .= $html;
9108 $info['txt'] .= $text.'. ';
9109 } else {
9110 $info['cachesused'] = '0 / 0 / 0';
9111 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9112 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9115 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
9116 return $info;
9120 * Delete directory or only its content
9122 * @param string $dir directory path
9123 * @param bool $contentonly
9124 * @return bool success, true also if dir does not exist
9126 function remove_dir($dir, $contentonly=false) {
9127 if (!file_exists($dir)) {
9128 // Nothing to do.
9129 return true;
9131 if (!$handle = opendir($dir)) {
9132 return false;
9134 $result = true;
9135 while (false!==($item = readdir($handle))) {
9136 if ($item != '.' && $item != '..') {
9137 if (is_dir($dir.'/'.$item)) {
9138 $result = remove_dir($dir.'/'.$item) && $result;
9139 } else {
9140 $result = unlink($dir.'/'.$item) && $result;
9144 closedir($handle);
9145 if ($contentonly) {
9146 clearstatcache(); // Make sure file stat cache is properly invalidated.
9147 return $result;
9149 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9150 clearstatcache(); // Make sure file stat cache is properly invalidated.
9151 return $result;
9155 * Detect if an object or a class contains a given property
9156 * will take an actual object or the name of a class
9158 * @param mix $obj Name of class or real object to test
9159 * @param string $property name of property to find
9160 * @return bool true if property exists
9162 function object_property_exists( $obj, $property ) {
9163 if (is_string( $obj )) {
9164 $properties = get_class_vars( $obj );
9165 } else {
9166 $properties = get_object_vars( $obj );
9168 return array_key_exists( $property, $properties );
9172 * Converts an object into an associative array
9174 * This function converts an object into an associative array by iterating
9175 * over its public properties. Because this function uses the foreach
9176 * construct, Iterators are respected. It works recursively on arrays of objects.
9177 * Arrays and simple values are returned as is.
9179 * If class has magic properties, it can implement IteratorAggregate
9180 * and return all available properties in getIterator()
9182 * @param mixed $var
9183 * @return array
9185 function convert_to_array($var) {
9186 $result = array();
9188 // Loop over elements/properties.
9189 foreach ($var as $key => $value) {
9190 // Recursively convert objects.
9191 if (is_object($value) || is_array($value)) {
9192 $result[$key] = convert_to_array($value);
9193 } else {
9194 // Simple values are untouched.
9195 $result[$key] = $value;
9198 return $result;
9202 * Detect a custom script replacement in the data directory that will
9203 * replace an existing moodle script
9205 * @return string|bool full path name if a custom script exists, false if no custom script exists
9207 function custom_script_path() {
9208 global $CFG, $SCRIPT;
9210 if ($SCRIPT === null) {
9211 // Probably some weird external script.
9212 return false;
9215 $scriptpath = $CFG->customscripts . $SCRIPT;
9217 // Check the custom script exists.
9218 if (file_exists($scriptpath) and is_file($scriptpath)) {
9219 return $scriptpath;
9220 } else {
9221 return false;
9226 * Returns whether or not the user object is a remote MNET user. This function
9227 * is in moodlelib because it does not rely on loading any of the MNET code.
9229 * @param object $user A valid user object
9230 * @return bool True if the user is from a remote Moodle.
9232 function is_mnet_remote_user($user) {
9233 global $CFG;
9235 if (!isset($CFG->mnet_localhost_id)) {
9236 include_once($CFG->dirroot . '/mnet/lib.php');
9237 $env = new mnet_environment();
9238 $env->init();
9239 unset($env);
9242 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9246 * This function will search for browser prefereed languages, setting Moodle
9247 * to use the best one available if $SESSION->lang is undefined
9249 function setup_lang_from_browser() {
9250 global $CFG, $SESSION, $USER;
9252 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9253 // Lang is defined in session or user profile, nothing to do.
9254 return;
9257 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9258 return;
9261 // Extract and clean langs from headers.
9262 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9263 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9264 $rawlangs = explode(',', $rawlangs); // Convert to array.
9265 $langs = array();
9267 $order = 1.0;
9268 foreach ($rawlangs as $lang) {
9269 if (strpos($lang, ';') === false) {
9270 $langs[(string)$order] = $lang;
9271 $order = $order-0.01;
9272 } else {
9273 $parts = explode(';', $lang);
9274 $pos = strpos($parts[1], '=');
9275 $langs[substr($parts[1], $pos+1)] = $parts[0];
9278 krsort($langs, SORT_NUMERIC);
9280 // Look for such langs under standard locations.
9281 foreach ($langs as $lang) {
9282 // Clean it properly for include.
9283 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9284 if (get_string_manager()->translation_exists($lang, false)) {
9285 // Lang exists, set it in session.
9286 $SESSION->lang = $lang;
9287 // We have finished. Go out.
9288 break;
9291 return;
9295 * Check if $url matches anything in proxybypass list
9297 * Any errors just result in the proxy being used (least bad)
9299 * @param string $url url to check
9300 * @return boolean true if we should bypass the proxy
9302 function is_proxybypass( $url ) {
9303 global $CFG;
9305 // Sanity check.
9306 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9307 return false;
9310 // Get the host part out of the url.
9311 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9312 return false;
9315 // Get the possible bypass hosts into an array.
9316 $matches = explode( ',', $CFG->proxybypass );
9318 // Check for a match.
9319 // (IPs need to match the left hand side and hosts the right of the url,
9320 // but we can recklessly check both as there can't be a false +ve).
9321 foreach ($matches as $match) {
9322 $match = trim($match);
9324 // Try for IP match (Left side).
9325 $lhs = substr($host, 0, strlen($match));
9326 if (strcasecmp($match, $lhs)==0) {
9327 return true;
9330 // Try for host match (Right side).
9331 $rhs = substr($host, -strlen($match));
9332 if (strcasecmp($match, $rhs)==0) {
9333 return true;
9337 // Nothing matched.
9338 return false;
9342 * Check if the passed navigation is of the new style
9344 * @param mixed $navigation
9345 * @return bool true for yes false for no
9347 function is_newnav($navigation) {
9348 if (is_array($navigation) && !empty($navigation['newnav'])) {
9349 return true;
9350 } else {
9351 return false;
9356 * Checks whether the given variable name is defined as a variable within the given object.
9358 * This will NOT work with stdClass objects, which have no class variables.
9360 * @param string $var The variable name
9361 * @param object $object The object to check
9362 * @return boolean
9364 function in_object_vars($var, $object) {
9365 $classvars = get_class_vars(get_class($object));
9366 $classvars = array_keys($classvars);
9367 return in_array($var, $classvars);
9371 * Returns an array without repeated objects.
9372 * This function is similar to array_unique, but for arrays that have objects as values
9374 * @param array $array
9375 * @param bool $keepkeyassoc
9376 * @return array
9378 function object_array_unique($array, $keepkeyassoc = true) {
9379 $duplicatekeys = array();
9380 $tmp = array();
9382 foreach ($array as $key => $val) {
9383 // Convert objects to arrays, in_array() does not support objects.
9384 if (is_object($val)) {
9385 $val = (array)$val;
9388 if (!in_array($val, $tmp)) {
9389 $tmp[] = $val;
9390 } else {
9391 $duplicatekeys[] = $key;
9395 foreach ($duplicatekeys as $key) {
9396 unset($array[$key]);
9399 return $keepkeyassoc ? $array : array_values($array);
9403 * Is a userid the primary administrator?
9405 * @param int $userid int id of user to check
9406 * @return boolean
9408 function is_primary_admin($userid) {
9409 $primaryadmin = get_admin();
9411 if ($userid == $primaryadmin->id) {
9412 return true;
9413 } else {
9414 return false;
9419 * Returns the site identifier
9421 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9423 function get_site_identifier() {
9424 global $CFG;
9425 // Check to see if it is missing. If so, initialise it.
9426 if (empty($CFG->siteidentifier)) {
9427 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9429 // Return it.
9430 return $CFG->siteidentifier;
9434 * Check whether the given password has no more than the specified
9435 * number of consecutive identical characters.
9437 * @param string $password password to be checked against the password policy
9438 * @param integer $maxchars maximum number of consecutive identical characters
9439 * @return bool
9441 function check_consecutive_identical_characters($password, $maxchars) {
9443 if ($maxchars < 1) {
9444 return true; // Zero 0 is to disable this check.
9446 if (strlen($password) <= $maxchars) {
9447 return true; // Too short to fail this test.
9450 $previouschar = '';
9451 $consecutivecount = 1;
9452 foreach (str_split($password) as $char) {
9453 if ($char != $previouschar) {
9454 $consecutivecount = 1;
9455 } else {
9456 $consecutivecount++;
9457 if ($consecutivecount > $maxchars) {
9458 return false; // Check failed already.
9462 $previouschar = $char;
9465 return true;
9469 * Helper function to do partial function binding.
9470 * so we can use it for preg_replace_callback, for example
9471 * this works with php functions, user functions, static methods and class methods
9472 * it returns you a callback that you can pass on like so:
9474 * $callback = partial('somefunction', $arg1, $arg2);
9475 * or
9476 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9477 * or even
9478 * $obj = new someclass();
9479 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9481 * and then the arguments that are passed through at calltime are appended to the argument list.
9483 * @param mixed $function a php callback
9484 * @param mixed $arg1,... $argv arguments to partially bind with
9485 * @return array Array callback
9487 function partial() {
9488 if (!class_exists('partial')) {
9490 * Used to manage function binding.
9491 * @copyright 2009 Penny Leach
9492 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9494 class partial{
9495 /** @var array */
9496 public $values = array();
9497 /** @var string The function to call as a callback. */
9498 public $func;
9500 * Constructor
9501 * @param string $func
9502 * @param array $args
9504 public function __construct($func, $args) {
9505 $this->values = $args;
9506 $this->func = $func;
9509 * Calls the callback function.
9510 * @return mixed
9512 public function method() {
9513 $args = func_get_args();
9514 return call_user_func_array($this->func, array_merge($this->values, $args));
9518 $args = func_get_args();
9519 $func = array_shift($args);
9520 $p = new partial($func, $args);
9521 return array($p, 'method');
9525 * helper function to load up and initialise the mnet environment
9526 * this must be called before you use mnet functions.
9528 * @return mnet_environment the equivalent of old $MNET global
9530 function get_mnet_environment() {
9531 global $CFG;
9532 require_once($CFG->dirroot . '/mnet/lib.php');
9533 static $instance = null;
9534 if (empty($instance)) {
9535 $instance = new mnet_environment();
9536 $instance->init();
9538 return $instance;
9542 * during xmlrpc server code execution, any code wishing to access
9543 * information about the remote peer must use this to get it.
9545 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9547 function get_mnet_remote_client() {
9548 if (!defined('MNET_SERVER')) {
9549 debugging(get_string('notinxmlrpcserver', 'mnet'));
9550 return false;
9552 global $MNET_REMOTE_CLIENT;
9553 if (isset($MNET_REMOTE_CLIENT)) {
9554 return $MNET_REMOTE_CLIENT;
9556 return false;
9560 * during the xmlrpc server code execution, this will be called
9561 * to setup the object returned by {@link get_mnet_remote_client}
9563 * @param mnet_remote_client $client the client to set up
9564 * @throws moodle_exception
9566 function set_mnet_remote_client($client) {
9567 if (!defined('MNET_SERVER')) {
9568 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9570 global $MNET_REMOTE_CLIENT;
9571 $MNET_REMOTE_CLIENT = $client;
9575 * return the jump url for a given remote user
9576 * this is used for rewriting forum post links in emails, etc
9578 * @param stdclass $user the user to get the idp url for
9580 function mnet_get_idp_jump_url($user) {
9581 global $CFG;
9583 static $mnetjumps = array();
9584 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9585 $idp = mnet_get_peer_host($user->mnethostid);
9586 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9587 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9589 return $mnetjumps[$user->mnethostid];
9593 * Gets the homepage to use for the current user
9595 * @return int One of HOMEPAGE_*
9597 function get_home_page() {
9598 global $CFG;
9600 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9601 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9602 return HOMEPAGE_MY;
9603 } else {
9604 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9607 return HOMEPAGE_SITE;
9611 * Gets the name of a course to be displayed when showing a list of courses.
9612 * By default this is just $course->fullname but user can configure it. The
9613 * result of this function should be passed through print_string.
9614 * @param stdClass|course_in_list $course Moodle course object
9615 * @return string Display name of course (either fullname or short + fullname)
9617 function get_course_display_name_for_list($course) {
9618 global $CFG;
9619 if (!empty($CFG->courselistshortnames)) {
9620 if (!($course instanceof stdClass)) {
9621 $course = (object)convert_to_array($course);
9623 return get_string('courseextendednamedisplay', '', $course);
9624 } else {
9625 return $course->fullname;
9630 * The lang_string class
9632 * This special class is used to create an object representation of a string request.
9633 * It is special because processing doesn't occur until the object is first used.
9634 * The class was created especially to aid performance in areas where strings were
9635 * required to be generated but were not necessarily used.
9636 * As an example the admin tree when generated uses over 1500 strings, of which
9637 * normally only 1/3 are ever actually printed at any time.
9638 * The performance advantage is achieved by not actually processing strings that
9639 * arn't being used, as such reducing the processing required for the page.
9641 * How to use the lang_string class?
9642 * There are two methods of using the lang_string class, first through the
9643 * forth argument of the get_string function, and secondly directly.
9644 * The following are examples of both.
9645 * 1. Through get_string calls e.g.
9646 * $string = get_string($identifier, $component, $a, true);
9647 * $string = get_string('yes', 'moodle', null, true);
9648 * 2. Direct instantiation
9649 * $string = new lang_string($identifier, $component, $a, $lang);
9650 * $string = new lang_string('yes');
9652 * How do I use a lang_string object?
9653 * The lang_string object makes use of a magic __toString method so that you
9654 * are able to use the object exactly as you would use a string in most cases.
9655 * This means you are able to collect it into a variable and then directly
9656 * echo it, or concatenate it into another string, or similar.
9657 * The other thing you can do is manually get the string by calling the
9658 * lang_strings out method e.g.
9659 * $string = new lang_string('yes');
9660 * $string->out();
9661 * Also worth noting is that the out method can take one argument, $lang which
9662 * allows the developer to change the language on the fly.
9664 * When should I use a lang_string object?
9665 * The lang_string object is designed to be used in any situation where a
9666 * string may not be needed, but needs to be generated.
9667 * The admin tree is a good example of where lang_string objects should be
9668 * used.
9669 * A more practical example would be any class that requries strings that may
9670 * not be printed (after all classes get renderer by renderers and who knows
9671 * what they will do ;))
9673 * When should I not use a lang_string object?
9674 * Don't use lang_strings when you are going to use a string immediately.
9675 * There is no need as it will be processed immediately and there will be no
9676 * advantage, and in fact perhaps a negative hit as a class has to be
9677 * instantiated for a lang_string object, however get_string won't require
9678 * that.
9680 * Limitations:
9681 * 1. You cannot use a lang_string object as an array offset. Doing so will
9682 * result in PHP throwing an error. (You can use it as an object property!)
9684 * @package core
9685 * @category string
9686 * @copyright 2011 Sam Hemelryk
9687 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9689 class lang_string {
9691 /** @var string The strings identifier */
9692 protected $identifier;
9693 /** @var string The strings component. Default '' */
9694 protected $component = '';
9695 /** @var array|stdClass Any arguments required for the string. Default null */
9696 protected $a = null;
9697 /** @var string The language to use when processing the string. Default null */
9698 protected $lang = null;
9700 /** @var string The processed string (once processed) */
9701 protected $string = null;
9704 * A special boolean. If set to true then the object has been woken up and
9705 * cannot be regenerated. If this is set then $this->string MUST be used.
9706 * @var bool
9708 protected $forcedstring = false;
9711 * Constructs a lang_string object
9713 * This function should do as little processing as possible to ensure the best
9714 * performance for strings that won't be used.
9716 * @param string $identifier The strings identifier
9717 * @param string $component The strings component
9718 * @param stdClass|array $a Any arguments the string requires
9719 * @param string $lang The language to use when processing the string.
9720 * @throws coding_exception
9722 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9723 if (empty($component)) {
9724 $component = 'moodle';
9727 $this->identifier = $identifier;
9728 $this->component = $component;
9729 $this->lang = $lang;
9731 // We MUST duplicate $a to ensure that it if it changes by reference those
9732 // changes are not carried across.
9733 // To do this we always ensure $a or its properties/values are strings
9734 // and that any properties/values that arn't convertable are forgotten.
9735 if (!empty($a)) {
9736 if (is_scalar($a)) {
9737 $this->a = $a;
9738 } else if ($a instanceof lang_string) {
9739 $this->a = $a->out();
9740 } else if (is_object($a) or is_array($a)) {
9741 $a = (array)$a;
9742 $this->a = array();
9743 foreach ($a as $key => $value) {
9744 // Make sure conversion errors don't get displayed (results in '').
9745 if (is_array($value)) {
9746 $this->a[$key] = '';
9747 } else if (is_object($value)) {
9748 if (method_exists($value, '__toString')) {
9749 $this->a[$key] = $value->__toString();
9750 } else {
9751 $this->a[$key] = '';
9753 } else {
9754 $this->a[$key] = (string)$value;
9760 if (debugging(false, DEBUG_DEVELOPER)) {
9761 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9762 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9764 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9765 throw new coding_exception('Invalid string compontent. Please check your string definition');
9767 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9768 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9774 * Processes the string.
9776 * This function actually processes the string, stores it in the string property
9777 * and then returns it.
9778 * You will notice that this function is VERY similar to the get_string method.
9779 * That is because it is pretty much doing the same thing.
9780 * However as this function is an upgrade it isn't as tolerant to backwards
9781 * compatibility.
9783 * @return string
9784 * @throws coding_exception
9786 protected function get_string() {
9787 global $CFG;
9789 // Check if we need to process the string.
9790 if ($this->string === null) {
9791 // Check the quality of the identifier.
9792 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9793 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);
9796 // Process the string.
9797 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9798 // Debugging feature lets you display string identifier and component.
9799 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9800 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9803 // Return the string.
9804 return $this->string;
9808 * Returns the string
9810 * @param string $lang The langauge to use when processing the string
9811 * @return string
9813 public function out($lang = null) {
9814 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9815 if ($this->forcedstring) {
9816 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9817 return $this->get_string();
9819 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9820 return $translatedstring->out();
9822 return $this->get_string();
9826 * Magic __toString method for printing a string
9828 * @return string
9830 public function __toString() {
9831 return $this->get_string();
9835 * Magic __set_state method used for var_export
9837 * @return string
9839 public function __set_state() {
9840 return $this->get_string();
9844 * Prepares the lang_string for sleep and stores only the forcedstring and
9845 * string properties... the string cannot be regenerated so we need to ensure
9846 * it is generated for this.
9848 * @return string
9850 public function __sleep() {
9851 $this->get_string();
9852 $this->forcedstring = true;
9853 return array('forcedstring', 'string', 'lang');