2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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
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.
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
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.
75 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
77 define('PARAM_ALPHA', 'alpha');
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');
86 * PARAM_ALPHANUM - expected numbers and letters only.
88 define('PARAM_ALPHANUM', 'alphanum');
91 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
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');
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);
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);
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
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
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];
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
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
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];
606 print_error('missingparam', '', '', $parname);
608 if (!is_array($param)) {
609 print_error('missingparam', '', '', $parname);
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);
618 $result[$key] = clean_param($value, $type);
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
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
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];
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
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
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];
694 if (!is_array($param)) {
695 debugging('optional_param_array() expects array parameters only: '.$parname);
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);
705 $result[$key] = clean_param($value, $type);
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
) {
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)) {
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);
755 * Makes sure array contains only the allowed types, this function does not validate array key names!
758 * $options = clean_param($options, PARAM_INT);
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
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)) {
773 $param[$key] = clean_param_array($value, $type, true);
775 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
778 $param[$key] = clean_param($value, $type);
785 * Used by {@link optional_param()} and {@link required_param()} to
786 * clean the variables and/or cast to specific types, based on
789 * $course->format = clean_param($course->format, PARAM_ALPHA);
790 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
793 * @param mixed $param the variable we are cleaning
794 * @param string $type expected format of param after cleaning.
796 * @throws coding_exception
798 function clean_param($param, $type) {
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();
807 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
813 // No cleaning at all.
814 $param = fix_utf8($param);
817 case PARAM_RAW_TRIMMED
:
818 // No cleaning, but strip leading and trailing whitespace.
819 $param = fix_utf8($param);
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)) {
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
);
840 // Convert to integer.
845 return (float)$param;
848 // Remove everything not `a-z`.
849 return preg_replace('/[^a-zA-Z]/i', '', $param);
852 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
853 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
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);
864 // Remove everything not `0-9,`.
865 return preg_replace('/[^0-9,]/i', '', $param);
868 // Convert to 1 or 0.
869 $tempstr = strtolower($param);
870 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
872 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
875 $param = empty($param) ?
0 : 1;
881 $param = fix_utf8($param);
882 return strip_tags($param);
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.
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)) {
897 foreach ($matches[0] as $match) {
898 if ($match === '</lang>') {
906 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
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)) {
924 foreach ($matches[0] as $match) {
925 if ($match === '</span>') {
933 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
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)) {
954 if (strpos($param, '__') !== false) {
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) {
967 // We do not want any guessing here, either the name is correct or not.
968 if (!is_valid_plugin_name($param)) {
974 // Remove everything not a-zA-Z0-9_- .
975 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
978 // Remove everything not a-zA-Z0-9/_- .
979 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
982 // Strip all suspicious characters from filename.
983 $param = fix_utf8($param);
984 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
985 if ($param === '.' ||
$param === '..') {
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.
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);
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
1021 ||
$match[4] > 255 ) {
1022 // Hmmm, what kind of dotted quad is this?
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.
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.
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
) {
1057 } else if (!empty($CFG->loginhttps
) && $param === $httpswwwroot) {
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.
1066 // Relative - let's make sure there are no tricks.
1067 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1077 $param = trim($param);
1078 // PEM formatted strings may contain letters/numbers and the symbols:
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
);
1088 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1096 if (!empty($param)) {
1097 // PEM formatted strings may contain letters/numbers and the symbols
1101 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
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++
) {
1109 if (64 < strlen($lines[$i])) {
1115 if (64 != strlen($lines[$i])) {
1119 return implode("\n", $lines);
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
);
1136 $param = fix_utf8($param);
1137 $tags = explode(',', $param);
1139 foreach ($tags as $tag) {
1140 $res = clean_param($tag, PARAM_TAG
);
1146 return implode(',', $result);
1151 case PARAM_CAPABILITY
:
1152 if (get_capability_info($param)) {
1158 case PARAM_PERMISSION
:
1159 $param = (int)$param;
1160 if (in_array($param, array(CAP_INHERIT
, CAP_ALLOW
, CAP_PREVENT
, CAP_PROHIBIT
))) {
1167 $param = clean_param($param, PARAM_PLUGIN
);
1168 if (empty($param)) {
1170 } else if (exists_auth_plugin($param)) {
1177 $param = clean_param($param, PARAM_SAFEDIR
);
1178 if (get_string_manager()->translation_exists($param)) {
1181 // Specified language is not installed or param malformed.
1186 $param = clean_param($param, PARAM_PLUGIN
);
1187 if (empty($param)) {
1189 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1191 } else if (!empty($CFG->themedir
) and file_exists("$CFG->themedir/$param/config.php")) {
1194 // Specified theme is not installed.
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);
1212 $param = fix_utf8($param);
1213 if (validate_email($param)) {
1219 case PARAM_STRINGID
:
1220 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
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)) {
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_*.
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 === '') {
1273 } else if (is_string($value)) {
1274 if ((string)(int)$value === $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€');
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);
1295 // Warn admins on admin/index.php page.
1300 $result = @iconv
('UTF-8', 'UTF-8//IGNORE', $value);
1305 } else if (is_array($value)) {
1306 foreach ($value as $k => $v) {
1307 $value[$k] = fix_utf8($v);
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);
1320 // This is some other type, no utf-8 here.
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)) {
1334 } else if (is_string($value)) {
1335 return ((string)(int)$value) === $value;
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);
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) {
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)) {
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));
1406 $DB->set_field('config', 'value', $value, array('name' => $name));
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');
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));
1426 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
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);
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) {
1465 static $siteidentifier = null;
1467 if ($plugin === 'moodle' ||
$plugin === 'core' ||
empty($plugin)) {
1468 $forced =& $CFG->config_php_settings
;
1472 if (array_key_exists($plugin, $CFG->forced_plugin_settings
)) {
1473 $forced =& $CFG->forced_plugin_settings
[$plugin];
1480 if ($siteidentifier === null) {
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;
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.
1506 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
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];
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]);
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) {
1550 if (empty($plugin)) {
1552 $DB->delete_records('config', array('name' => $name));
1553 cache_helper
::invalidate_by_definition('core', 'config', array(), 'core');
1555 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1556 cache_helper
::invalidate_by_definition('core', 'config', array(), $plugin);
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) {
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));
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@$') {
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@$') {
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;
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()}
1635 function purge_all_caches() {
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.
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.
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) {
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";
1689 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1690 foreach ($flags as $flag) {
1691 $cf[$flag->name
] = $flag->value
;
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) {
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) {
1731 $timemodified = time();
1732 if ($expiry === null ||
$expiry < $timemodified) {
1733 $expiry = $timemodified +
24 * 60 * 60;
1735 $expiry = (int)$expiry;
1738 if ($value === null) {
1739 unset_cache_flag($type, $name);
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.
1749 $f->expiry
= $expiry;
1750 $f->timemodified
= $timemodified;
1751 $DB->update_record('cache_flags', $f);
1753 $f = new stdClass();
1754 $f->flagtype
= $type;
1757 $f->expiry
= $expiry;
1758 $f->timemodified
= $timemodified;
1759 $DB->insert_record('cache_flags', $f);
1765 * Removes a single volatile flag
1767 * @param string $type the "type" namespace for the key
1768 * @param string $name the key to set
1771 function unset_cache_flag($type, $name) {
1773 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1778 * Garbage-collect volatile flags
1780 * @return bool Always returns true
1782 function gc_cache_flags() {
1784 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
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.
1797 * @category preference
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
1804 function check_user_preferences_loaded(stdClass
$user, $cachelifetime = 120) {
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();
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.
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;
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.
1849 * @param integer $userid the user whose prefs were changed.
1851 function mark_user_preferences_changed($userid) {
1854 if (empty($userid) or isguestuser($userid)) {
1855 // No cache flags for guest and not-logged-in users.
1859 set_cache_flag('userpreferenceschanged', $userid, 1, time() +
$CFG->sessiontimeout
);
1863 * Sets a preference for the specified user.
1865 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1867 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1870 * @category preference
1872 * @param string $name The key to set as preference for the specified user
1873 * @param string $value The value to set for the $name key in the specified user's
1874 * record, null means delete current value.
1875 * @param stdClass|int|null $user A moodle user object or id, null means current user
1876 * @throws coding_exception
1877 * @return bool Always true or exception
1879 function set_user_preference($name, $value, $user = null) {
1882 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1883 throw new coding_exception('Invalid preference name in set_user_preference() call');
1886 if (is_null($value)) {
1887 // Null means delete current.
1888 return unset_user_preference($name, $user);
1889 } else if (is_object($value)) {
1890 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1891 } else if (is_array($value)) {
1892 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1894 // Value column maximum length is 1333 characters.
1895 $value = (string)$value;
1896 if (core_text
::strlen($value) > 1333) {
1897 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1900 if (is_null($user)) {
1902 } else if (isset($user->id
)) {
1903 // It is a valid object.
1904 } else if (is_numeric($user)) {
1905 $user = (object)array('id' => (int)$user);
1907 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1910 check_user_preferences_loaded($user);
1912 if (empty($user->id
) or isguestuser($user->id
)) {
1913 // No permanent storage for not-logged-in users and guest.
1914 $user->preference
[$name] = $value;
1918 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => $name))) {
1919 if ($preference->value
=== $value and isset($user->preference
[$name]) and $user->preference
[$name] === $value) {
1920 // Preference already set to this value.
1923 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id
));
1926 $preference = new stdClass();
1927 $preference->userid
= $user->id
;
1928 $preference->name
= $name;
1929 $preference->value
= $value;
1930 $DB->insert_record('user_preferences', $preference);
1933 // Update value in cache.
1934 $user->preference
[$name] = $value;
1935 // Update the $USER in case where we've not a direct reference to $USER.
1936 if ($user !== $USER && $user->id
== $USER->id
) {
1937 $USER->preference
[$name] = $value;
1940 // Set reload flag for other sessions.
1941 mark_user_preferences_changed($user->id
);
1947 * Sets a whole array of preferences for the current user
1949 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1952 * @category preference
1954 * @param array $prefarray An array of key/value pairs to be set
1955 * @param stdClass|int|null $user A moodle user object or id, null means current user
1956 * @return bool Always true or exception
1958 function set_user_preferences(array $prefarray, $user = null) {
1959 foreach ($prefarray as $name => $value) {
1960 set_user_preference($name, $value, $user);
1966 * Unsets a preference completely by deleting it from the database
1968 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1971 * @category preference
1973 * @param string $name The key to unset as preference for the specified user
1974 * @param stdClass|int|null $user A moodle user object or id, null means current user
1975 * @throws coding_exception
1976 * @return bool Always true or exception
1978 function unset_user_preference($name, $user = null) {
1981 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1982 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1985 if (is_null($user)) {
1987 } else if (isset($user->id
)) {
1988 // It is a valid object.
1989 } else if (is_numeric($user)) {
1990 $user = (object)array('id' => (int)$user);
1992 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1995 check_user_preferences_loaded($user);
1997 if (empty($user->id
) or isguestuser($user->id
)) {
1998 // No permanent storage for not-logged-in user and guest.
1999 unset($user->preference
[$name]);
2004 $DB->delete_records('user_preferences', array('userid' => $user->id
, 'name' => $name));
2006 // Delete the preference from cache.
2007 unset($user->preference
[$name]);
2008 // Update the $USER in case where we've not a direct reference to $USER.
2009 if ($user !== $USER && $user->id
== $USER->id
) {
2010 unset($USER->preference
[$name]);
2013 // Set reload flag for other sessions.
2014 mark_user_preferences_changed($user->id
);
2020 * Used to fetch user preference(s)
2022 * If no arguments are supplied this function will return
2023 * all of the current user preferences as an array.
2025 * If a name is specified then this function
2026 * attempts to return that particular preference value. If
2027 * none is found, then the optional value $default is returned,
2030 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2033 * @category preference
2035 * @param string $name Name of the key to use in finding a preference value
2036 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2037 * @param stdClass|int|null $user A moodle user object or id, null means current user
2038 * @throws coding_exception
2039 * @return string|mixed|null A string containing the value of a single preference. An
2040 * array with all of the preferences or null
2042 function get_user_preferences($name = null, $default = null, $user = null) {
2045 if (is_null($name)) {
2047 } else if (is_numeric($name) or $name === '_lastloaded') {
2048 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2051 if (is_null($user)) {
2053 } else if (isset($user->id
)) {
2054 // Is a valid object.
2055 } else if (is_numeric($user)) {
2056 $user = (object)array('id' => (int)$user);
2058 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2061 check_user_preferences_loaded($user);
2065 return $user->preference
;
2066 } else if (isset($user->preference
[$name])) {
2067 // The single string value.
2068 return $user->preference
[$name];
2070 // Default value (null if not specified).
2075 // FUNCTIONS FOR HANDLING TIME.
2078 * Given Gregorian date parts in user time produce a GMT timestamp.
2082 * @param int $year The year part to create timestamp of
2083 * @param int $month The month part to create timestamp of
2084 * @param int $day The day part to create timestamp of
2085 * @param int $hour The hour part to create timestamp of
2086 * @param int $minute The minute part to create timestamp of
2087 * @param int $second The second part to create timestamp of
2088 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2089 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2090 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2091 * applied only if timezone is 99 or string.
2092 * @return int GMT timestamp
2094 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2095 $date = new DateTime('now', core_date
::get_user_timezone_object($timezone));
2096 $date->setDate((int)$year, (int)$month, (int)$day);
2097 $date->setTime((int)$hour, (int)$minute, (int)$second);
2099 $time = $date->getTimestamp();
2101 if ($time === false) {
2102 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2103 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2106 // Moodle BC DST stuff.
2108 $time +
= dst_offset_on($time, $timezone);
2116 * Format a date/time (seconds) as weeks, days, hours etc as needed
2118 * Given an amount of time in seconds, returns string
2119 * formatted nicely as weeks, days, hours etc as needed
2127 * @param int $totalsecs Time in seconds
2128 * @param stdClass $str Should be a time object
2129 * @return string A nicely formatted date/time string
2131 function format_time($totalsecs, $str = null) {
2133 $totalsecs = abs($totalsecs);
2136 // Create the str structure the slow way.
2137 $str = new stdClass();
2138 $str->day
= get_string('day');
2139 $str->days
= get_string('days');
2140 $str->hour
= get_string('hour');
2141 $str->hours
= get_string('hours');
2142 $str->min
= get_string('min');
2143 $str->mins
= get_string('mins');
2144 $str->sec
= get_string('sec');
2145 $str->secs
= get_string('secs');
2146 $str->year
= get_string('year');
2147 $str->years
= get_string('years');
2150 $years = floor($totalsecs/YEARSECS
);
2151 $remainder = $totalsecs - ($years*YEARSECS
);
2152 $days = floor($remainder/DAYSECS
);
2153 $remainder = $totalsecs - ($days*DAYSECS
);
2154 $hours = floor($remainder/HOURSECS
);
2155 $remainder = $remainder - ($hours*HOURSECS
);
2156 $mins = floor($remainder/MINSECS
);
2157 $secs = $remainder - ($mins*MINSECS
);
2159 $ss = ($secs == 1) ?
$str->sec
: $str->secs
;
2160 $sm = ($mins == 1) ?
$str->min
: $str->mins
;
2161 $sh = ($hours == 1) ?
$str->hour
: $str->hours
;
2162 $sd = ($days == 1) ?
$str->day
: $str->days
;
2163 $sy = ($years == 1) ?
$str->year
: $str->years
;
2172 $oyears = $years .' '. $sy;
2175 $odays = $days .' '. $sd;
2178 $ohours = $hours .' '. $sh;
2181 $omins = $mins .' '. $sm;
2184 $osecs = $secs .' '. $ss;
2188 return trim($oyears .' '. $odays);
2191 return trim($odays .' '. $ohours);
2194 return trim($ohours .' '. $omins);
2197 return trim($omins .' '. $osecs);
2202 return get_string('now');
2206 * Returns a formatted string that represents a date in user time.
2210 * @param int $date the timestamp in UTC, as obtained from the database.
2211 * @param string $format strftime format. You should probably get this using
2212 * get_string('strftime...', 'langconfig');
2213 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2214 * not 99 then daylight saving will not be added.
2215 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2216 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2217 * If false then the leading zero is maintained.
2218 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2219 * @return string the formatted date/time.
2221 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2222 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2223 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2227 * Returns a formatted date ensuring it is UTF-8.
2229 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2230 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2232 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2233 * @param string $format strftime format.
2234 * @param int|float|string $tz the user timezone
2235 * @return string the formatted date/time.
2236 * @since Moodle 2.3.3
2238 function date_format_string($date, $format, $tz = 99) {
2241 $localewincharset = null;
2242 // Get the calendar type user is using.
2243 if ($CFG->ostype
== 'WINDOWS') {
2244 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2245 $localewincharset = $calendartype->locale_win_charset();
2248 if ($localewincharset) {
2249 $format = core_text
::convert($format, 'utf-8', $localewincharset);
2252 date_default_timezone_set(core_date
::get_user_timezone($tz));
2253 $datestring = strftime($format, $date);
2254 core_date
::set_default_server_timezone();
2256 if ($localewincharset) {
2257 $datestring = core_text
::convert($datestring, $localewincharset, 'utf-8');
2264 * Given a $time timestamp in GMT (seconds since epoch),
2265 * returns an array that represents the Gregorian date in user time
2269 * @param int $time Timestamp in GMT
2270 * @param float|int|string $timezone user timezone
2271 * @return array An array that represents the date in user time
2273 function usergetdate($time, $timezone=99) {
2274 date_default_timezone_set(core_date
::get_user_timezone($timezone));
2275 $result = getdate($time);
2276 core_date
::set_default_server_timezone();
2282 * Given a GMT timestamp (seconds since epoch), offsets it by
2283 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2285 * NOTE: this function does not include DST properly,
2286 * you should use the PHP date stuff instead!
2290 * @param int $date Timestamp in GMT
2291 * @param float|int|string $timezone user timezone
2294 function usertime($date, $timezone=99) {
2295 $userdate = new DateTime('@' . $date);
2296 $userdate->setTimezone(core_date
::get_user_timezone_object($timezone));
2297 $dst = dst_offset_on($date, $timezone);
2299 return $date - $userdate->getOffset() +
$dst;
2303 * Given a time, return the GMT timestamp of the most recent midnight
2304 * for the current user.
2308 * @param int $date Timestamp in GMT
2309 * @param float|int|string $timezone user timezone
2310 * @return int Returns a GMT timestamp
2312 function usergetmidnight($date, $timezone=99) {
2314 $userdate = usergetdate($date, $timezone);
2316 // Time of midnight of this user's day, in GMT.
2317 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2322 * Returns a string that prints the user's timezone
2326 * @param float|int|string $timezone user timezone
2329 function usertimezone($timezone=99) {
2330 $tz = core_date
::get_user_timezone($timezone);
2331 return core_date
::get_localised_timezone($tz);
2335 * Returns a float or a string which denotes the user's timezone
2336 * 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)
2337 * means that for this timezone there are also DST rules to be taken into account
2338 * Checks various settings and picks the most dominant of those which have a value
2342 * @param float|int|string $tz timezone to calculate GMT time offset before
2343 * calculating user timezone, 99 is default user timezone
2344 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2345 * @return float|string
2347 function get_user_timezone($tz = 99) {
2352 isset($CFG->forcetimezone
) ?
$CFG->forcetimezone
: 99,
2353 isset($USER->timezone
) ?
$USER->timezone
: 99,
2354 isset($CFG->timezone
) ?
$CFG->timezone
: 99,
2359 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2360 while (((empty($tz) && !is_numeric($tz)) ||
$tz == 99) && $next = each($timezones)) {
2361 $tz = $next['value'];
2363 return is_numeric($tz) ?
(float) $tz : $tz;
2367 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2368 * - Note: Daylight saving only works for string timezones and not for float.
2372 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2373 * @param int|float|string $strtimezone user timezone
2376 function dst_offset_on($time, $strtimezone = null) {
2377 $tz = core_date
::get_user_timezone($strtimezone);
2378 $date = new DateTime('@' . $time);
2379 $date->setTimezone(new DateTimeZone($tz));
2380 if ($date->format('I') == '1') {
2381 if ($tz === 'Australia/Lord_Howe') {
2390 * Calculates when the day appears in specific month
2394 * @param int $startday starting day of the month
2395 * @param int $weekday The day when week starts (normally taken from user preferences)
2396 * @param int $month The month whose day is sought
2397 * @param int $year The year of the month whose day is sought
2400 function find_day_in_month($startday, $weekday, $month, $year) {
2401 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2403 $daysinmonth = days_in_month($month, $year);
2404 $daysinweek = count($calendartype->get_weekdays());
2406 if ($weekday == -1) {
2407 // Don't care about weekday, so return:
2408 // abs($startday) if $startday != -1
2409 // $daysinmonth otherwise.
2410 return ($startday == -1) ?
$daysinmonth : abs($startday);
2413 // From now on we 're looking for a specific weekday.
2414 // Give "end of month" its actual value, since we know it.
2415 if ($startday == -1) {
2416 $startday = -1 * $daysinmonth;
2419 // Starting from day $startday, the sign is the direction.
2420 if ($startday < 1) {
2421 $startday = abs($startday);
2422 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2424 // This is the last such weekday of the month.
2425 $lastinmonth = $daysinmonth +
$weekday - $lastmonthweekday;
2426 if ($lastinmonth > $daysinmonth) {
2427 $lastinmonth -= $daysinweek;
2430 // Find the first such weekday <= $startday.
2431 while ($lastinmonth > $startday) {
2432 $lastinmonth -= $daysinweek;
2435 return $lastinmonth;
2437 $indexweekday = dayofweek($startday, $month, $year);
2439 $diff = $weekday - $indexweekday;
2441 $diff +
= $daysinweek;
2444 // This is the first such weekday of the month equal to or after $startday.
2445 $firstfromindex = $startday +
$diff;
2447 return $firstfromindex;
2452 * Calculate the number of days in a given month
2456 * @param int $month The month whose day count is sought
2457 * @param int $year The year of the month whose day count is sought
2460 function days_in_month($month, $year) {
2461 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2462 return $calendartype->get_num_days_in_month($year, $month);
2466 * Calculate the position in the week of a specific calendar day
2470 * @param int $day The day of the date whose position in the week is sought
2471 * @param int $month The month of the date whose position in the week is sought
2472 * @param int $year The year of the date whose position in the week is sought
2475 function dayofweek($day, $month, $year) {
2476 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2477 return $calendartype->get_weekday($year, $month, $day);
2480 // USER AUTHENTICATION AND LOGIN.
2483 * Returns full login url.
2485 * @return string login url
2487 function get_login_url() {
2490 $url = "$CFG->wwwroot/login/index.php";
2492 if (!empty($CFG->loginhttps
)) {
2493 $url = str_replace('http:', 'https:', $url);
2500 * This function checks that the current user is logged in and has the
2501 * required privileges
2503 * This function checks that the current user is logged in, and optionally
2504 * whether they are allowed to be in a particular course and view a particular
2506 * If they are not logged in, then it redirects them to the site login unless
2507 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2508 * case they are automatically logged in as guests.
2509 * If $courseid is given and the user is not enrolled in that course then the
2510 * user is redirected to the course enrolment page.
2511 * If $cm is given and the course module is hidden and the user is not a teacher
2512 * in the course then the user is redirected to the course home page.
2514 * When $cm parameter specified, this function sets page layout to 'module'.
2515 * You need to change it manually later if some other layout needed.
2517 * @package core_access
2520 * @param mixed $courseorid id of the course or course object
2521 * @param bool $autologinguest default true
2522 * @param object $cm course module object
2523 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2524 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2525 * in order to keep redirects working properly. MDL-14495
2526 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2527 * @return mixed Void, exit, and die depending on path
2528 * @throws coding_exception
2529 * @throws require_login_exception
2530 * @throws moodle_exception
2532 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2533 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2535 // Must not redirect when byteserving already started.
2536 if (!empty($_SERVER['HTTP_RANGE'])) {
2537 $preventredirect = true;
2541 // We cannot redirect for AJAX scripts either.
2542 $preventredirect = true;
2545 // Setup global $COURSE, themes, language and locale.
2546 if (!empty($courseorid)) {
2547 if (is_object($courseorid)) {
2548 $course = $courseorid;
2549 } else if ($courseorid == SITEID
) {
2550 $course = clone($SITE);
2552 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST
);
2555 if ($cm->course
!= $course->id
) {
2556 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2558 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2559 if (!($cm instanceof cm_info
)) {
2560 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2561 // db queries so this is not really a performance concern, however it is obviously
2562 // better if you use get_fast_modinfo to get the cm before calling this.
2563 $modinfo = get_fast_modinfo($course);
2564 $cm = $modinfo->get_cm($cm->id
);
2568 // Do not touch global $COURSE via $PAGE->set_course(),
2569 // the reasons is we need to be able to call require_login() at any time!!
2572 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2576 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2577 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2578 // risk leading the user back to the AJAX request URL.
2579 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT
) {
2580 $setwantsurltome = false;
2583 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2584 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out
) && !empty($CFG->dbsessions
)) {
2585 if ($preventredirect) {
2586 throw new require_login_session_timeout_exception();
2588 if ($setwantsurltome) {
2589 $SESSION->wantsurl
= qualified_me();
2591 redirect(get_login_url());
2595 // If the user is not even logged in yet then make sure they are.
2596 if (!isloggedin()) {
2597 if ($autologinguest and !empty($CFG->guestloginbutton
) and !empty($CFG->autologinguests
)) {
2598 if (!$guest = get_complete_user_data('id', $CFG->siteguest
)) {
2599 // Misconfigured site guest, just redirect to login page.
2600 redirect(get_login_url());
2601 exit; // Never reached.
2603 $lang = isset($SESSION->lang
) ?
$SESSION->lang
: $CFG->lang
;
2604 complete_user_login($guest);
2605 $USER->autologinguest
= true;
2606 $SESSION->lang
= $lang;
2608 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2609 if ($preventredirect) {
2610 throw new require_login_exception('You are not logged in');
2613 if ($setwantsurltome) {
2614 $SESSION->wantsurl
= qualified_me();
2617 $referer = get_local_referer(false);
2618 if (!empty($referer)) {
2619 $SESSION->fromurl
= $referer;
2622 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2623 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2624 foreach($authsequence as $authname) {
2625 $authplugin = get_auth_plugin($authname);
2626 $authplugin->pre_loginpage_hook();
2632 // If we're still not logged in then go to the login page
2633 if (!isloggedin()) {
2634 redirect(get_login_url());
2635 exit; // Never reached.
2640 // Loginas as redirection if needed.
2641 if ($course->id
!= SITEID
and \core\session\manager
::is_loggedinas()) {
2642 if ($USER->loginascontext
->contextlevel
== CONTEXT_COURSE
) {
2643 if ($USER->loginascontext
->instanceid
!= $course->id
) {
2644 print_error('loginasonecourse', '', $CFG->wwwroot
.'/course/view.php?id='.$USER->loginascontext
->instanceid
);
2649 // Check whether the user should be changing password (but only if it is REALLY them).
2650 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager
::is_loggedinas()) {
2651 $userauth = get_auth_plugin($USER->auth
);
2652 if ($userauth->can_change_password() and !$preventredirect) {
2653 if ($setwantsurltome) {
2654 $SESSION->wantsurl
= qualified_me();
2656 if ($changeurl = $userauth->change_password_url()) {
2657 // Use plugin custom url.
2658 redirect($changeurl);
2660 // Use moodle internal method.
2661 if (empty($CFG->loginhttps
)) {
2662 redirect($CFG->wwwroot
.'/login/change_password.php');
2664 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot
);
2665 redirect($wwwroot .'/login/change_password.php');
2668 } else if ($userauth->can_change_password()) {
2669 throw new moodle_exception('forcepasswordchangenotice');
2671 throw new moodle_exception('nopasswordchangeforced', 'auth');
2675 // Check that the user account is properly set up. If we can't redirect to
2676 // edit their profile and this is not a WS request, perform just the lax check.
2677 // It will allow them to use filepicker on the profile edit page.
2679 if ($preventredirect && !WS_SERVER
) {
2680 $usernotfullysetup = user_not_fully_set_up($USER, false);
2682 $usernotfullysetup = user_not_fully_set_up($USER, true);
2685 if ($usernotfullysetup) {
2686 if ($preventredirect) {
2687 throw new moodle_exception('usernotfullysetup');
2689 if ($setwantsurltome) {
2690 $SESSION->wantsurl
= qualified_me();
2692 redirect($CFG->wwwroot
.'/user/edit.php?id='. $USER->id
.'&course='. SITEID
);
2695 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2698 // Do not bother admins with any formalities, except for activities pending deletion.
2699 if (is_siteadmin() && !($cm && $cm->deletioninprogress
)) {
2700 // Set the global $COURSE.
2702 $PAGE->set_cm($cm, $course);
2703 $PAGE->set_pagelayout('incourse');
2704 } else if (!empty($courseorid)) {
2705 $PAGE->set_course($course);
2707 // Set accesstime or the user will appear offline which messes up messaging.
2708 user_accesstime_log($course->id
);
2712 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2713 if (!$USER->policyagreed
and !is_siteadmin()) {
2714 if (!empty($CFG->sitepolicy
) and !isguestuser()) {
2715 if ($preventredirect) {
2716 throw new moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicy
);
2718 if ($setwantsurltome) {
2719 $SESSION->wantsurl
= qualified_me();
2721 redirect($CFG->wwwroot
.'/user/policy.php');
2722 } else if (!empty($CFG->sitepolicyguest
) and isguestuser()) {
2723 if ($preventredirect) {
2724 throw new moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicyguest
);
2726 if ($setwantsurltome) {
2727 $SESSION->wantsurl
= qualified_me();
2729 redirect($CFG->wwwroot
.'/user/policy.php');
2733 // Fetch the system context, the course context, and prefetch its child contexts.
2734 $sysctx = context_system
::instance();
2735 $coursecontext = context_course
::instance($course->id
, MUST_EXIST
);
2737 $cmcontext = context_module
::instance($cm->id
, MUST_EXIST
);
2742 // If the site is currently under maintenance, then print a message.
2743 if (!empty($CFG->maintenance_enabled
) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2744 if ($preventredirect) {
2745 throw new require_login_exception('Maintenance in progress');
2747 $PAGE->set_context(null);
2748 print_maintenance_message();
2751 // Make sure the course itself is not hidden.
2752 if ($course->id
== SITEID
) {
2753 // Frontpage can not be hidden.
2755 if (is_role_switched($course->id
)) {
2756 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2758 if (!$course->visible
and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2759 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2760 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2761 if ($preventredirect) {
2762 throw new require_login_exception('Course is hidden');
2764 $PAGE->set_context(null);
2765 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2766 // the navigation will mess up when trying to find it.
2767 navigation_node
::override_active_url(new moodle_url('/'));
2768 notice(get_string('coursehidden'), $CFG->wwwroot
.'/');
2773 // Is the user enrolled?
2774 if ($course->id
== SITEID
) {
2775 // Everybody is enrolled on the frontpage.
2777 if (\core\session\manager
::is_loggedinas()) {
2778 // Make sure the REAL person can access this course first.
2779 $realuser = \core\session\manager
::get_realuser();
2780 if (!is_enrolled($coursecontext, $realuser->id
, '', true) and
2781 !is_viewing($coursecontext, $realuser->id
) and !is_siteadmin($realuser->id
)) {
2782 if ($preventredirect) {
2783 throw new require_login_exception('Invalid course login-as access');
2785 $PAGE->set_context(null);
2786 echo $OUTPUT->header();
2787 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot
.'/');
2793 if (is_role_switched($course->id
)) {
2794 // Ok, user had to be inside this course before the switch.
2797 } else if (is_viewing($coursecontext, $USER)) {
2798 // Ok, no need to mess with enrol.
2802 if (isset($USER->enrol
['enrolled'][$course->id
])) {
2803 if ($USER->enrol
['enrolled'][$course->id
] > time()) {
2805 if (isset($USER->enrol
['tempguest'][$course->id
])) {
2806 unset($USER->enrol
['tempguest'][$course->id
]);
2807 remove_temp_course_roles($coursecontext);
2811 unset($USER->enrol
['enrolled'][$course->id
]);
2814 if (isset($USER->enrol
['tempguest'][$course->id
])) {
2815 if ($USER->enrol
['tempguest'][$course->id
] == 0) {
2817 } else if ($USER->enrol
['tempguest'][$course->id
] > time()) {
2821 unset($USER->enrol
['tempguest'][$course->id
]);
2822 remove_temp_course_roles($coursecontext);
2828 $until = enrol_get_enrolment_end($coursecontext->instanceid
, $USER->id
);
2829 if ($until !== false) {
2830 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2832 $until = ENROL_MAX_TIMESTAMP
;
2834 $USER->enrol
['enrolled'][$course->id
] = $until;
2838 $params = array('courseid' => $course->id
, 'status' => ENROL_INSTANCE_ENABLED
);
2839 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2840 $enrols = enrol_get_plugins(true);
2841 // First ask all enabled enrol instances in course if they want to auto enrol user.
2842 foreach ($instances as $instance) {
2843 if (!isset($enrols[$instance->enrol
])) {
2846 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2847 $until = $enrols[$instance->enrol
]->try_autoenrol($instance);
2848 if ($until !== false) {
2850 $until = ENROL_MAX_TIMESTAMP
;
2852 $USER->enrol
['enrolled'][$course->id
] = $until;
2857 // If not enrolled yet try to gain temporary guest access.
2859 foreach ($instances as $instance) {
2860 if (!isset($enrols[$instance->enrol
])) {
2863 // Get a duration for the guest access, a timestamp in the future or false.
2864 $until = $enrols[$instance->enrol
]->try_guestaccess($instance);
2865 if ($until !== false and $until > time()) {
2866 $USER->enrol
['tempguest'][$course->id
] = $until;
2877 if ($preventredirect) {
2878 throw new require_login_exception('Not enrolled');
2880 if ($setwantsurltome) {
2881 $SESSION->wantsurl
= qualified_me();
2883 redirect($CFG->wwwroot
.'/enrol/index.php?id='. $course->id
);
2887 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
2888 if ($cm && $cm->deletioninprogress
) {
2889 if ($preventredirect) {
2890 throw new moodle_exception('activityisscheduledfordeletion');
2892 require_once($CFG->dirroot
. '/course/lib.php');
2893 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
2896 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2897 if ($cm && !$cm->uservisible
) {
2898 if ($preventredirect) {
2899 throw new require_login_exception('Activity is hidden');
2901 if ($course->id
!= SITEID
) {
2902 $url = new moodle_url('/course/view.php', array('id' => $course->id
));
2904 $url = new moodle_url('/');
2906 redirect($url, get_string('activityiscurrentlyhidden'));
2909 // Set the global $COURSE.
2911 $PAGE->set_cm($cm, $course);
2912 $PAGE->set_pagelayout('incourse');
2913 } else if (!empty($courseorid)) {
2914 $PAGE->set_course($course);
2917 // Finally access granted, update lastaccess times.
2918 user_accesstime_log($course->id
);
2923 * This function just makes sure a user is logged out.
2925 * @package core_access
2928 function require_logout() {
2931 if (!isloggedin()) {
2932 // This should not happen often, no need for hooks or events here.
2933 \core\session\manager
::terminate_current();
2937 // Execute hooks before action.
2938 $authplugins = array();
2939 $authsequence = get_enabled_auth_plugins();
2940 foreach ($authsequence as $authname) {
2941 $authplugins[$authname] = get_auth_plugin($authname);
2942 $authplugins[$authname]->prelogout_hook();
2945 // Store info that gets removed during logout.
2946 $sid = session_id();
2947 $event = \core\event\user_loggedout
::create(
2949 'userid' => $USER->id
,
2950 'objectid' => $USER->id
,
2951 'other' => array('sessionid' => $sid),
2954 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2955 $event->add_record_snapshot('sessions', $session);
2958 // Clone of $USER object to be used by auth plugins.
2959 $user = fullclone($USER);
2961 // Delete session record and drop $_SESSION content.
2962 \core\session\manager
::terminate_current();
2964 // Trigger event AFTER action.
2967 // Hook to execute auth plugins redirection after event trigger.
2968 foreach ($authplugins as $authplugin) {
2969 $authplugin->postlogout_hook($user);
2974 * Weaker version of require_login()
2976 * This is a weaker version of {@link require_login()} which only requires login
2977 * when called from within a course rather than the site page, unless
2978 * the forcelogin option is turned on.
2979 * @see require_login()
2981 * @package core_access
2984 * @param mixed $courseorid The course object or id in question
2985 * @param bool $autologinguest Allow autologin guests if that is wanted
2986 * @param object $cm Course activity module if known
2987 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2988 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2989 * in order to keep redirects working properly. MDL-14495
2990 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2992 * @throws coding_exception
2994 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2995 global $CFG, $PAGE, $SITE;
2996 $issite = ((is_object($courseorid) and $courseorid->id
== SITEID
)
2997 or (!is_object($courseorid) and $courseorid == SITEID
));
2998 if ($issite && !empty($cm) && !($cm instanceof cm_info
)) {
2999 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3000 // db queries so this is not really a performance concern, however it is obviously
3001 // better if you use get_fast_modinfo to get the cm before calling this.
3002 if (is_object($courseorid)) {
3003 $course = $courseorid;
3005 $course = clone($SITE);
3007 $modinfo = get_fast_modinfo($course);
3008 $cm = $modinfo->get_cm($cm->id
);
3010 if (!empty($CFG->forcelogin
)) {
3011 // Login required for both SITE and courses.
3012 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3014 } else if ($issite && !empty($cm) and !$cm->uservisible
) {
3015 // Always login for hidden activities.
3016 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3018 } else if ($issite) {
3019 // Login for SITE not required.
3020 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3021 if (!empty($courseorid)) {
3022 if (is_object($courseorid)) {
3023 $course = $courseorid;
3025 $course = clone $SITE;
3028 if ($cm->course
!= $course->id
) {
3029 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3031 $PAGE->set_cm($cm, $course);
3032 $PAGE->set_pagelayout('incourse');
3034 $PAGE->set_course($course);
3037 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3038 $PAGE->set_course($PAGE->course
);
3040 user_accesstime_log(SITEID
);
3044 // Course login always required.
3045 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3050 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3052 * @param string $keyvalue the key value
3053 * @param string $script unique script identifier
3054 * @param int $instance instance id
3055 * @return stdClass the key entry in the user_private_key table
3057 * @throws moodle_exception
3059 function validate_user_key($keyvalue, $script, $instance) {
3062 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3063 print_error('invalidkey');
3066 if (!empty($key->validuntil
) and $key->validuntil
< time()) {
3067 print_error('expiredkey');
3070 if ($key->iprestriction
) {
3071 $remoteaddr = getremoteaddr(null);
3072 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction
)) {
3073 print_error('ipmismatch');
3080 * Require key login. Function terminates with error if key not found or incorrect.
3082 * @uses NO_MOODLE_COOKIES
3083 * @uses PARAM_ALPHANUM
3084 * @param string $script unique script identifier
3085 * @param int $instance optional instance id
3086 * @return int Instance ID
3088 function require_user_key_login($script, $instance=null) {
3091 if (!NO_MOODLE_COOKIES
) {
3092 print_error('sessioncookiesdisable');
3096 \core\session\manager
::write_close();
3098 $keyvalue = required_param('key', PARAM_ALPHANUM
);
3100 $key = validate_user_key($keyvalue, $script, $instance);
3102 if (!$user = $DB->get_record('user', array('id' => $key->userid
))) {
3103 print_error('invaliduserid');
3106 // Emulate normal session.
3107 enrol_check_plugins($user);
3108 \core\session\manager
::set_user($user);
3110 // Note we are not using normal login.
3111 if (!defined('USER_KEY_LOGIN')) {
3112 define('USER_KEY_LOGIN', true);
3115 // Return instance id - it might be empty.
3116 return $key->instance
;
3120 * Creates a new private user access key.
3122 * @param string $script unique target identifier
3123 * @param int $userid
3124 * @param int $instance optional instance id
3125 * @param string $iprestriction optional ip restricted access
3126 * @param int $validuntil key valid only until given data
3127 * @return string access key value
3129 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3132 $key = new stdClass();
3133 $key->script
= $script;
3134 $key->userid
= $userid;
3135 $key->instance
= $instance;
3136 $key->iprestriction
= $iprestriction;
3137 $key->validuntil
= $validuntil;
3138 $key->timecreated
= time();
3140 // Something long and unique.
3141 $key->value
= md5($userid.'_'.time().random_string(40));
3142 while ($DB->record_exists('user_private_key', array('value' => $key->value
))) {
3144 $key->value
= md5($userid.'_'.time().random_string(40));
3146 $DB->insert_record('user_private_key', $key);
3151 * Delete the user's new private user access keys for a particular script.
3153 * @param string $script unique target identifier
3154 * @param int $userid
3157 function delete_user_key($script, $userid) {
3159 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3163 * Gets a private user access key (and creates one if one doesn't exist).
3165 * @param string $script unique target identifier
3166 * @param int $userid
3167 * @param int $instance optional instance id
3168 * @param string $iprestriction optional ip restricted access
3169 * @param int $validuntil key valid only until given date
3170 * @return string access key value
3172 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3175 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3176 'instance' => $instance, 'iprestriction' => $iprestriction,
3177 'validuntil' => $validuntil))) {
3180 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3186 * Modify the user table by setting the currently logged in user's last login to now.
3188 * @return bool Always returns true
3190 function update_user_login_times() {
3193 if (isguestuser()) {
3194 // Do not update guest access times/ips for performance.
3200 $user = new stdClass();
3201 $user->id
= $USER->id
;
3203 // Make sure all users that logged in have some firstaccess.
3204 if ($USER->firstaccess
== 0) {
3205 $USER->firstaccess
= $user->firstaccess
= $now;
3208 // Store the previous current as lastlogin.
3209 $USER->lastlogin
= $user->lastlogin
= $USER->currentlogin
;
3211 $USER->currentlogin
= $user->currentlogin
= $now;
3213 // Function user_accesstime_log() may not update immediately, better do it here.
3214 $USER->lastaccess
= $user->lastaccess
= $now;
3215 $USER->lastip
= $user->lastip
= getremoteaddr();
3217 // Note: do not call user_update_user() here because this is part of the login process,
3218 // the login event means that these fields were updated.
3219 $DB->update_record('user', $user);
3224 * Determines if a user has completed setting up their account.
3226 * The lax mode (with $strict = false) has been introduced for special cases
3227 * only where we want to skip certain checks intentionally. This is valid in
3228 * certain mnet or ajax scenarios when the user cannot / should not be
3229 * redirected to edit their profile. In most cases, you should perform the
3232 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3233 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3236 function user_not_fully_set_up($user, $strict = true) {
3238 require_once($CFG->dirroot
.'/user/profile/lib.php');
3240 if (isguestuser($user)) {
3244 if (empty($user->firstname
) or empty($user->lastname
) or empty($user->email
) or over_bounce_threshold($user)) {
3249 if (empty($user->id
)) {
3250 // Strict mode can be used with existing accounts only.
3253 if (!profile_has_required_custom_fields_set($user->id
)) {
3262 * Check whether the user has exceeded the bounce threshold
3264 * @param stdClass $user A {@link $USER} object
3265 * @return bool true => User has exceeded bounce threshold
3267 function over_bounce_threshold($user) {
3270 if (empty($CFG->handlebounces
)) {
3274 if (empty($user->id
)) {
3275 // No real (DB) user, nothing to do here.
3279 // Set sensible defaults.
3280 if (empty($CFG->minbounces
)) {
3281 $CFG->minbounces
= 10;
3283 if (empty($CFG->bounceratio
)) {
3284 $CFG->bounceratio
= .20;
3288 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id
, 'name' => 'email_bounce_count'))) {
3289 $bouncecount = $bounce->value
;
3291 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_send_count'))) {
3292 $sendcount = $send->value
;
3294 return ($bouncecount >= $CFG->minbounces
&& $bouncecount/$sendcount >= $CFG->bounceratio
);
3298 * Used to increment or reset email sent count
3300 * @param stdClass $user object containing an id
3301 * @param bool $reset will reset the count to 0
3304 function set_send_count($user, $reset=false) {
3307 if (empty($user->id
)) {
3308 // No real (DB) user, nothing to do here.
3312 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_send_count'))) {
3313 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3314 $DB->update_record('user_preferences', $pref);
3315 } else if (!empty($reset)) {
3316 // If it's not there and we're resetting, don't bother. Make a new one.
3317 $pref = new stdClass();
3318 $pref->name
= 'email_send_count';
3320 $pref->userid
= $user->id
;
3321 $DB->insert_record('user_preferences', $pref, false);
3326 * Increment or reset user's email bounce count
3328 * @param stdClass $user object containing an id
3329 * @param bool $reset will reset the count to 0
3331 function set_bounce_count($user, $reset=false) {
3334 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_bounce_count'))) {
3335 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3336 $DB->update_record('user_preferences', $pref);
3337 } else if (!empty($reset)) {
3338 // If it's not there and we're resetting, don't bother. Make a new one.
3339 $pref = new stdClass();
3340 $pref->name
= 'email_bounce_count';
3342 $pref->userid
= $user->id
;
3343 $DB->insert_record('user_preferences', $pref, false);
3348 * Determines if the logged in user is currently moving an activity
3350 * @param int $courseid The id of the course being tested
3353 function ismoving($courseid) {
3356 if (!empty($USER->activitycopy
)) {
3357 return ($USER->activitycopycourse
== $courseid);
3363 * Returns a persons full name
3365 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3366 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3369 * @param stdClass $user A {@link $USER} object to get full name of.
3370 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3373 function fullname($user, $override=false) {
3374 global $CFG, $SESSION;
3376 if (!isset($user->firstname
) and !isset($user->lastname
)) {
3380 // Get all of the name fields.
3381 $allnames = get_all_user_name_fields();
3382 if ($CFG->debugdeveloper
) {
3383 foreach ($allnames as $allname) {
3384 if (!property_exists($user, $allname)) {
3385 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3386 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER
);
3387 // Message has been sent, no point in sending the message multiple times.
3394 if (!empty($CFG->forcefirstname
)) {
3395 $user->firstname
= $CFG->forcefirstname
;
3397 if (!empty($CFG->forcelastname
)) {
3398 $user->lastname
= $CFG->forcelastname
;
3402 if (!empty($SESSION->fullnamedisplay
)) {
3403 $CFG->fullnamedisplay
= $SESSION->fullnamedisplay
;
3407 // If the fullnamedisplay setting is available, set the template to that.
3408 if (isset($CFG->fullnamedisplay
)) {
3409 $template = $CFG->fullnamedisplay
;
3411 // If the template is empty, or set to language, return the language string.
3412 if ((empty($template) ||
$template == 'language') && !$override) {
3413 return get_string('fullnamedisplay', null, $user);
3416 // Check to see if we are displaying according to the alternative full name format.
3418 if (empty($CFG->alternativefullnameformat
) ||
$CFG->alternativefullnameformat
== 'language') {
3419 // Default to show just the user names according to the fullnamedisplay string.
3420 return get_string('fullnamedisplay', null, $user);
3422 // If the override is true, then change the template to use the complete name.
3423 $template = $CFG->alternativefullnameformat
;
3427 $requirednames = array();
3428 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3429 foreach ($allnames as $allname) {
3430 if (strpos($template, $allname) !== false) {
3431 $requirednames[] = $allname;
3435 $displayname = $template;
3436 // Switch in the actual data into the template.
3437 foreach ($requirednames as $altname) {
3438 if (isset($user->$altname)) {
3439 // Using empty() on the below if statement causes breakages.
3440 if ((string)$user->$altname == '') {
3441 $displayname = str_replace($altname, 'EMPTY', $displayname);
3443 $displayname = str_replace($altname, $user->$altname, $displayname);
3446 $displayname = str_replace($altname, 'EMPTY', $displayname);
3449 // Tidy up any misc. characters (Not perfect, but gets most characters).
3450 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3451 // katakana and parenthesis.
3452 $patterns = array();
3453 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3454 // filled in by a user.
3455 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3456 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3457 // This regular expression is to remove any double spaces in the display name.
3458 $patterns[] = '/\s{2,}/u';
3459 foreach ($patterns as $pattern) {
3460 $displayname = preg_replace($pattern, ' ', $displayname);
3463 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3464 $displayname = trim($displayname);
3465 if (empty($displayname)) {
3466 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3467 // people in general feel is a good setting to fall back on.
3468 $displayname = $user->firstname
;
3470 return $displayname;
3474 * A centralised location for the all name fields. Returns an array / sql string snippet.
3476 * @param bool $returnsql True for an sql select field snippet.
3477 * @param string $tableprefix table query prefix to use in front of each field.
3478 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3479 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3480 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3481 * @return array|string All name fields.
3483 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3484 // This array is provided in this order because when called by fullname() (above) if firstname is before
3485 // firstnamephonetic str_replace() will change the wrong placeholder.
3486 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3487 'lastnamephonetic' => 'lastnamephonetic',
3488 'middlename' => 'middlename',
3489 'alternatename' => 'alternatename',
3490 'firstname' => 'firstname',
3491 'lastname' => 'lastname');
3493 // Let's add a prefix to the array of user name fields if provided.
3495 foreach ($alternatenames as $key => $altname) {
3496 $alternatenames[$key] = $prefix . $altname;
3500 // If we want the end result to have firstname and lastname at the front / top of the result.
3502 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3503 for ($i = 0; $i < 2; $i++
) {
3504 // Get the last element.
3505 $lastelement = end($alternatenames);
3506 // Remove it from the array.
3507 unset($alternatenames[$lastelement]);
3508 // Put the element back on the top of the array.
3509 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3513 // Create an sql field snippet if requested.
3517 foreach ($alternatenames as $key => $altname) {
3518 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3521 foreach ($alternatenames as $key => $altname) {
3522 $alternatenames[$key] = $tableprefix . '.' . $altname;
3526 $alternatenames = implode(',', $alternatenames);
3528 return $alternatenames;
3532 * Reduces lines of duplicated code for getting user name fields.
3534 * See also {@link user_picture::unalias()}
3536 * @param object $addtoobject Object to add user name fields to.
3537 * @param object $secondobject Object that contains user name field information.
3538 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3539 * @param array $additionalfields Additional fields to be matched with data in the second object.
3540 * The key can be set to the user table field name.
3541 * @return object User name fields.
3543 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3544 $fields = get_all_user_name_fields(false, null, $prefix);
3545 if ($additionalfields) {
3546 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3547 // the key is a number and then sets the key to the array value.
3548 foreach ($additionalfields as $key => $value) {
3549 if (is_numeric($key)) {
3550 $additionalfields[$value] = $prefix . $value;
3551 unset($additionalfields[$key]);
3553 $additionalfields[$key] = $prefix . $value;
3556 $fields = array_merge($fields, $additionalfields);
3558 foreach ($fields as $key => $field) {
3559 // Important that we have all of the user name fields present in the object that we are sending back.
3560 $addtoobject->$key = '';
3561 if (isset($secondobject->$field)) {
3562 $addtoobject->$key = $secondobject->$field;
3565 return $addtoobject;
3569 * Returns an array of values in order of occurance in a provided string.
3570 * The key in the result is the character postion in the string.
3572 * @param array $values Values to be found in the string format
3573 * @param string $stringformat The string which may contain values being searched for.
3574 * @return array An array of values in order according to placement in the string format.
3576 function order_in_string($values, $stringformat) {
3577 $valuearray = array();
3578 foreach ($values as $value) {
3579 $pattern = "/$value\b/";
3580 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3581 if (preg_match($pattern, $stringformat)) {
3582 $replacement = "thing";
3583 // Replace the value with something more unique to ensure we get the right position when using strpos().
3584 $newformat = preg_replace($pattern, $replacement, $stringformat);
3585 $position = strpos($newformat, $replacement);
3586 $valuearray[$position] = $value;
3594 * Checks if current user is shown any extra fields when listing users.
3596 * @param object $context Context
3597 * @param array $already Array of fields that we're going to show anyway
3598 * so don't bother listing them
3599 * @return array Array of field names from user table, not including anything
3600 * listed in $already
3602 function get_extra_user_fields($context, $already = array()) {
3605 // Only users with permission get the extra fields.
3606 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3610 // Split showuseridentity on comma.
3611 if (empty($CFG->showuseridentity
)) {
3612 // Explode gives wrong result with empty string.
3615 $extra = explode(',', $CFG->showuseridentity
);
3618 foreach ($extra as $key => $field) {
3619 if (in_array($field, $already)) {
3620 unset($extra[$key]);
3625 // For consistency, if entries are removed from array, renumber it
3626 // so they are numbered as you would expect.
3627 $extra = array_merge($extra);
3633 * If the current user is to be shown extra user fields when listing or
3634 * selecting users, returns a string suitable for including in an SQL select
3635 * clause to retrieve those fields.
3637 * @param context $context Context
3638 * @param string $alias Alias of user table, e.g. 'u' (default none)
3639 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3640 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3641 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3643 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3644 $fields = get_extra_user_fields($context, $already);
3646 // Add punctuation for alias.
3647 if ($alias !== '') {
3650 foreach ($fields as $field) {
3651 $result .= ', ' . $alias . $field;
3653 $result .= ' AS ' . $prefix . $field;
3660 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3661 * @param string $field Field name, e.g. 'phone1'
3662 * @return string Text description taken from language file, e.g. 'Phone number'
3664 function get_user_field_name($field) {
3665 // Some fields have language strings which are not the same as field name.
3668 return get_string('webpage');
3671 return get_string('icqnumber');
3674 return get_string('skypeid');
3677 return get_string('aimid');
3680 return get_string('yahooid');
3683 return get_string('msnid');
3686 // Otherwise just use the same lang string.
3687 return get_string($field);
3691 * Returns whether a given authentication plugin exists.
3693 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3694 * @return boolean Whether the plugin is available.
3696 function exists_auth_plugin($auth) {
3699 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3700 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3706 * Checks if a given plugin is in the list of enabled authentication plugins.
3708 * @param string $auth Authentication plugin.
3709 * @return boolean Whether the plugin is enabled.
3711 function is_enabled_auth($auth) {
3716 $enabled = get_enabled_auth_plugins();
3718 return in_array($auth, $enabled);
3722 * Returns an authentication plugin instance.
3724 * @param string $auth name of authentication plugin
3725 * @return auth_plugin_base An instance of the required authentication plugin.
3727 function get_auth_plugin($auth) {
3730 // Check the plugin exists first.
3731 if (! exists_auth_plugin($auth)) {
3732 print_error('authpluginnotfound', 'debug', '', $auth);
3735 // Return auth plugin instance.
3736 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3737 $class = "auth_plugin_$auth";
3742 * Returns array of active auth plugins.
3744 * @param bool $fix fix $CFG->auth if needed
3747 function get_enabled_auth_plugins($fix=false) {
3750 $default = array('manual', 'nologin');
3752 if (empty($CFG->auth
)) {
3755 $auths = explode(',', $CFG->auth
);
3759 $auths = array_unique($auths);
3760 foreach ($auths as $k => $authname) {
3761 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3765 $newconfig = implode(',', $auths);
3766 if (!isset($CFG->auth
) or $newconfig != $CFG->auth
) {
3767 set_config('auth', $newconfig);
3771 return (array_merge($default, $auths));
3775 * Returns true if an internal authentication method is being used.
3776 * if method not specified then, global default is assumed
3778 * @param string $auth Form of authentication required
3781 function is_internal_auth($auth) {
3782 // Throws error if bad $auth.
3783 $authplugin = get_auth_plugin($auth);
3784 return $authplugin->is_internal();
3788 * Returns true if the user is a 'restored' one.
3790 * Used in the login process to inform the user and allow him/her to reset the password
3792 * @param string $username username to be checked
3795 function is_restored_user($username) {
3798 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'password' => 'restored'));
3802 * Returns an array of user fields
3804 * @return array User field/column names
3806 function get_user_fieldnames() {
3809 $fieldarray = $DB->get_columns('user');
3810 unset($fieldarray['id']);
3811 $fieldarray = array_keys($fieldarray);
3817 * Creates a bare-bones user record
3819 * @todo Outline auth types and provide code example
3821 * @param string $username New user's username to add to record
3822 * @param string $password New user's password to add to record
3823 * @param string $auth Form of authentication required
3824 * @return stdClass A complete user object
3826 function create_user_record($username, $password, $auth = 'manual') {
3828 require_once($CFG->dirroot
.'/user/profile/lib.php');
3829 require_once($CFG->dirroot
.'/user/lib.php');
3831 // Just in case check text case.
3832 $username = trim(core_text
::strtolower($username));
3834 $authplugin = get_auth_plugin($auth);
3835 $customfields = $authplugin->get_custom_user_profile_fields();
3836 $newuser = new stdClass();
3837 if ($newinfo = $authplugin->get_userinfo($username)) {
3838 $newinfo = truncate_userinfo($newinfo);
3839 foreach ($newinfo as $key => $value) {
3840 if (in_array($key, $authplugin->userfields
) ||
(in_array($key, $customfields))) {
3841 $newuser->$key = $value;
3846 if (!empty($newuser->email
)) {
3847 if (email_is_not_allowed($newuser->email
)) {
3848 unset($newuser->email
);
3852 if (!isset($newuser->city
)) {
3853 $newuser->city
= '';
3856 $newuser->auth
= $auth;
3857 $newuser->username
= $username;
3860 // user CFG lang for user if $newuser->lang is empty
3861 // or $user->lang is not an installed language.
3862 if (empty($newuser->lang
) ||
!get_string_manager()->translation_exists($newuser->lang
)) {
3863 $newuser->lang
= $CFG->lang
;
3865 $newuser->confirmed
= 1;
3866 $newuser->lastip
= getremoteaddr();
3867 $newuser->timecreated
= time();
3868 $newuser->timemodified
= $newuser->timecreated
;
3869 $newuser->mnethostid
= $CFG->mnet_localhost_id
;
3871 $newuser->id
= user_create_user($newuser, false, false);
3873 // Save user profile data.
3874 profile_save_data($newuser);
3876 $user = get_complete_user_data('id', $newuser->id
);
3877 if (!empty($CFG->{'auth_'.$newuser->auth
.'_forcechangepassword'})) {
3878 set_user_preference('auth_forcepasswordchange', 1, $user);
3880 // Set the password.
3881 update_internal_user_password($user, $password);
3884 \core\event\user_created
::create_from_userid($newuser->id
)->trigger();
3890 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3892 * @param string $username user's username to update the record
3893 * @return stdClass A complete user object
3895 function update_user_record($username) {
3897 // Just in case check text case.
3898 $username = trim(core_text
::strtolower($username));
3900 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
), '*', MUST_EXIST
);
3901 return update_user_record_by_id($oldinfo->id
);
3905 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3907 * @param int $id user id
3908 * @return stdClass A complete user object
3910 function update_user_record_by_id($id) {
3912 require_once($CFG->dirroot
."/user/profile/lib.php");
3913 require_once($CFG->dirroot
.'/user/lib.php');
3915 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'id' => $id, 'deleted' => 0);
3916 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST
);
3919 $userauth = get_auth_plugin($oldinfo->auth
);
3921 if ($newinfo = $userauth->get_userinfo($oldinfo->username
)) {
3922 $newinfo = truncate_userinfo($newinfo);
3923 $customfields = $userauth->get_custom_user_profile_fields();
3925 foreach ($newinfo as $key => $value) {
3926 $iscustom = in_array($key, $customfields);
3928 $key = strtolower($key);
3930 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3931 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3932 // Unknown or must not be changed.
3935 $confval = $userauth->config
->{'field_updatelocal_' . $key};
3936 $lockval = $userauth->config
->{'field_lock_' . $key};
3937 if (empty($confval) ||
empty($lockval)) {
3940 if ($confval === 'onlogin') {
3941 // MDL-4207 Don't overwrite modified user profile values with
3942 // empty LDAP values when 'unlocked if empty' is set. The purpose
3943 // of the setting 'unlocked if empty' is to allow the user to fill
3944 // in a value for the selected field _if LDAP is giving
3945 // nothing_ for this field. Thus it makes sense to let this value
3946 // stand in until LDAP is giving a value for this field.
3947 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3948 if ($iscustom ||
(in_array($key, $userauth->userfields
) &&
3949 ((string)$oldinfo->$key !== (string)$value))) {
3950 $newuser[$key] = (string)$value;
3956 $newuser['id'] = $oldinfo->id
;
3957 $newuser['timemodified'] = time();
3958 user_update_user((object) $newuser, false, false);
3960 // Save user profile data.
3961 profile_save_data((object) $newuser);
3964 \core\event\user_updated
::create_from_userid($newuser['id'])->trigger();
3968 return get_complete_user_data('id', $oldinfo->id
);
3972 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
3974 * @param array $info Array of user properties to truncate if needed
3975 * @return array The now truncated information that was passed in
3977 function truncate_userinfo(array $info) {
3978 // Define the limits.
3988 'institution' => 255,
3989 'department' => 255,
3996 // Apply where needed.
3997 foreach (array_keys($info) as $key) {
3998 if (!empty($limit[$key])) {
3999 $info[$key] = trim(core_text
::substr($info[$key], 0, $limit[$key]));
4007 * Marks user deleted in internal user database and notifies the auth plugin.
4008 * Also unenrols user from all roles and does other cleanup.
4010 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4012 * @param stdClass $user full user object before delete
4013 * @return boolean success
4014 * @throws coding_exception if invalid $user parameter detected
4016 function delete_user(stdClass
$user) {
4018 require_once($CFG->libdir
.'/grouplib.php');
4019 require_once($CFG->libdir
.'/gradelib.php');
4020 require_once($CFG->dirroot
.'/message/lib.php');
4021 require_once($CFG->dirroot
.'/user/lib.php');
4023 // Make sure nobody sends bogus record type as parameter.
4024 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4025 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4028 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4029 if (!$user = $DB->get_record('user', array('id' => $user->id
))) {
4030 debugging('Attempt to delete unknown user account.');
4034 // There must be always exactly one guest record, originally the guest account was identified by username only,
4035 // now we use $CFG->siteguest for performance reasons.
4036 if ($user->username
=== 'guest' or isguestuser($user)) {
4037 debugging('Guest user account can not be deleted.');
4041 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4042 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4043 if ($user->auth
=== 'manual' and is_siteadmin($user)) {
4044 debugging('Local administrator accounts can not be deleted.');
4048 // Allow plugins to use this user object before we completely delete it.
4049 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4050 foreach ($pluginsfunction as $plugintype => $plugins) {
4051 foreach ($plugins as $pluginfunction) {
4052 $pluginfunction($user);
4057 // Keep user record before updating it, as we have to pass this to user_deleted event.
4058 $olduser = clone $user;
4060 // Keep a copy of user context, we need it for event.
4061 $usercontext = context_user
::instance($user->id
);
4063 // Delete all grades - backup is kept in grade_grades_history table.
4064 grade_user_delete($user->id
);
4066 // Move unread messages from this user to read.
4067 message_move_userfrom_unread2read($user->id
);
4069 // TODO: remove from cohorts using standard API here.
4071 // Remove user tags.
4072 core_tag_tag
::remove_all_item_tags('core', 'user', $user->id
);
4074 // Unconditionally unenrol from all courses.
4075 enrol_user_delete($user);
4077 // Unenrol from all roles in all contexts.
4078 // This might be slow but it is really needed - modules might do some extra cleanup!
4079 role_unassign_all(array('userid' => $user->id
));
4081 // Now do a brute force cleanup.
4083 // Remove from all cohorts.
4084 $DB->delete_records('cohort_members', array('userid' => $user->id
));
4086 // Remove from all groups.
4087 $DB->delete_records('groups_members', array('userid' => $user->id
));
4089 // Brute force unenrol from all courses.
4090 $DB->delete_records('user_enrolments', array('userid' => $user->id
));
4092 // Purge user preferences.
4093 $DB->delete_records('user_preferences', array('userid' => $user->id
));
4095 // Purge user extra profile info.
4096 $DB->delete_records('user_info_data', array('userid' => $user->id
));
4098 // Purge log of previous password hashes.
4099 $DB->delete_records('user_password_history', array('userid' => $user->id
));
4101 // Last course access not necessary either.
4102 $DB->delete_records('user_lastaccess', array('userid' => $user->id
));
4103 // Remove all user tokens.
4104 $DB->delete_records('external_tokens', array('userid' => $user->id
));
4106 // Unauthorise the user for all services.
4107 $DB->delete_records('external_services_users', array('userid' => $user->id
));
4109 // Remove users private keys.
4110 $DB->delete_records('user_private_key', array('userid' => $user->id
));
4112 // Remove users customised pages.
4113 $DB->delete_records('my_pages', array('userid' => $user->id
, 'private' => 1));
4115 // Force logout - may fail if file based sessions used, sorry.
4116 \core\session\manager
::kill_user_sessions($user->id
);
4118 // Generate username from email address, or a fake email.
4119 $delemail = !empty($user->email
) ?
$user->email
: $user->username
. '.' . $user->id
. '@unknownemail.invalid';
4120 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME
);
4122 // Workaround for bulk deletes of users with the same email address.
4123 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4127 // Mark internal user record as "deleted".
4128 $updateuser = new stdClass();
4129 $updateuser->id
= $user->id
;
4130 $updateuser->deleted
= 1;
4131 $updateuser->username
= $delname; // Remember it just in case.
4132 $updateuser->email
= md5($user->username
);// Store hash of username, useful importing/restoring users.
4133 $updateuser->idnumber
= ''; // Clear this field to free it up.
4134 $updateuser->picture
= 0;
4135 $updateuser->timemodified
= time();
4137 // Don't trigger update event, as user is being deleted.
4138 user_update_user($updateuser, false, false);
4140 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4141 context_helper
::delete_instance(CONTEXT_USER
, $user->id
);
4143 // Any plugin that needs to cleanup should register this event.
4145 $event = \core\event\user_deleted
::create(
4147 'objectid' => $user->id
,
4148 'relateduserid' => $user->id
,
4149 'context' => $usercontext,
4151 'username' => $user->username
,
4152 'email' => $user->email
,
4153 'idnumber' => $user->idnumber
,
4154 'picture' => $user->picture
,
4155 'mnethostid' => $user->mnethostid
4159 $event->add_record_snapshot('user', $olduser);
4162 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4163 // should know about this updated property persisted to the user's table.
4164 $user->timemodified
= $updateuser->timemodified
;
4166 // Notify auth plugin - do not block the delete even when plugin fails.
4167 $authplugin = get_auth_plugin($user->auth
);
4168 $authplugin->user_delete($user);
4174 * Retrieve the guest user object.
4176 * @return stdClass A {@link $USER} object
4178 function guest_user() {
4181 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest
))) {
4182 $newuser->confirmed
= 1;
4183 $newuser->lang
= $CFG->lang
;
4184 $newuser->lastip
= getremoteaddr();
4191 * Authenticates a user against the chosen authentication mechanism
4193 * Given a username and password, this function looks them
4194 * up using the currently selected authentication mechanism,
4195 * and if the authentication is successful, it returns a
4196 * valid $user object from the 'user' table.
4198 * Uses auth_ functions from the currently active auth module
4200 * After authenticate_user_login() returns success, you will need to
4201 * log that the user has logged in, and call complete_user_login() to set
4204 * Note: this function works only with non-mnet accounts!
4206 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4207 * @param string $password User's password
4208 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4209 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4210 * @return stdClass|false A {@link $USER} object or false if error
4212 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4214 require_once("$CFG->libdir/authlib.php");
4216 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id
)) {
4217 // we have found the user
4219 } else if (!empty($CFG->authloginviaemail
)) {
4220 if ($email = clean_param($username, PARAM_EMAIL
)) {
4221 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4222 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'email' => $email);
4223 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4224 if (count($users) === 1) {
4225 // Use email for login only if unique.
4226 $user = reset($users);
4227 $user = get_complete_user_data('id', $user->id
);
4228 $username = $user->username
;
4234 $authsenabled = get_enabled_auth_plugins();
4237 // Use manual if auth not set.
4238 $auth = empty($user->auth
) ?
'manual' : $user->auth
;
4240 if (in_array($user->auth
, $authsenabled)) {
4241 $authplugin = get_auth_plugin($user->auth
);
4242 $authplugin->pre_user_login_hook($user);
4245 if (!empty($user->suspended
)) {
4246 $failurereason = AUTH_LOGIN_SUSPENDED
;
4248 // Trigger login failed event.
4249 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4250 'other' => array('username' => $username, 'reason' => $failurereason)));
4252 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4255 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4256 // Legacy way to suspend user.
4257 $failurereason = AUTH_LOGIN_SUSPENDED
;
4259 // Trigger login failed event.
4260 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4261 'other' => array('username' => $username, 'reason' => $failurereason)));
4263 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4266 $auths = array($auth);
4269 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4270 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'deleted' => 1))) {
4271 $failurereason = AUTH_LOGIN_NOUSER
;
4273 // Trigger login failed event.
4274 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4275 'reason' => $failurereason)));
4277 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4281 // User does not exist.
4282 $auths = $authsenabled;
4283 $user = new stdClass();
4287 if ($ignorelockout) {
4288 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4289 // or this function is called from a SSO script.
4290 } else if ($user->id
) {
4291 // Verify login lockout after other ways that may prevent user login.
4292 if (login_is_lockedout($user)) {
4293 $failurereason = AUTH_LOGIN_LOCKOUT
;
4295 // Trigger login failed event.
4296 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4297 'other' => array('username' => $username, 'reason' => $failurereason)));
4300 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4304 // We can not lockout non-existing accounts.
4307 foreach ($auths as $auth) {
4308 $authplugin = get_auth_plugin($auth);
4310 // On auth fail fall through to the next plugin.
4311 if (!$authplugin->user_login($username, $password)) {
4315 // Successful authentication.
4317 // User already exists in database.
4318 if (empty($user->auth
)) {
4319 // For some reason auth isn't set yet.
4320 $DB->set_field('user', 'auth', $auth, array('id' => $user->id
));
4321 $user->auth
= $auth;
4324 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4325 // the current hash algorithm while we have access to the user's password.
4326 update_internal_user_password($user, $password);
4328 if ($authplugin->is_synchronised_with_external()) {
4329 // Update user record from external DB.
4330 $user = update_user_record_by_id($user->id
);
4333 // The user is authenticated but user creation may be disabled.
4334 if (!empty($CFG->authpreventaccountcreation
)) {
4335 $failurereason = AUTH_LOGIN_UNAUTHORISED
;
4337 // Trigger login failed event.
4338 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4339 'reason' => $failurereason)));
4342 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4343 $_SERVER['HTTP_USER_AGENT']);
4346 $user = create_user_record($username, $password, $auth);
4350 $authplugin->sync_roles($user);
4352 foreach ($authsenabled as $hau) {
4353 $hauth = get_auth_plugin($hau);
4354 $hauth->user_authenticated_hook($user, $username, $password);
4357 if (empty($user->id
)) {
4358 $failurereason = AUTH_LOGIN_NOUSER
;
4359 // Trigger login failed event.
4360 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4361 'reason' => $failurereason)));
4366 if (!empty($user->suspended
)) {
4367 // Just in case some auth plugin suspended account.
4368 $failurereason = AUTH_LOGIN_SUSPENDED
;
4369 // Trigger login failed event.
4370 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4371 'other' => array('username' => $username, 'reason' => $failurereason)));
4373 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4377 login_attempt_valid($user);
4378 $failurereason = AUTH_LOGIN_OK
;
4382 // Failed if all the plugins have failed.
4383 if (debugging('', DEBUG_ALL
)) {
4384 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4388 login_attempt_failed($user);
4389 $failurereason = AUTH_LOGIN_FAILED
;
4390 // Trigger login failed event.
4391 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4392 'other' => array('username' => $username, 'reason' => $failurereason)));
4395 $failurereason = AUTH_LOGIN_NOUSER
;
4396 // Trigger login failed event.
4397 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4398 'reason' => $failurereason)));
4406 * Call to complete the user login process after authenticate_user_login()
4407 * has succeeded. It will setup the $USER variable and other required bits
4411 * - It will NOT log anything -- up to the caller to decide what to log.
4412 * - this function does not set any cookies any more!
4414 * @param stdClass $user
4415 * @return stdClass A {@link $USER} object - BC only, do not use
4417 function complete_user_login($user) {
4418 global $CFG, $USER, $SESSION;
4420 \core\session\manager
::login_user($user);
4422 // Reload preferences from DB.
4423 unset($USER->preference
);
4424 check_user_preferences_loaded($USER);
4426 // Update login times.
4427 update_user_login_times();
4429 // Extra session prefs init.
4430 set_login_session_preferences();
4432 // Trigger login event.
4433 $event = \core\event\user_loggedin
::create(
4435 'userid' => $USER->id
,
4436 'objectid' => $USER->id
,
4437 'other' => array('username' => $USER->username
),
4442 if (isguestuser()) {
4443 // No need to continue when user is THE guest.
4448 // We can redirect to password change URL only in browser.
4452 // Select password change url.
4453 $userauth = get_auth_plugin($USER->auth
);
4455 // Check whether the user should be changing password.
4456 if (get_user_preferences('auth_forcepasswordchange', false)) {
4457 if ($userauth->can_change_password()) {
4458 if ($changeurl = $userauth->change_password_url()) {
4459 redirect($changeurl);
4461 require_once($CFG->dirroot
. '/login/lib.php');
4462 $SESSION->wantsurl
= core_login_get_return_url();
4463 redirect($CFG->httpswwwroot
.'/login/change_password.php');
4466 print_error('nopasswordchangeforced', 'auth');
4473 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4475 * @param string $password String to check.
4476 * @return boolean True if the $password matches the format of an md5 sum.
4478 function password_is_legacy_hash($password) {
4479 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4483 * Compare password against hash stored in user object to determine if it is valid.
4485 * If necessary it also updates the stored hash to the current format.
4487 * @param stdClass $user (Password property may be updated).
4488 * @param string $password Plain text password.
4489 * @return bool True if password is valid.
4491 function validate_internal_user_password($user, $password) {
4494 if ($user->password
=== AUTH_PASSWORD_NOT_CACHED
) {
4495 // Internal password is not used at all, it can not validate.
4499 // If hash isn't a legacy (md5) hash, validate using the library function.
4500 if (!password_is_legacy_hash($user->password
)) {
4501 return password_verify($password, $user->password
);
4504 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4505 // is valid we can then update it to the new algorithm.
4507 $sitesalt = isset($CFG->passwordsaltmain
) ?
$CFG->passwordsaltmain
: '';
4510 if ($user->password
=== md5($password.$sitesalt)
4511 or $user->password
=== md5($password)
4512 or $user->password
=== md5(addslashes($password).$sitesalt)
4513 or $user->password
=== md5(addslashes($password))) {
4514 // Note: we are intentionally using the addslashes() here because we
4515 // need to accept old password hashes of passwords with magic quotes.
4519 for ($i=1; $i<=20; $i++
) { // 20 alternative salts should be enough, right?
4520 $alt = 'passwordsaltalt'.$i;
4521 if (!empty($CFG->$alt)) {
4522 if ($user->password
=== md5($password.$CFG->$alt) or $user->password
=== md5(addslashes($password).$CFG->$alt)) {
4531 // If the password matches the existing md5 hash, update to the
4532 // current hash algorithm while we have access to the user's password.
4533 update_internal_user_password($user, $password);
4540 * Calculate hash for a plain text password.
4542 * @param string $password Plain text password to be hashed.
4543 * @param bool $fasthash If true, use a low cost factor when generating the hash
4544 * This is much faster to generate but makes the hash
4545 * less secure. It is used when lots of hashes need to
4546 * be generated quickly.
4547 * @return string The hashed password.
4549 * @throws moodle_exception If a problem occurs while generating the hash.
4551 function hash_internal_user_password($password, $fasthash = false) {
4554 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4555 $options = ($fasthash) ?
array('cost' => 4) : array();
4557 $generatedhash = password_hash($password, PASSWORD_DEFAULT
, $options);
4559 if ($generatedhash === false ||
$generatedhash === null) {
4560 throw new moodle_exception('Failed to generate password hash.');
4563 return $generatedhash;
4567 * Update password hash in user object (if necessary).
4569 * The password is updated if:
4570 * 1. The password has changed (the hash of $user->password is different
4571 * to the hash of $password).
4572 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4575 * Updating the password will modify the $user object and the database
4576 * record to use the current hashing algorithm.
4577 * It will remove Web Services user tokens too.
4579 * @param stdClass $user User object (password property may be updated).
4580 * @param string $password Plain text password.
4581 * @param bool $fasthash If true, use a low cost factor when generating the hash
4582 * This is much faster to generate but makes the hash
4583 * less secure. It is used when lots of hashes need to
4584 * be generated quickly.
4585 * @return bool Always returns true.
4587 function update_internal_user_password($user, $password, $fasthash = false) {
4590 // Figure out what the hashed password should be.
4591 if (!isset($user->auth
)) {
4592 debugging('User record in update_internal_user_password() must include field auth',
4594 $user->auth
= $DB->get_field('user', 'auth', array('id' => $user->id
));
4596 $authplugin = get_auth_plugin($user->auth
);
4597 if ($authplugin->prevent_local_passwords()) {
4598 $hashedpassword = AUTH_PASSWORD_NOT_CACHED
;
4600 $hashedpassword = hash_internal_user_password($password, $fasthash);
4603 $algorithmchanged = false;
4605 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED
) {
4606 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4607 $passwordchanged = ($user->password
!== $hashedpassword);
4609 } else if (isset($user->password
)) {
4610 // If verification fails then it means the password has changed.
4611 $passwordchanged = !password_verify($password, $user->password
);
4612 $algorithmchanged = password_needs_rehash($user->password
, PASSWORD_DEFAULT
);
4614 // While creating new user, password in unset in $user object, to avoid
4615 // saving it with user_create()
4616 $passwordchanged = true;
4619 if ($passwordchanged ||
$algorithmchanged) {
4620 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id
));
4621 $user->password
= $hashedpassword;
4624 $user = $DB->get_record('user', array('id' => $user->id
));
4625 \core\event\user_password_updated
::create_from_user($user)->trigger();
4627 // Remove WS user tokens.
4628 if (!empty($CFG->passwordchangetokendeletion
)) {
4629 require_once($CFG->dirroot
.'/webservice/lib.php');
4630 webservice
::delete_user_ws_tokens($user->id
);
4638 * Get a complete user record, which includes all the info in the user record.
4640 * Intended for setting as $USER session variable
4642 * @param string $field The user field to be checked for a given value.
4643 * @param string $value The value to match for $field.
4644 * @param int $mnethostid
4645 * @return mixed False, or A {@link $USER} object.
4647 function get_complete_user_data($field, $value, $mnethostid = null) {
4650 if (!$field ||
!$value) {
4654 // Build the WHERE clause for an SQL query.
4655 $params = array('fieldval' => $value);
4656 $constraints = "$field = :fieldval AND deleted <> 1";
4658 // If we are loading user data based on anything other than id,
4659 // we must also restrict our search based on mnet host.
4660 if ($field != 'id') {
4661 if (empty($mnethostid)) {
4662 // If empty, we restrict to local users.
4663 $mnethostid = $CFG->mnet_localhost_id
;
4666 if (!empty($mnethostid)) {
4667 $params['mnethostid'] = $mnethostid;
4668 $constraints .= " AND mnethostid = :mnethostid";
4671 // Get all the basic user data.
4672 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4676 // Get various settings and preferences.
4678 // Preload preference cache.
4679 check_user_preferences_loaded($user);
4681 // Load course enrolment related stuff.
4682 $user->lastcourseaccess
= array(); // During last session.
4683 $user->currentcourseaccess
= array(); // During current session.
4684 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id
))) {
4685 foreach ($lastaccesses as $lastaccess) {
4686 $user->lastcourseaccess
[$lastaccess->courseid
] = $lastaccess->timeaccess
;
4690 $sql = "SELECT g.id, g.courseid
4691 FROM {groups} g, {groups_members} gm
4692 WHERE gm.groupid=g.id AND gm.userid=?";
4694 // This is a special hack to speedup calendar display.
4695 $user->groupmember
= array();
4696 if (!isguestuser($user)) {
4697 if ($groups = $DB->get_records_sql($sql, array($user->id
))) {
4698 foreach ($groups as $group) {
4699 if (!array_key_exists($group->courseid
, $user->groupmember
)) {
4700 $user->groupmember
[$group->courseid
] = array();
4702 $user->groupmember
[$group->courseid
][$group->id
] = $group->id
;
4707 // Add the custom profile fields to the user record.
4708 $user->profile
= array();
4709 if (!isguestuser($user)) {
4710 require_once($CFG->dirroot
.'/user/profile/lib.php');
4711 profile_load_custom_fields($user);
4714 // Rewrite some variables if necessary.
4715 if (!empty($user->description
)) {
4716 // No need to cart all of it around.
4717 $user->description
= true;
4719 if (isguestuser($user)) {
4720 // Guest language always same as site.
4721 $user->lang
= $CFG->lang
;
4722 // Name always in current language.
4723 $user->firstname
= get_string('guestuser');
4724 $user->lastname
= ' ';
4731 * Validate a password against the configured password policy
4733 * @param string $password the password to be checked against the password policy
4734 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4735 * @return bool true if the password is valid according to the policy. false otherwise.
4737 function check_password_policy($password, &$errmsg) {
4740 if (empty($CFG->passwordpolicy
)) {
4745 if (core_text
::strlen($password) < $CFG->minpasswordlength
) {
4746 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength
) .'</div>';
4749 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits
) {
4750 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits
) .'</div>';
4753 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower
) {
4754 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower
) .'</div>';
4757 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper
) {
4758 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper
) .'</div>';
4761 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum
) {
4762 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
) .'</div>';
4764 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars
)) {
4765 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars
) .'</div>';
4768 if ($errmsg == '') {
4777 * When logging in, this function is run to set certain preferences for the current SESSION.
4779 function set_login_session_preferences() {
4782 $SESSION->justloggedin
= true;
4784 unset($SESSION->lang
);
4785 unset($SESSION->forcelang
);
4786 unset($SESSION->load_navigation_admin
);
4791 * Delete a course, including all related data from the database, and any associated files.
4793 * @param mixed $courseorid The id of the course or course object to delete.
4794 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4795 * @return bool true if all the removals succeeded. false if there were any failures. If this
4796 * method returns false, some of the removals will probably have succeeded, and others
4797 * failed, but you have no way of knowing which.
4799 function delete_course($courseorid, $showfeedback = true) {
4802 if (is_object($courseorid)) {
4803 $courseid = $courseorid->id
;
4804 $course = $courseorid;
4806 $courseid = $courseorid;
4807 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4811 $context = context_course
::instance($courseid);
4813 // Frontpage course can not be deleted!!
4814 if ($courseid == SITEID
) {
4818 // Allow plugins to use this course before we completely delete it.
4819 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
4820 foreach ($pluginsfunction as $plugintype => $plugins) {
4821 foreach ($plugins as $pluginfunction) {
4822 $pluginfunction($course);
4827 // Make the course completely empty.
4828 remove_course_contents($courseid, $showfeedback);
4830 // Delete the course and related context instance.
4831 context_helper
::delete_instance(CONTEXT_COURSE
, $courseid);
4833 $DB->delete_records("course", array("id" => $courseid));
4834 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4836 // Reset all course related caches here.
4837 if (class_exists('format_base', false)) {
4838 format_base
::reset_course_cache($courseid);
4841 // Trigger a course deleted event.
4842 $event = \core\event\course_deleted
::create(array(
4843 'objectid' => $course->id
,
4844 'context' => $context,
4846 'shortname' => $course->shortname
,
4847 'fullname' => $course->fullname
,
4848 'idnumber' => $course->idnumber
4851 $event->add_record_snapshot('course', $course);
4858 * Clear a course out completely, deleting all content but don't delete the course itself.
4860 * This function does not verify any permissions.
4862 * Please note this function also deletes all user enrolments,
4863 * enrolment instances and role assignments by default.
4866 * - 'keep_roles_and_enrolments' - false by default
4867 * - 'keep_groups_and_groupings' - false by default
4869 * @param int $courseid The id of the course that is being deleted
4870 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4871 * @param array $options extra options
4872 * @return bool true if all the removals succeeded. false if there were any failures. If this
4873 * method returns false, some of the removals will probably have succeeded, and others
4874 * failed, but you have no way of knowing which.
4876 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4877 global $CFG, $DB, $OUTPUT;
4879 require_once($CFG->libdir
.'/badgeslib.php');
4880 require_once($CFG->libdir
.'/completionlib.php');
4881 require_once($CFG->libdir
.'/questionlib.php');
4882 require_once($CFG->libdir
.'/gradelib.php');
4883 require_once($CFG->dirroot
.'/group/lib.php');
4884 require_once($CFG->dirroot
.'/comment/lib.php');
4885 require_once($CFG->dirroot
.'/rating/lib.php');
4886 require_once($CFG->dirroot
.'/notes/lib.php');
4888 // Handle course badges.
4889 badges_handle_course_deletion($courseid);
4891 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4892 $strdeleted = get_string('deleted').' - ';
4894 // Some crazy wishlist of stuff we should skip during purging of course content.
4895 $options = (array)$options;
4897 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST
);
4898 $coursecontext = context_course
::instance($courseid);
4899 $fs = get_file_storage();
4901 // Delete course completion information, this has to be done before grades and enrols.
4902 $cc = new completion_info($course);
4903 $cc->clear_criteria();
4904 if ($showfeedback) {
4905 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4908 // Remove all data from gradebook - this needs to be done before course modules
4909 // because while deleting this information, the system may need to reference
4910 // the course modules that own the grades.
4911 remove_course_grades($courseid, $showfeedback);
4912 remove_grade_letters($coursecontext, $showfeedback);
4914 // Delete course blocks in any all child contexts,
4915 // they may depend on modules so delete them first.
4916 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4917 foreach ($childcontexts as $childcontext) {
4918 blocks_delete_all_for_context($childcontext->id
);
4920 unset($childcontexts);
4921 blocks_delete_all_for_context($coursecontext->id
);
4922 if ($showfeedback) {
4923 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4926 // Get the list of all modules that are properly installed.
4927 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
4929 // Delete every instance of every module,
4930 // this has to be done before deleting of course level stuff.
4931 $locations = core_component
::get_plugin_list('mod');
4932 foreach ($locations as $modname => $moddir) {
4933 if ($modname === 'NEWMODULE') {
4936 if (array_key_exists($modname, $allmodules)) {
4937 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
4938 FROM {".$modname."} m
4939 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
4940 WHERE m.course = :courseid";
4941 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id
,
4942 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
4944 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
4945 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
4946 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
4949 foreach ($instances as $cm) {
4951 // Delete activity context questions and question categories.
4952 question_delete_activity($cm, $showfeedback);
4953 // Notify the competency subsystem.
4954 \core_competency\api
::hook_course_module_deleted($cm);
4956 if (function_exists($moddelete)) {
4957 // This purges all module data in related tables, extra user prefs, settings, etc.
4958 $moddelete($cm->modinstance
);
4960 // NOTE: we should not allow installation of modules with missing delete support!
4961 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
4962 $DB->delete_records($modname, array('id' => $cm->modinstance
));
4966 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
4967 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
4968 $DB->delete_records('course_modules', array('id' => $cm->id
));
4972 if (function_exists($moddeletecourse)) {
4973 // Execute optional course cleanup callback. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
4974 debugging("Callback delete_course is deprecated. Function $moddeletecourse should be converted " .
4975 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER
);
4976 $moddeletecourse($course, $showfeedback);
4978 if ($instances and $showfeedback) {
4979 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
4982 // Ooops, this module is not properly installed, force-delete it in the next block.
4986 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
4988 // Remove all data from availability and completion tables that is associated
4989 // with course-modules belonging to this course. Note this is done even if the
4990 // features are not enabled now, in case they were enabled previously.
4991 $DB->delete_records_select('course_modules_completion',
4992 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4995 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
4996 $cms = $DB->get_records('course_modules', array('course' => $course->id
));
4997 $allmodulesbyid = array_flip($allmodules);
4998 foreach ($cms as $cm) {
4999 if (array_key_exists($cm->module
, $allmodulesbyid)) {
5001 $DB->delete_records($allmodulesbyid[$cm->module
], array('id' => $cm->instance
));
5002 } catch (Exception
$e) {
5003 // Ignore weird or missing table problems.
5006 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
5007 $DB->delete_records('course_modules', array('id' => $cm->id
));
5010 if ($showfeedback) {
5011 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5014 // Cleanup the rest of plugins. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
5015 $cleanuplugintypes = array('report', 'coursereport', 'format');
5016 $callbacks = get_plugins_with_function('delete_course', 'lib.php');
5017 foreach ($cleanuplugintypes as $type) {
5018 if (!empty($callbacks[$type])) {
5019 foreach ($callbacks[$type] as $pluginfunction) {
5020 debugging("Callback delete_course is deprecated. Function $pluginfunction should be converted " .
5021 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER
);
5022 $pluginfunction($course->id
, $showfeedback);
5024 if ($showfeedback) {
5025 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5030 // Delete questions and question categories.
5031 question_delete_course($course, $showfeedback);
5032 if ($showfeedback) {
5033 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5036 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5037 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5038 foreach ($childcontexts as $childcontext) {
5039 $childcontext->delete();
5041 unset($childcontexts);
5043 // Remove all roles and enrolments by default.
5044 if (empty($options['keep_roles_and_enrolments'])) {
5045 // This hack is used in restore when deleting contents of existing course.
5046 role_unassign_all(array('contextid' => $coursecontext->id
, 'component' => ''), true);
5047 enrol_course_delete($course);
5048 if ($showfeedback) {
5049 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5053 // Delete any groups, removing members and grouping/course links first.
5054 if (empty($options['keep_groups_and_groupings'])) {
5055 groups_delete_groupings($course->id
, $showfeedback);
5056 groups_delete_groups($course->id
, $showfeedback);
5060 filter_delete_all_for_context($coursecontext->id
);
5062 // Notes, you shall not pass!
5063 note_delete_all($course->id
);
5066 comment
::delete_comments($coursecontext->id
);
5068 // Ratings are history too.
5069 $delopt = new stdclass();
5070 $delopt->contextid
= $coursecontext->id
;
5071 $rm = new rating_manager();
5072 $rm->delete_ratings($delopt);
5074 // Delete course tags.
5075 core_tag_tag
::remove_all_item_tags('core', 'course', $course->id
);
5077 // Notify the competency subsystem.
5078 \core_competency\api
::hook_course_deleted($course);
5080 // Delete calendar events.
5081 $DB->delete_records('event', array('courseid' => $course->id
));
5082 $fs->delete_area_files($coursecontext->id
, 'calendar');
5084 // Delete all related records in other core tables that may have a courseid
5085 // This array stores the tables that need to be cleared, as
5086 // table_name => column_name that contains the course id.
5087 $tablestoclear = array(
5088 'backup_courses' => 'courseid', // Scheduled backup stuff.
5089 'user_lastaccess' => 'courseid', // User access info.
5091 foreach ($tablestoclear as $table => $col) {
5092 $DB->delete_records($table, array($col => $course->id
));
5095 // Delete all course backup files.
5096 $fs->delete_area_files($coursecontext->id
, 'backup');
5098 // Cleanup course record - remove links to deleted stuff.
5099 $oldcourse = new stdClass();
5100 $oldcourse->id
= $course->id
;
5101 $oldcourse->summary
= '';
5102 $oldcourse->cacherev
= 0;
5103 $oldcourse->legacyfiles
= 0;
5104 if (!empty($options['keep_groups_and_groupings'])) {
5105 $oldcourse->defaultgroupingid
= 0;
5107 $DB->update_record('course', $oldcourse);
5109 // Delete course sections.
5110 $DB->delete_records('course_sections', array('course' => $course->id
));
5112 // Delete legacy, section and any other course files.
5113 $fs->delete_area_files($coursecontext->id
, 'course'); // Files from summary and section.
5115 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5116 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5117 // Easy, do not delete the context itself...
5118 $coursecontext->delete_content();
5121 // We can not drop all context stuff because it would bork enrolments and roles,
5122 // there might be also files used by enrol plugins...
5125 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5126 // also some non-standard unsupported plugins may try to store something there.
5127 fulldelete($CFG->dataroot
.'/'.$course->id
);
5129 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5130 $cachemodinfo = cache
::make('core', 'coursemodinfo');
5131 $cachemodinfo->delete($courseid);
5133 // Trigger a course content deleted event.
5134 $event = \core\event\course_content_deleted
::create(array(
5135 'objectid' => $course->id
,
5136 'context' => $coursecontext,
5137 'other' => array('shortname' => $course->shortname
,
5138 'fullname' => $course->fullname
,
5139 'options' => $options) // Passing this for legacy reasons.
5141 $event->add_record_snapshot('course', $course);
5148 * Change dates in module - used from course reset.
5150 * @param string $modname forum, assignment, etc
5151 * @param array $fields array of date fields from mod table
5152 * @param int $timeshift time difference
5153 * @param int $courseid
5154 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5155 * @return bool success
5157 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5159 include_once($CFG->dirroot
.'/mod/'.$modname.'/lib.php');
5162 $params = array($timeshift, $courseid);
5163 foreach ($fields as $field) {
5164 $updatesql = "UPDATE {".$modname."}
5165 SET $field = $field + ?
5166 WHERE course=? AND $field<>0";
5168 $updatesql .= ' AND id=?';
5171 $return = $DB->execute($updatesql, $params) && $return;
5174 $refreshfunction = $modname.'_refresh_events';
5175 if (function_exists($refreshfunction)) {
5176 $refreshfunction($courseid);
5183 * This function will empty a course of user data.
5184 * It will retain the activities and the structure of the course.
5186 * @param object $data an object containing all the settings including courseid (without magic quotes)
5187 * @return array status array of array component, item, error
5189 function reset_course_userdata($data) {
5191 require_once($CFG->libdir
.'/gradelib.php');
5192 require_once($CFG->libdir
.'/completionlib.php');
5193 require_once($CFG->dirroot
.'/completion/criteria/completion_criteria_date.php');
5194 require_once($CFG->dirroot
.'/group/lib.php');
5196 $data->courseid
= $data->id
;
5197 $context = context_course
::instance($data->courseid
);
5199 $eventparams = array(
5200 'context' => $context,
5201 'courseid' => $data->id
,
5203 'reset_options' => (array) $data
5206 $event = \core\event\course_reset_started
::create($eventparams);
5209 // Calculate the time shift of dates.
5210 if (!empty($data->reset_start_date
)) {
5211 // Time part of course startdate should be zero.
5212 $data->timeshift
= $data->reset_start_date
- usergetmidnight($data->reset_start_date_old
);
5214 $data->timeshift
= 0;
5217 // Result array: component, item, error.
5220 // Start the resetting.
5221 $componentstr = get_string('general');
5223 // Move the course start time.
5224 if (!empty($data->reset_start_date
) and $data->timeshift
) {
5225 // Change course start data.
5226 $DB->set_field('course', 'startdate', $data->reset_start_date
, array('id' => $data->courseid
));
5227 // Update all course and group events - do not move activity events.
5228 $updatesql = "UPDATE {event}
5229 SET timestart = timestart + ?
5230 WHERE courseid=? AND instance=0";
5231 $DB->execute($updatesql, array($data->timeshift
, $data->courseid
));
5233 // Update any date activity restrictions.
5234 if ($CFG->enableavailability
) {
5235 \availability_date\condition
::update_all_dates($data->courseid
, $data->timeshift
);
5238 // Update completion expected dates.
5239 if ($CFG->enablecompletion
) {
5240 $modinfo = get_fast_modinfo($data->courseid
);
5242 foreach ($modinfo->get_cms() as $cm) {
5243 if ($cm->completion
&& !empty($cm->completionexpected
)) {
5244 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected +
$data->timeshift
,
5245 array('id' => $cm->id
));
5250 // Clear course cache if changes made.
5252 rebuild_course_cache($data->courseid
, true);
5255 // Update course date completion criteria.
5256 \completion_criteria_date
::update_date($data->courseid
, $data->timeshift
);
5259 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5262 if (!empty($data->reset_end_date
)) {
5263 // If the user set a end date value respect it.
5264 $DB->set_field('course', 'enddate', $data->reset_end_date
, array('id' => $data->courseid
));
5265 } else if ($data->timeshift
> 0 && $data->reset_end_date_old
) {
5266 // If there is a time shift apply it to the end date as well.
5267 $enddate = $data->reset_end_date_old +
$data->timeshift
;
5268 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid
));
5271 if (!empty($data->reset_events
)) {
5272 $DB->delete_records('event', array('courseid' => $data->courseid
));
5273 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5276 if (!empty($data->reset_notes
)) {
5277 require_once($CFG->dirroot
.'/notes/lib.php');
5278 note_delete_all($data->courseid
);
5279 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5282 if (!empty($data->delete_blog_associations
)) {
5283 require_once($CFG->dirroot
.'/blog/lib.php');
5284 blog_remove_associations_for_course($data->courseid
);
5285 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5288 if (!empty($data->reset_completion
)) {
5289 // Delete course and activity completion information.
5290 $course = $DB->get_record('course', array('id' => $data->courseid
));
5291 $cc = new completion_info($course);
5292 $cc->delete_all_completion_data();
5293 $status[] = array('component' => $componentstr,
5294 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5297 if (!empty($data->reset_competency_ratings
)) {
5298 \core_competency\api
::hook_course_reset_competency_ratings($data->courseid
);
5299 $status[] = array('component' => $componentstr,
5300 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5303 $componentstr = get_string('roles');
5305 if (!empty($data->reset_roles_overrides
)) {
5306 $children = $context->get_child_contexts();
5307 foreach ($children as $child) {
5308 $DB->delete_records('role_capabilities', array('contextid' => $child->id
));
5310 $DB->delete_records('role_capabilities', array('contextid' => $context->id
));
5311 // Force refresh for logged in users.
5312 $context->mark_dirty();
5313 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5316 if (!empty($data->reset_roles_local
)) {
5317 $children = $context->get_child_contexts();
5318 foreach ($children as $child) {
5319 role_unassign_all(array('contextid' => $child->id
));
5321 // Force refresh for logged in users.
5322 $context->mark_dirty();
5323 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5326 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5327 $data->unenrolled
= array();
5328 if (!empty($data->unenrol_users
)) {
5329 $plugins = enrol_get_plugins(true);
5330 $instances = enrol_get_instances($data->courseid
, true);
5331 foreach ($instances as $key => $instance) {
5332 if (!isset($plugins[$instance->enrol
])) {
5333 unset($instances[$key]);
5338 foreach ($data->unenrol_users
as $withroleid) {
5341 FROM {user_enrolments} ue
5342 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5343 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5344 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5345 $params = array('courseid' => $data->courseid
, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE
);
5348 // Without any role assigned at course context.
5350 FROM {user_enrolments} ue
5351 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5352 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5353 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5354 WHERE ra.id IS null";
5355 $params = array('courseid' => $data->courseid
, 'courselevel' => CONTEXT_COURSE
);
5358 $rs = $DB->get_recordset_sql($sql, $params);
5359 foreach ($rs as $ue) {
5360 if (!isset($instances[$ue->enrolid
])) {
5363 $instance = $instances[$ue->enrolid
];
5364 $plugin = $plugins[$instance->enrol
];
5365 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5369 $plugin->unenrol_user($instance, $ue->userid
);
5370 $data->unenrolled
[$ue->userid
] = $ue->userid
;
5375 if (!empty($data->unenrolled
)) {
5377 'component' => $componentstr,
5378 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled
).')',
5383 $componentstr = get_string('groups');
5385 // Remove all group members.
5386 if (!empty($data->reset_groups_members
)) {
5387 groups_delete_group_members($data->courseid
);
5388 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5391 // Remove all groups.
5392 if (!empty($data->reset_groups_remove
)) {
5393 groups_delete_groups($data->courseid
, false);
5394 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5397 // Remove all grouping members.
5398 if (!empty($data->reset_groupings_members
)) {
5399 groups_delete_groupings_groups($data->courseid
, false);
5400 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5403 // Remove all groupings.
5404 if (!empty($data->reset_groupings_remove
)) {
5405 groups_delete_groupings($data->courseid
, false);
5406 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5409 // Look in every instance of every module for data to delete.
5410 $unsupportedmods = array();
5411 if ($allmods = $DB->get_records('modules') ) {
5412 foreach ($allmods as $mod) {
5413 $modname = $mod->name
;
5414 $modfile = $CFG->dirroot
.'/mod/'. $modname.'/lib.php';
5415 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5416 if (file_exists($modfile)) {
5417 if (!$DB->count_records($modname, array('course' => $data->courseid
))) {
5418 continue; // Skip mods with no instances.
5420 include_once($modfile);
5421 if (function_exists($moddeleteuserdata)) {
5422 $modstatus = $moddeleteuserdata($data);
5423 if (is_array($modstatus)) {
5424 $status = array_merge($status, $modstatus);
5426 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5429 $unsupportedmods[] = $mod;
5432 debugging('Missing lib.php in '.$modname.' module!');
5437 // Mention unsupported mods.
5438 if (!empty($unsupportedmods)) {
5439 foreach ($unsupportedmods as $mod) {
5441 'component' => get_string('modulenameplural', $mod->name
),
5443 'error' => get_string('resetnotimplemented')
5448 $componentstr = get_string('gradebook', 'grades');
5449 // Reset gradebook,.
5450 if (!empty($data->reset_gradebook_items
)) {
5451 remove_course_grades($data->courseid
, false);
5452 grade_grab_course_grades($data->courseid
);
5453 grade_regrade_final_grades($data->courseid
);
5454 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5456 } else if (!empty($data->reset_gradebook_grades
)) {
5457 grade_course_reset($data->courseid
);
5458 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5461 if (!empty($data->reset_comments
)) {
5462 require_once($CFG->dirroot
.'/comment/lib.php');
5463 comment
::reset_course_page_comments($context);
5466 $event = \core\event\course_reset_ended
::create($eventparams);
5473 * Generate an email processing address.
5476 * @param string $modargs
5477 * @return string Returns email processing address
5479 function generate_email_processing_address($modid, $modargs) {
5482 $header = $CFG->mailprefix
. substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5483 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain
;
5489 * @todo Finish documenting this function
5491 * @param string $modargs
5492 * @param string $body Currently unused
5494 function moodle_process_email($modargs, $body) {
5497 // The first char should be an unencoded letter. We'll take this as an action.
5498 switch ($modargs{0}) {
5499 case 'B': { // Bounce.
5500 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5501 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5502 // Check the half md5 of their email.
5503 $md5check = substr(md5($user->email
), 0, 16);
5504 if ($md5check == substr($modargs, -16)) {
5505 set_bounce_count($user);
5507 // Else maybe they've already changed it?
5511 // Maybe more later?
5518 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5520 * @param string $action 'get', 'buffer', 'close' or 'flush'
5521 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5523 function get_mailer($action='get') {
5526 /** @var moodle_phpmailer $mailer */
5527 static $mailer = null;
5528 static $counter = 0;
5530 if (!isset($CFG->smtpmaxbulk
)) {
5531 $CFG->smtpmaxbulk
= 1;
5534 if ($action == 'get') {
5535 $prevkeepalive = false;
5537 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5538 if ($counter < $CFG->smtpmaxbulk
and !$mailer->isError()) {
5540 // Reset the mailer.
5541 $mailer->Priority
= 3;
5542 $mailer->CharSet
= 'UTF-8'; // Our default.
5543 $mailer->ContentType
= "text/plain";
5544 $mailer->Encoding
= "8bit";
5545 $mailer->From
= "root@localhost";
5546 $mailer->FromName
= "Root User";
5547 $mailer->Sender
= "";
5548 $mailer->Subject
= "";
5550 $mailer->AltBody
= "";
5551 $mailer->ConfirmReadingTo
= "";
5553 $mailer->clearAllRecipients();
5554 $mailer->clearReplyTos();
5555 $mailer->clearAttachments();
5556 $mailer->clearCustomHeaders();
5560 $prevkeepalive = $mailer->SMTPKeepAlive
;
5561 get_mailer('flush');
5564 require_once($CFG->libdir
.'/phpmailer/moodle_phpmailer.php');
5565 $mailer = new moodle_phpmailer();
5569 if ($CFG->smtphosts
== 'qmail') {
5570 // Use Qmail system.
5573 } else if (empty($CFG->smtphosts
)) {
5574 // Use PHP mail() = sendmail.
5578 // Use SMTP directly.
5580 if (!empty($CFG->debugsmtp
)) {
5581 $mailer->SMTPDebug
= true;
5583 // Specify main and backup servers.
5584 $mailer->Host
= $CFG->smtphosts
;
5585 // Specify secure connection protocol.
5586 $mailer->SMTPSecure
= $CFG->smtpsecure
;
5587 // Use previous keepalive.
5588 $mailer->SMTPKeepAlive
= $prevkeepalive;
5590 if ($CFG->smtpuser
) {
5591 // Use SMTP authentication.
5592 $mailer->SMTPAuth
= true;
5593 $mailer->Username
= $CFG->smtpuser
;
5594 $mailer->Password
= $CFG->smtppass
;
5603 // Keep smtp session open after sending.
5604 if ($action == 'buffer') {
5605 if (!empty($CFG->smtpmaxbulk
)) {
5606 get_mailer('flush');
5608 if ($m->Mailer
== 'smtp') {
5609 $m->SMTPKeepAlive
= true;
5615 // Close smtp session, but continue buffering.
5616 if ($action == 'flush') {
5617 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5618 if (!empty($mailer->SMTPDebug
)) {
5621 $mailer->SmtpClose();
5622 if (!empty($mailer->SMTPDebug
)) {
5629 // Close smtp session, do not buffer anymore.
5630 if ($action == 'close') {
5631 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5632 get_mailer('flush');
5633 $mailer->SMTPKeepAlive
= false;
5635 $mailer = null; // Better force new instance.
5641 * A helper function to test for email diversion
5643 * @param string $email
5644 * @return bool Returns true if the email should be diverted
5646 function email_should_be_diverted($email) {
5649 if (empty($CFG->divertallemailsto
)) {
5653 if (empty($CFG->divertallemailsexcept
)) {
5657 $patterns = array_map('trim', explode(',', $CFG->divertallemailsexcept
));
5658 foreach ($patterns as $pattern) {
5659 if (preg_match("/$pattern/", $email)) {
5668 * Generate a unique email Message-ID using the moodle domain and install path
5670 * @param string $localpart An optional unique message id prefix.
5671 * @return string The formatted ID ready for appending to the email headers.
5673 function generate_email_messageid($localpart = null) {
5676 $urlinfo = parse_url($CFG->wwwroot
);
5677 $base = '@' . $urlinfo['host'];
5679 // If multiple moodles are on the same domain we want to tell them
5680 // apart so we add the install path to the local part. This means
5681 // that the id local part should never contain a / character so
5682 // we can correctly parse the id to reassemble the wwwroot.
5683 if (isset($urlinfo['path'])) {
5684 $base = $urlinfo['path'] . $base;
5687 if (empty($localpart)) {
5688 $localpart = uniqid('', true);
5691 // Because we may have an option /installpath suffix to the local part
5692 // of the id we need to escape any / chars which are in the $localpart.
5693 $localpart = str_replace('/', '%2F', $localpart);
5695 return '<' . $localpart . $base . '>';
5699 * Send an email to a specified user
5701 * @param stdClass $user A {@link $USER} object
5702 * @param stdClass $from A {@link $USER} object
5703 * @param string $subject plain text subject line of the email
5704 * @param string $messagetext plain text version of the message
5705 * @param string $messagehtml complete html version of the message (optional)
5706 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5707 * @param string $attachname the name of the file (extension indicates MIME)
5708 * @param bool $usetrueaddress determines whether $from email address should
5709 * be sent out. Will be overruled by user profile setting for maildisplay
5710 * @param string $replyto Email address to reply to
5711 * @param string $replytoname Name of reply to recipient
5712 * @param int $wordwrapwidth custom word wrap width, default 79
5713 * @return bool Returns true if mail was sent OK and false if there was an error.
5715 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5716 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5718 global $CFG, $PAGE, $SITE;
5720 if (empty($user) or empty($user->id
)) {
5721 debugging('Can not send email to null user', DEBUG_DEVELOPER
);
5725 if (empty($user->email
)) {
5726 debugging('Can not send email to user without email: '.$user->id
, DEBUG_DEVELOPER
);
5730 if (!empty($user->deleted
)) {
5731 debugging('Can not send email to deleted user: '.$user->id
, DEBUG_DEVELOPER
);
5735 if (defined('BEHAT_SITE_RUNNING')) {
5736 // Fake email sending in behat.
5740 if (!empty($CFG->noemailever
)) {
5741 // Hidden setting for development sites, set in config.php if needed.
5742 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL
);
5746 if (email_should_be_diverted($user->email
)) {
5747 $subject = "[DIVERTED {$user->email}] $subject";
5748 $user = clone($user);
5749 $user->email
= $CFG->divertallemailsto
;
5752 // Skip mail to suspended users.
5753 if ((isset($user->auth
) && $user->auth
=='nologin') or (isset($user->suspended
) && $user->suspended
)) {
5757 if (!validate_email($user->email
)) {
5758 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5759 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5763 if (over_bounce_threshold($user)) {
5764 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5768 // TLD .invalid is specifically reserved for invalid domain names.
5769 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5770 if (substr($user->email
, -8) == '.invalid') {
5771 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5772 return true; // This is not an error.
5775 // If the user is a remote mnet user, parse the email text for URL to the
5776 // wwwroot and modify the url to direct the user's browser to login at their
5777 // home site (identity provider - idp) before hitting the link itself.
5778 if (is_mnet_remote_user($user)) {
5779 require_once($CFG->dirroot
.'/mnet/lib.php');
5781 $jumpurl = mnet_get_idp_jump_url($user);
5782 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5784 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5787 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5791 $mail = get_mailer();
5793 if (!empty($mail->SMTPDebug
)) {
5794 echo '<pre>' . "\n";
5797 $temprecipients = array();
5798 $tempreplyto = array();
5800 // Make sure that we fall back onto some reasonable no-reply address.
5801 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot
);
5802 $noreplyaddress = empty($CFG->noreplyaddress
) ?
$noreplyaddressdefault : $CFG->noreplyaddress
;
5804 if (!validate_email($noreplyaddress)) {
5805 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
5806 $noreplyaddress = $noreplyaddressdefault;
5809 // Make up an email address for handling bounces.
5810 if (!empty($CFG->handlebounces
)) {
5811 $modargs = 'B'.base64_encode(pack('V', $user->id
)).substr(md5($user->email
), 0, 16);
5812 $mail->Sender
= generate_email_processing_address(0, $modargs);
5814 $mail->Sender
= $noreplyaddress;
5817 // Make sure that the explicit replyto is valid, fall back to the implicit one.
5818 if (!empty($replyto) && !validate_email($replyto)) {
5819 debugging('email_to_user: Invalid replyto-email '.s($replyto));
5820 $replyto = $noreplyaddress;
5823 $alloweddomains = null;
5824 if (!empty($CFG->allowedemaildomains
)) {
5825 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains
));
5828 // Email will be sent using no reply address.
5829 if (empty($alloweddomains)) {
5830 $usetrueaddress = false;
5833 if (is_string($from)) { // So we can pass whatever we want if there is need.
5834 $mail->From
= $noreplyaddress;
5835 $mail->FromName
= $from;
5836 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
5837 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
5838 // in a course with the sender.
5839 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user, $alloweddomains)) {
5840 if (!validate_email($from->email
)) {
5841 debugging('email_to_user: Invalid from-email '.s($from->email
).' - not sending');
5842 // Better not to use $noreplyaddress in this case.
5845 $mail->From
= $from->email
;
5846 $fromdetails = new stdClass();
5847 $fromdetails->name
= fullname($from);
5848 $fromdetails->url
= preg_replace('#^https?://#', '', $CFG->wwwroot
);
5849 $fromdetails->siteshortname
= format_string($SITE->shortname
);
5850 $fromstring = $fromdetails->name
;
5851 if ($CFG->emailfromvia
== EMAIL_VIA_ALWAYS
) {
5852 $fromstring = get_string('emailvia', 'core', $fromdetails);
5854 $mail->FromName
= $fromstring;
5855 if (empty($replyto)) {
5856 $tempreplyto[] = array($from->email
, fullname($from));
5859 $mail->From
= $noreplyaddress;
5860 $fromdetails = new stdClass();
5861 $fromdetails->name
= fullname($from);
5862 $fromdetails->url
= preg_replace('#^https?://#', '', $CFG->wwwroot
);
5863 $fromdetails->siteshortname
= format_string($SITE->shortname
);
5864 $fromstring = $fromdetails->name
;
5865 if ($CFG->emailfromvia
!= EMAIL_VIA_NEVER
) {
5866 $fromstring = get_string('emailvia', 'core', $fromdetails);
5868 $mail->FromName
= $fromstring;
5869 if (empty($replyto)) {
5870 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
5874 if (!empty($replyto)) {
5875 $tempreplyto[] = array($replyto, $replytoname);
5878 $temprecipients[] = array($user->email
, fullname($user));
5881 $mail->WordWrap
= $wordwrapwidth;
5883 if (!empty($from->customheaders
)) {
5884 // Add custom headers.
5885 if (is_array($from->customheaders
)) {
5886 foreach ($from->customheaders
as $customheader) {
5887 $mail->addCustomHeader($customheader);
5890 $mail->addCustomHeader($from->customheaders
);
5894 // If the X-PHP-Originating-Script email header is on then also add an additional
5895 // header with details of where exactly in moodle the email was triggered from,
5896 // either a call to message_send() or to email_to_user().
5897 if (ini_get('mail.add_x_header')) {
5899 $stack = debug_backtrace(false);
5900 $origin = $stack[0];
5902 foreach ($stack as $depth => $call) {
5903 if ($call['function'] == 'message_send') {
5908 $originheader = $CFG->wwwroot
. ' => ' . gethostname() . ':'
5909 . str_replace($CFG->dirroot
. '/', '', $origin['file']) . ':' . $origin['line'];
5910 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
5913 if (!empty($from->priority
)) {
5914 $mail->Priority
= $from->priority
;
5917 $renderer = $PAGE->get_renderer('core');
5919 'sitefullname' => $SITE->fullname
,
5920 'siteshortname' => $SITE->shortname
,
5921 'sitewwwroot' => $CFG->wwwroot
,
5922 'subject' => $subject,
5923 'to' => $user->email
,
5924 'toname' => fullname($user),
5925 'from' => $mail->From
,
5926 'fromname' => $mail->FromName
,
5928 if (!empty($tempreplyto[0])) {
5929 $context['replyto'] = $tempreplyto[0][0];
5930 $context['replytoname'] = $tempreplyto[0][1];
5932 if ($user->id
> 0) {
5933 $context['touserid'] = $user->id
;
5934 $context['tousername'] = $user->username
;
5937 if (!empty($user->mailformat
) && $user->mailformat
== 1) {
5938 // Only process html templates if the user preferences allow html email.
5941 // If html has been given then pass it through the template.
5942 $context['body'] = $messagehtml;
5943 $messagehtml = $renderer->render_from_template('core/email_html', $context);
5946 // If no html has been given, BUT there is an html wrapping template then
5947 // auto convert the text to html and then wrap it.
5948 $autohtml = trim(text_to_html($messagetext));
5949 $context['body'] = $autohtml;
5950 $temphtml = $renderer->render_from_template('core/email_html', $context);
5951 if ($autohtml != $temphtml) {
5952 $messagehtml = $temphtml;
5957 $context['body'] = $messagetext;
5958 $mail->Subject
= $renderer->render_from_template('core/email_subject', $context);
5959 $mail->FromName
= $renderer->render_from_template('core/email_fromname', $context);
5960 $messagetext = $renderer->render_from_template('core/email_text', $context);
5962 // Autogenerate a MessageID if it's missing.
5963 if (empty($mail->MessageID
)) {
5964 $mail->MessageID
= generate_email_messageid();
5967 if ($messagehtml && !empty($user->mailformat
) && $user->mailformat
== 1) {
5968 // Don't ever send HTML to users who don't want it.
5969 $mail->isHTML(true);
5970 $mail->Encoding
= 'quoted-printable';
5971 $mail->Body
= $messagehtml;
5972 $mail->AltBody
= "\n$messagetext\n";
5974 $mail->IsHTML(false);
5975 $mail->Body
= "\n$messagetext\n";
5978 if ($attachment && $attachname) {
5979 if (preg_match( "~\\.\\.~" , $attachment )) {
5980 // Security check for ".." in dir path.
5981 $supportuser = core_user
::get_support_user();
5982 $temprecipients[] = array($supportuser->email
, fullname($supportuser, true));
5983 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5985 require_once($CFG->libdir
.'/filelib.php');
5986 $mimetype = mimeinfo('type', $attachname);
5988 $attachmentpath = $attachment;
5990 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5991 $attachpath = str_replace('\\', '/', $attachmentpath);
5992 // Make sure both variables are normalised before comparing.
5993 $temppath = str_replace('\\', '/', realpath($CFG->tempdir
));
5995 // If the attachment is a full path to a file in the tempdir, use it as is,
5996 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5997 if (strpos($attachpath, $temppath) !== 0) {
5998 $attachmentpath = $CFG->dataroot
. '/' . $attachmentpath;
6001 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
6005 // Check if the email should be sent in an other charset then the default UTF-8.
6006 if ((!empty($CFG->sitemailcharset
) ||
!empty($CFG->allowusermailcharset
))) {
6008 // Use the defined site mail charset or eventually the one preferred by the recipient.
6009 $charset = $CFG->sitemailcharset
;
6010 if (!empty($CFG->allowusermailcharset
)) {
6011 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id
)) {
6012 $charset = $useremailcharset;
6016 // Convert all the necessary strings if the charset is supported.
6017 $charsets = get_list_of_charsets();
6018 unset($charsets['UTF-8']);
6019 if (in_array($charset, $charsets)) {
6020 $mail->CharSet
= $charset;
6021 $mail->FromName
= core_text
::convert($mail->FromName
, 'utf-8', strtolower($charset));
6022 $mail->Subject
= core_text
::convert($mail->Subject
, 'utf-8', strtolower($charset));
6023 $mail->Body
= core_text
::convert($mail->Body
, 'utf-8', strtolower($charset));
6024 $mail->AltBody
= core_text
::convert($mail->AltBody
, 'utf-8', strtolower($charset));
6026 foreach ($temprecipients as $key => $values) {
6027 $temprecipients[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
6029 foreach ($tempreplyto as $key => $values) {
6030 $tempreplyto[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
6035 foreach ($temprecipients as $values) {
6036 $mail->addAddress($values[0], $values[1]);
6038 foreach ($tempreplyto as $values) {
6039 $mail->addReplyTo($values[0], $values[1]);
6042 if ($mail->send()) {
6043 set_send_count($user);
6044 if (!empty($mail->SMTPDebug
)) {
6049 // Trigger event for failing to send email.
6050 $event = \core\event\email_failed
::create(array(
6051 'context' => context_system
::instance(),
6052 'userid' => $from->id
,
6053 'relateduserid' => $user->id
,
6055 'subject' => $subject,
6056 'message' => $messagetext,
6057 'errorinfo' => $mail->ErrorInfo
6062 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo
);
6064 if (!empty($mail->SMTPDebug
)) {
6072 * Check to see if a user's real email address should be used for the "From" field.
6074 * @param object $from The user object for the user we are sending the email from.
6075 * @param object $user The user object that we are sending the email to.
6076 * @param array $alloweddomains An array of allowed domains that we can send email from.
6077 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6079 function can_send_from_real_email_address($from, $user, $alloweddomains) {
6080 // Email is in the list of allowed domains for sending email,
6081 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6082 // in a course with the sender.
6083 if (\core\ip_utils
::is_domain_in_allowed_list(substr($from->email
, strpos($from->email
, '@') +
1), $alloweddomains)
6084 && ($from->maildisplay
== core_user
::MAILDISPLAY_EVERYONE
6085 ||
($from->maildisplay
== core_user
::MAILDISPLAY_COURSE_MEMBERS_ONLY
6086 && enrol_get_shared_courses($user, $from, false, true)))) {
6093 * Generate a signoff for emails based on support settings
6097 function generate_email_signoff() {
6101 if (!empty($CFG->supportname
)) {
6102 $signoff .= $CFG->supportname
."\n";
6104 if (!empty($CFG->supportemail
)) {
6105 $signoff .= $CFG->supportemail
."\n";
6107 if (!empty($CFG->supportpage
)) {
6108 $signoff .= $CFG->supportpage
."\n";
6114 * Sets specified user's password and send the new password to the user via email.
6116 * @param stdClass $user A {@link $USER} object
6117 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6118 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6120 function setnew_password_and_mail($user, $fasthash = false) {
6123 // We try to send the mail in language the user understands,
6124 // unfortunately the filter_string() does not support alternative langs yet
6125 // so multilang will not work properly for site->fullname.
6126 $lang = empty($user->lang
) ?
$CFG->lang
: $user->lang
;
6130 $supportuser = core_user
::get_support_user();
6132 $newpassword = generate_password();
6134 update_internal_user_password($user, $newpassword, $fasthash);
6136 $a = new stdClass();
6137 $a->firstname
= fullname($user, true);
6138 $a->sitename
= format_string($site->fullname
);
6139 $a->username
= $user->username
;
6140 $a->newpassword
= $newpassword;
6141 $a->link
= $CFG->wwwroot
.'/login/';
6142 $a->signoff
= generate_email_signoff();
6144 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6146 $subject = format_string($site->fullname
) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6148 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6149 return email_to_user($user, $supportuser, $subject, $message);
6154 * Resets specified user's password and send the new password to the user via email.
6156 * @param stdClass $user A {@link $USER} object
6157 * @return bool Returns true if mail was sent OK and false if there was an error.
6159 function reset_password_and_mail($user) {
6163 $supportuser = core_user
::get_support_user();
6165 $userauth = get_auth_plugin($user->auth
);
6166 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth
)) {
6167 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6171 $newpassword = generate_password();
6173 if (!$userauth->user_update_password($user, $newpassword)) {
6174 print_error("cannotsetpassword");
6177 $a = new stdClass();
6178 $a->firstname
= $user->firstname
;
6179 $a->lastname
= $user->lastname
;
6180 $a->sitename
= format_string($site->fullname
);
6181 $a->username
= $user->username
;
6182 $a->newpassword
= $newpassword;
6183 $a->link
= $CFG->httpswwwroot
.'/login/change_password.php';
6184 $a->signoff
= generate_email_signoff();
6186 $message = get_string('newpasswordtext', '', $a);
6188 $subject = format_string($site->fullname
) .': '. get_string('changedpassword');
6190 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6192 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6193 return email_to_user($user, $supportuser, $subject, $message);
6197 * Send email to specified user with confirmation text and activation link.
6199 * @param stdClass $user A {@link $USER} object
6200 * @param string $confirmationurl user confirmation URL
6201 * @return bool Returns true if mail was sent OK and false if there was an error.
6203 function send_confirmation_email($user, $confirmationurl = null) {
6207 $supportuser = core_user
::get_support_user();
6209 $data = new stdClass();
6210 $data->firstname
= fullname($user);
6211 $data->sitename
= format_string($site->fullname
);
6212 $data->admin
= generate_email_signoff();
6214 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname
));
6216 if (empty($confirmationurl)) {
6217 $confirmationurl = '/login/confirm.php';
6220 $confirmationurl = new moodle_url($confirmationurl);
6221 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6222 $confirmationurl->remove_params('data');
6223 $confirmationpath = $confirmationurl->out(false);
6225 // We need to custom encode the username to include trailing dots in the link.
6226 // Because of this custom encoding we can't use moodle_url directly.
6227 // Determine if a query string is present in the confirmation url.
6228 $hasquerystring = strpos($confirmationpath, '?') !== false;
6229 // Perform normal url encoding of the username first.
6230 $username = urlencode($user->username
);
6231 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6232 $username = str_replace('.', '%2E', $username);
6234 $data->link
= $confirmationpath . ( $hasquerystring ?
'&' : '?') . 'data='. $user->secret
.'/'. $username;
6236 $message = get_string('emailconfirmation', '', $data);
6237 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6239 $user->mailformat
= 1; // Always send HTML version as well.
6241 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6242 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6246 * Sends a password change confirmation email.
6248 * @param stdClass $user A {@link $USER} object
6249 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6250 * @return bool Returns true if mail was sent OK and false if there was an error.
6252 function send_password_change_confirmation_email($user, $resetrecord) {
6256 $supportuser = core_user
::get_support_user();
6257 $pwresetmins = isset($CFG->pwresettime
) ?
floor($CFG->pwresettime
/ MINSECS
) : 30;
6259 $data = new stdClass();
6260 $data->firstname
= $user->firstname
;
6261 $data->lastname
= $user->lastname
;
6262 $data->username
= $user->username
;
6263 $data->sitename
= format_string($site->fullname
);
6264 $data->link
= $CFG->httpswwwroot
.'/login/forgot_password.php?token='. $resetrecord->token
;
6265 $data->admin
= generate_email_signoff();
6266 $data->resetminutes
= $pwresetmins;
6268 $message = get_string('emailresetconfirmation', '', $data);
6269 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname
));
6271 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6272 return email_to_user($user, $supportuser, $subject, $message);
6277 * Sends an email containinginformation on how to change your password.
6279 * @param stdClass $user A {@link $USER} object
6280 * @return bool Returns true if mail was sent OK and false if there was an error.
6282 function send_password_change_info($user) {
6286 $supportuser = core_user
::get_support_user();
6287 $systemcontext = context_system
::instance();
6289 $data = new stdClass();
6290 $data->firstname
= $user->firstname
;
6291 $data->lastname
= $user->lastname
;
6292 $data->sitename
= format_string($site->fullname
);
6293 $data->admin
= generate_email_signoff();
6295 $userauth = get_auth_plugin($user->auth
);
6297 if (!is_enabled_auth($user->auth
) or $user->auth
== 'nologin') {
6298 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6299 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6300 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6301 return email_to_user($user, $supportuser, $subject, $message);
6304 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6305 // We have some external url for password changing.
6306 $data->link
.= $userauth->change_password_url();
6309 // No way to change password, sorry.
6313 if (!empty($data->link
) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id
)) {
6314 $message = get_string('emailpasswordchangeinfo', '', $data);
6315 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6317 $message = get_string('emailpasswordchangeinfofail', '', $data);
6318 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6321 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6322 return email_to_user($user, $supportuser, $subject, $message);
6327 * Check that an email is allowed. It returns an error message if there was a problem.
6329 * @param string $email Content of email
6330 * @return string|false
6332 function email_is_not_allowed($email) {
6335 if (!empty($CFG->allowemailaddresses
)) {
6336 $allowed = explode(' ', $CFG->allowemailaddresses
);
6337 foreach ($allowed as $allowedpattern) {
6338 $allowedpattern = trim($allowedpattern);
6339 if (!$allowedpattern) {
6342 if (strpos($allowedpattern, '.') === 0) {
6343 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6344 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6348 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6352 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses
);
6354 } else if (!empty($CFG->denyemailaddresses
)) {
6355 $denied = explode(' ', $CFG->denyemailaddresses
);
6356 foreach ($denied as $deniedpattern) {
6357 $deniedpattern = trim($deniedpattern);
6358 if (!$deniedpattern) {
6361 if (strpos($deniedpattern, '.') === 0) {
6362 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6363 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6364 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
6367 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6368 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
6379 * Returns local file storage instance
6381 * @return file_storage
6383 function get_file_storage() {
6392 require_once("$CFG->libdir/filelib.php");
6394 if (isset($CFG->filedir
)) {
6395 $filedir = $CFG->filedir
;
6397 $filedir = $CFG->dataroot
.'/filedir';
6400 if (isset($CFG->trashdir
)) {
6401 $trashdirdir = $CFG->trashdir
;
6403 $trashdirdir = $CFG->dataroot
.'/trashdir';
6406 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions
, $CFG->filepermissions
);
6412 * Returns local file storage instance
6414 * @return file_browser
6416 function get_file_browser() {
6425 require_once("$CFG->libdir/filelib.php");
6427 $fb = new file_browser();
6433 * Returns file packer
6435 * @param string $mimetype default application/zip
6436 * @return file_packer
6438 function get_file_packer($mimetype='application/zip') {
6441 static $fp = array();
6443 if (isset($fp[$mimetype])) {
6444 return $fp[$mimetype];
6447 switch ($mimetype) {
6448 case 'application/zip':
6449 case 'application/vnd.moodle.profiling':
6450 $classname = 'zip_packer';
6453 case 'application/x-gzip' :
6454 $classname = 'tgz_packer';
6457 case 'application/vnd.moodle.backup':
6458 $classname = 'mbz_packer';
6465 require_once("$CFG->libdir/filestorage/$classname.php");
6466 $fp[$mimetype] = new $classname();
6468 return $fp[$mimetype];
6472 * Returns current name of file on disk if it exists.
6474 * @param string $newfile File to be verified
6475 * @return string Current name of file on disk if true
6477 function valid_uploaded_file($newfile) {
6478 if (empty($newfile)) {
6481 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6482 return $newfile['tmp_name'];
6489 * Returns the maximum size for uploading files.
6491 * There are seven possible upload limits:
6492 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6493 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6494 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6495 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6496 * 5. by the Moodle admin in $CFG->maxbytes
6497 * 6. by the teacher in the current course $course->maxbytes
6498 * 7. by the teacher for the current module, eg $assignment->maxbytes
6500 * These last two are passed to this function as arguments (in bytes).
6501 * Anything defined as 0 is ignored.
6502 * The smallest of all the non-zero numbers is returned.
6504 * @todo Finish documenting this function
6506 * @param int $sitebytes Set maximum size
6507 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6508 * @param int $modulebytes Current module ->maxbytes (in bytes)
6509 * @param bool $unused This parameter has been deprecated and is not used any more.
6510 * @return int The maximum size for uploading files.
6512 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6514 if (! $filesize = ini_get('upload_max_filesize')) {
6517 $minimumsize = get_real_size($filesize);
6519 if ($postsize = ini_get('post_max_size')) {
6520 $postsize = get_real_size($postsize);
6521 if ($postsize < $minimumsize) {
6522 $minimumsize = $postsize;
6526 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6527 $minimumsize = $sitebytes;
6530 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6531 $minimumsize = $coursebytes;
6534 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6535 $minimumsize = $modulebytes;
6538 return $minimumsize;
6542 * Returns the maximum size for uploading files for the current user
6544 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6546 * @param context $context The context in which to check user capabilities
6547 * @param int $sitebytes Set maximum size
6548 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6549 * @param int $modulebytes Current module ->maxbytes (in bytes)
6550 * @param stdClass $user The user
6551 * @param bool $unused This parameter has been deprecated and is not used any more.
6552 * @return int The maximum size for uploading files.
6554 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6562 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6563 return USER_CAN_IGNORE_FILE_SIZE_LIMITS
;
6566 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6570 * Returns an array of possible sizes in local language
6572 * Related to {@link get_max_upload_file_size()} - this function returns an
6573 * array of possible sizes in an array, translated to the
6576 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6578 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6579 * with the value set to 0. This option will be the first in the list.
6581 * @uses SORT_NUMERIC
6582 * @param int $sitebytes Set maximum size
6583 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6584 * @param int $modulebytes Current module ->maxbytes (in bytes)
6585 * @param int|array $custombytes custom upload size/s which will be added to list,
6586 * Only value/s smaller then maxsize will be added to list.
6589 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6592 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6596 if ($sitebytes == 0) {
6597 // Will get the minimum of upload_max_filesize or post_max_size.
6598 $sitebytes = get_max_upload_file_size();
6601 $filesize = array();
6602 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6603 5242880, 10485760, 20971520, 52428800, 104857600);
6605 // If custombytes is given and is valid then add it to the list.
6606 if (is_number($custombytes) and $custombytes > 0) {
6607 $custombytes = (int)$custombytes;
6608 if (!in_array($custombytes, $sizelist)) {
6609 $sizelist[] = $custombytes;
6611 } else if (is_array($custombytes)) {
6612 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6615 // Allow maxbytes to be selected if it falls outside the above boundaries.
6616 if (isset($CFG->maxbytes
) && !in_array(get_real_size($CFG->maxbytes
), $sizelist)) {
6617 // Note: get_real_size() is used in order to prevent problems with invalid values.
6618 $sizelist[] = get_real_size($CFG->maxbytes
);
6621 foreach ($sizelist as $sizebytes) {
6622 if ($sizebytes < $maxsize && $sizebytes > 0) {
6623 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6630 (($modulebytes < $coursebytes ||
$coursebytes == 0) &&
6631 ($modulebytes < $sitebytes ||
$sitebytes == 0))) {
6632 $limitlevel = get_string('activity', 'core');
6633 $displaysize = display_size($modulebytes);
6634 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6636 } else if ($coursebytes && ($coursebytes < $sitebytes ||
$sitebytes == 0)) {
6637 $limitlevel = get_string('course', 'core');
6638 $displaysize = display_size($coursebytes);
6639 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6641 } else if ($sitebytes) {
6642 $limitlevel = get_string('site', 'core');
6643 $displaysize = display_size($sitebytes);
6644 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6647 krsort($filesize, SORT_NUMERIC
);
6649 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6650 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) +
$filesize;
6657 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6659 * If excludefiles is defined, then that file/directory is ignored
6660 * If getdirs is true, then (sub)directories are included in the output
6661 * If getfiles is true, then files are included in the output
6662 * (at least one of these must be true!)
6664 * @todo Finish documenting this function. Add examples of $excludefile usage.
6666 * @param string $rootdir A given root directory to start from
6667 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6668 * @param bool $descend If true then subdirectories are recursed as well
6669 * @param bool $getdirs If true then (sub)directories are included in the output
6670 * @param bool $getfiles If true then files are included in the output
6671 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6673 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6677 if (!$getdirs and !$getfiles) { // Nothing to show.
6681 if (!is_dir($rootdir)) { // Must be a directory.
6685 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6689 if (!is_array($excludefiles)) {
6690 $excludefiles = array($excludefiles);
6693 while (false !== ($file = readdir($dir))) {
6694 $firstchar = substr($file, 0, 1);
6695 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6698 $fullfile = $rootdir .'/'. $file;
6699 if (filetype($fullfile) == 'dir') {
6704 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6705 foreach ($subdirs as $subdir) {
6706 $dirs[] = $file .'/'. $subdir;
6709 } else if ($getfiles) {
6722 * Adds up all the files in a directory and works out the size.
6724 * @param string $rootdir The directory to start from
6725 * @param string $excludefile A file to exclude when summing directory size
6726 * @return int The summed size of all files and subfiles within the root directory
6728 function get_directory_size($rootdir, $excludefile='') {
6731 // Do it this way if we can, it's much faster.
6732 if (!empty($CFG->pathtodu
) && is_executable(trim($CFG->pathtodu
))) {
6733 $command = trim($CFG->pathtodu
).' -sk '.escapeshellarg($rootdir);
6736 exec($command, $output, $return);
6737 if (is_array($output)) {
6738 // We told it to return k.
6739 return get_real_size(intval($output[0]).'k');
6743 if (!is_dir($rootdir)) {
6744 // Must be a directory.
6748 if (!$dir = @opendir
($rootdir)) {
6749 // Can't open it for some reason.
6755 while (false !== ($file = readdir($dir))) {
6756 $firstchar = substr($file, 0, 1);
6757 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6760 $fullfile = $rootdir .'/'. $file;
6761 if (filetype($fullfile) == 'dir') {
6762 $size +
= get_directory_size($fullfile, $excludefile);
6764 $size +
= filesize($fullfile);
6773 * Converts bytes into display form
6775 * @static string $gb Localized string for size in gigabytes
6776 * @static string $mb Localized string for size in megabytes
6777 * @static string $kb Localized string for size in kilobytes
6778 * @static string $b Localized string for size in bytes
6779 * @param int $size The size to convert to human readable form
6782 function display_size($size) {
6784 static $gb, $mb, $kb, $b;
6786 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS
) {
6787 return get_string('unlimited');
6791 $gb = get_string('sizegb');
6792 $mb = get_string('sizemb');
6793 $kb = get_string('sizekb');
6794 $b = get_string('sizeb');
6797 if ($size >= 1073741824) {
6798 $size = round($size / 1073741824 * 10) / 10 . $gb;
6799 } else if ($size >= 1048576) {
6800 $size = round($size / 1048576 * 10) / 10 . $mb;
6801 } else if ($size >= 1024) {
6802 $size = round($size / 1024 * 10) / 10 . $kb;
6804 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6810 * Cleans a given filename by removing suspicious or troublesome characters
6812 * @see clean_param()
6813 * @param string $string file name
6814 * @return string cleaned file name
6816 function clean_filename($string) {
6817 return clean_param($string, PARAM_FILE
);
6821 // STRING TRANSLATION.
6824 * Returns the code for the current language
6829 function current_language() {
6830 global $CFG, $USER, $SESSION, $COURSE;
6832 if (!empty($SESSION->forcelang
)) {
6833 // Allows overriding course-forced language (useful for admins to check
6834 // issues in courses whose language they don't understand).
6835 // Also used by some code to temporarily get language-related information in a
6836 // specific language (see force_current_language()).
6837 $return = $SESSION->forcelang
;
6839 } else if (!empty($COURSE->id
) and $COURSE->id
!= SITEID
and !empty($COURSE->lang
)) {
6840 // Course language can override all other settings for this page.
6841 $return = $COURSE->lang
;
6843 } else if (!empty($SESSION->lang
)) {
6844 // Session language can override other settings.
6845 $return = $SESSION->lang
;
6847 } else if (!empty($USER->lang
)) {
6848 $return = $USER->lang
;
6850 } else if (isset($CFG->lang
)) {
6851 $return = $CFG->lang
;
6857 // Just in case this slipped in from somewhere by accident.
6858 $return = str_replace('_utf8', '', $return);
6864 * Returns parent language of current active language if defined
6867 * @param string $lang null means current language
6870 function get_parent_language($lang=null) {
6872 // Let's hack around the current language.
6873 if (!empty($lang)) {
6874 $oldforcelang = force_current_language($lang);
6877 $parentlang = get_string('parentlanguage', 'langconfig');
6878 if ($parentlang === 'en') {
6882 // Let's hack around the current language.
6883 if (!empty($lang)) {
6884 force_current_language($oldforcelang);
6891 * Force the current language to get strings and dates localised in the given language.
6893 * After calling this function, all strings will be provided in the given language
6894 * until this function is called again, or equivalent code is run.
6896 * @param string $language
6897 * @return string previous $SESSION->forcelang value
6899 function force_current_language($language) {
6901 $sessionforcelang = isset($SESSION->forcelang
) ?
$SESSION->forcelang
: '';
6902 if ($language !== $sessionforcelang) {
6903 // Seting forcelang to null or an empty string disables it's effect.
6904 if (empty($language) ||
get_string_manager()->translation_exists($language, false)) {
6905 $SESSION->forcelang
= $language;
6909 return $sessionforcelang;
6913 * Returns current string_manager instance.
6915 * The param $forcereload is needed for CLI installer only where the string_manager instance
6916 * must be replaced during the install.php script life time.
6919 * @param bool $forcereload shall the singleton be released and new instance created instead?
6920 * @return core_string_manager
6922 function get_string_manager($forcereload=false) {
6925 static $singleton = null;
6930 if ($singleton === null) {
6931 if (empty($CFG->early_install_lang
)) {
6933 if (empty($CFG->langlist
)) {
6934 $translist = array();
6936 $translist = explode(',', $CFG->langlist
);
6939 if (!empty($CFG->config_php_settings
['customstringmanager'])) {
6940 $classname = $CFG->config_php_settings
['customstringmanager'];
6942 if (class_exists($classname)) {
6943 $implements = class_implements($classname);
6945 if (isset($implements['core_string_manager'])) {
6946 $singleton = new $classname($CFG->langotherroot
, $CFG->langlocalroot
, $translist);
6950 debugging('Unable to instantiate custom string manager: class '.$classname.
6951 ' does not implement the core_string_manager interface.');
6955 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
6959 $singleton = new core_string_manager_standard($CFG->langotherroot
, $CFG->langlocalroot
, $translist);
6962 $singleton = new core_string_manager_install();
6970 * Returns a localized string.
6972 * Returns the translated string specified by $identifier as
6973 * for $module. Uses the same format files as STphp.
6974 * $a is an object, string or number that can be used
6975 * within translation strings
6977 * eg 'hello {$a->firstname} {$a->lastname}'
6980 * If you would like to directly echo the localized string use
6981 * the function {@link print_string()}
6983 * Example usage of this function involves finding the string you would
6984 * like a local equivalent of and using its identifier and module information
6985 * to retrieve it.<br/>
6986 * If you open moodle/lang/en/moodle.php and look near line 278
6987 * you will find a string to prompt a user for their word for 'course'
6989 * $string['course'] = 'Course';
6991 * So if you want to display the string 'Course'
6992 * in any language that supports it on your site
6993 * you just need to use the identifier 'course'
6995 * $mystring = '<strong>'. get_string('course') .'</strong>';
6998 * If the string you want is in another file you'd take a slightly
6999 * different approach. Looking in moodle/lang/en/calendar.php you find
7002 * $string['typecourse'] = 'Course event';
7004 * If you want to display the string "Course event" in any language
7005 * supported you would use the identifier 'typecourse' and the module 'calendar'
7006 * (because it is in the file calendar.php):
7008 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7011 * As a last resort, should the identifier fail to map to a string
7012 * the returned string will be [[ $identifier ]]
7014 * In Moodle 2.3 there is a new argument to this function $lazyload.
7015 * Setting $lazyload to true causes get_string to return a lang_string object
7016 * rather than the string itself. The fetching of the string is then put off until
7017 * the string object is first used. The object can be used by calling it's out
7018 * method or by casting the object to a string, either directly e.g.
7019 * (string)$stringobject
7020 * or indirectly by using the string within another string or echoing it out e.g.
7021 * echo $stringobject
7022 * return "<p>{$stringobject}</p>";
7023 * It is worth noting that using $lazyload and attempting to use the string as an
7024 * array key will cause a fatal error as objects cannot be used as array keys.
7025 * But you should never do that anyway!
7026 * For more information {@link lang_string}
7029 * @param string $identifier The key identifier for the localized string
7030 * @param string $component The module where the key identifier is stored,
7031 * usually expressed as the filename in the language pack without the
7032 * .php on the end but can also be written as mod/forum or grade/export/xls.
7033 * If none is specified then moodle.php is used.
7034 * @param string|object|array $a An object, string or number that can be used
7035 * within translation strings
7036 * @param bool $lazyload If set to true a string object is returned instead of
7037 * the string itself. The string then isn't calculated until it is first used.
7038 * @return string The localized string.
7039 * @throws coding_exception
7041 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7044 // If the lazy load argument has been supplied return a lang_string object
7046 // We need to make sure it is true (and a bool) as you will see below there
7047 // used to be a forth argument at one point.
7048 if ($lazyload === true) {
7049 return new lang_string($identifier, $component, $a);
7052 if ($CFG->debugdeveloper
&& clean_param($identifier, PARAM_STRINGID
) === '') {
7053 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER
);
7056 // There is now a forth argument again, this time it is a boolean however so
7057 // we can still check for the old extralocations parameter.
7058 if (!is_bool($lazyload) && !empty($lazyload)) {
7059 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7062 if (strpos($component, '/') !== false) {
7063 debugging('The module name you passed to get_string is the deprecated format ' .
7064 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER
);
7065 $componentpath = explode('/', $component);
7067 switch ($componentpath[0]) {
7069 $component = $componentpath[1];
7073 $component = 'block_'.$componentpath[1];
7076 $component = 'enrol_'.$componentpath[1];
7079 $component = 'format_'.$componentpath[1];
7082 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7087 $result = get_string_manager()->get_string($identifier, $component, $a);
7089 // Debugging feature lets you display string identifier and component.
7090 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
7091 $result .= ' {' . $identifier . '/' . $component . '}';
7097 * Converts an array of strings to their localized value.
7099 * @param array $array An array of strings
7100 * @param string $component The language module that these strings can be found in.
7101 * @return stdClass translated strings.
7103 function get_strings($array, $component = '') {
7104 $string = new stdClass
;
7105 foreach ($array as $item) {
7106 $string->$item = get_string($item, $component);
7112 * Prints out a translated string.
7114 * Prints out a translated string using the return value from the {@link get_string()} function.
7116 * Example usage of this function when the string is in the moodle.php file:<br/>
7119 * print_string('course');
7123 * Example usage of this function when the string is not in the moodle.php file:<br/>
7126 * print_string('typecourse', 'calendar');
7131 * @param string $identifier The key identifier for the localized string
7132 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7133 * @param string|object|array $a An object, string or number that can be used within translation strings
7135 function print_string($identifier, $component = '', $a = null) {
7136 echo get_string($identifier, $component, $a);
7140 * Returns a list of charset codes
7142 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7143 * (checking that such charset is supported by the texlib library!)
7145 * @return array And associative array with contents in the form of charset => charset
7147 function get_list_of_charsets() {
7150 'EUC-JP' => 'EUC-JP',
7151 'ISO-2022-JP'=> 'ISO-2022-JP',
7152 'ISO-8859-1' => 'ISO-8859-1',
7153 'SHIFT-JIS' => 'SHIFT-JIS',
7154 'GB2312' => 'GB2312',
7155 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7156 'UTF-8' => 'UTF-8');
7164 * Returns a list of valid and compatible themes
7168 function get_list_of_themes() {
7173 if (!empty($CFG->themelist
)) { // Use admin's list of themes.
7174 $themelist = explode(',', $CFG->themelist
);
7176 $themelist = array_keys(core_component
::get_plugin_list("theme"));
7179 foreach ($themelist as $key => $themename) {
7180 $theme = theme_config
::load($themename);
7181 $themes[$themename] = $theme;
7184 core_collator
::asort_objects_by_method($themes, 'get_theme_name');
7190 * Factory function for emoticon_manager
7192 * @return emoticon_manager singleton
7194 function get_emoticon_manager() {
7195 static $singleton = null;
7197 if (is_null($singleton)) {
7198 $singleton = new emoticon_manager();
7205 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7207 * Whenever this manager mentiones 'emoticon object', the following data
7208 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7209 * altidentifier and altcomponent
7211 * @see admin_setting_emoticons
7213 * @copyright 2010 David Mudrak
7214 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7216 class emoticon_manager
{
7219 * Returns the currently enabled emoticons
7221 * @return array of emoticon objects
7223 public function get_emoticons() {
7226 if (empty($CFG->emoticons
)) {
7230 $emoticons = $this->decode_stored_config($CFG->emoticons
);
7232 if (!is_array($emoticons)) {
7233 // Something is wrong with the format of stored setting.
7234 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL
);
7242 * Converts emoticon object into renderable pix_emoticon object
7244 * @param stdClass $emoticon emoticon object
7245 * @param array $attributes explicit HTML attributes to set
7246 * @return pix_emoticon
7248 public function prepare_renderable_emoticon(stdClass
$emoticon, array $attributes = array()) {
7249 $stringmanager = get_string_manager();
7250 if ($stringmanager->string_exists($emoticon->altidentifier
, $emoticon->altcomponent
)) {
7251 $alt = get_string($emoticon->altidentifier
, $emoticon->altcomponent
);
7253 $alt = s($emoticon->text
);
7255 return new pix_emoticon($emoticon->imagename
, $alt, $emoticon->imagecomponent
, $attributes);
7259 * Encodes the array of emoticon objects into a string storable in config table
7261 * @see self::decode_stored_config()
7262 * @param array $emoticons array of emtocion objects
7265 public function encode_stored_config(array $emoticons) {
7266 return json_encode($emoticons);
7270 * Decodes the string into an array of emoticon objects
7272 * @see self::encode_stored_config()
7273 * @param string $encoded
7274 * @return string|null
7276 public function decode_stored_config($encoded) {
7277 $decoded = json_decode($encoded);
7278 if (!is_array($decoded)) {
7285 * Returns default set of emoticons supported by Moodle
7287 * @return array of sdtClasses
7289 public function default_emoticons() {
7291 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7292 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7293 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7294 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7295 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7296 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7297 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7298 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7299 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7300 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7301 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7302 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7303 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7304 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7305 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7306 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7307 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7308 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7309 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7310 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7311 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7312 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7313 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7314 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7315 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7316 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7317 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7318 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7319 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7320 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7325 * Helper method preparing the stdClass with the emoticon properties
7327 * @param string|array $text or array of strings
7328 * @param string $imagename to be used by {@link pix_emoticon}
7329 * @param string $altidentifier alternative string identifier, null for no alt
7330 * @param string $altcomponent where the alternative string is defined
7331 * @param string $imagecomponent to be used by {@link pix_emoticon}
7334 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7335 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7336 return (object)array(
7338 'imagename' => $imagename,
7339 'imagecomponent' => $imagecomponent,
7340 'altidentifier' => $altidentifier,
7341 'altcomponent' => $altcomponent,
7351 * @param string $data Data to encrypt.
7352 * @return string The now encrypted data.
7354 function rc4encrypt($data) {
7355 return endecrypt(get_site_identifier(), $data, '');
7361 * @param string $data Data to decrypt.
7362 * @return string The now decrypted data.
7364 function rc4decrypt($data) {
7365 return endecrypt(get_site_identifier(), $data, 'de');
7369 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7371 * @todo Finish documenting this function
7373 * @param string $pwd The password to use when encrypting or decrypting
7374 * @param string $data The data to be decrypted/encrypted
7375 * @param string $case Either 'de' for decrypt or '' for encrypt
7378 function endecrypt ($pwd, $data, $case) {
7380 if ($case == 'de') {
7381 $data = urldecode($data);
7386 $pwdlength = strlen($pwd);
7388 for ($i = 0; $i <= 255; $i++
) {
7389 $key[$i] = ord(substr($pwd, ($i %
$pwdlength), 1));
7395 for ($i = 0; $i <= 255; $i++
) {
7396 $x = ($x +
$box[$i] +
$key[$i]) %
256;
7397 $tempswap = $box[$i];
7398 $box[$i] = $box[$x];
7399 $box[$x] = $tempswap;
7407 for ($i = 0; $i < strlen($data); $i++
) {
7408 $a = ($a +
1) %
256;
7409 $j = ($j +
$box[$a]) %
256;
7411 $box[$a] = $box[$j];
7413 $k = $box[(($box[$a] +
$box[$j]) %
256)];
7414 $cipherby = ord(substr($data, $i, 1)) ^
$k;
7415 $cipher .= chr($cipherby);
7418 if ($case == 'de') {
7419 $cipher = urldecode(urlencode($cipher));
7421 $cipher = urlencode($cipher);
7427 // ENVIRONMENT CHECKING.
7430 * This method validates a plug name. It is much faster than calling clean_param.
7432 * @param string $name a string that might be a plugin name.
7433 * @return bool if this string is a valid plugin name.
7435 function is_valid_plugin_name($name) {
7436 // This does not work for 'mod', bad luck, use any other type.
7437 return core_component
::is_valid_plugin_name('tool', $name);
7441 * Get a list of all the plugins of a given type that define a certain API function
7442 * in a certain file. The plugin component names and function names are returned.
7444 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7445 * @param string $function the part of the name of the function after the
7446 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7447 * names like report_courselist_hook.
7448 * @param string $file the name of file within the plugin that defines the
7449 * function. Defaults to lib.php.
7450 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7451 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7453 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7456 // We don't include here as all plugin types files would be included.
7457 $plugins = get_plugins_with_function($function, $file, false);
7459 if (empty($plugins[$plugintype])) {
7463 $allplugins = core_component
::get_plugin_list($plugintype);
7465 // Reformat the array and include the files.
7466 $pluginfunctions = array();
7467 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7469 // Check that it has not been removed and the file is still available.
7470 if (!empty($allplugins[$pluginname])) {
7472 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR
. $file;
7473 if (file_exists($filepath)) {
7474 include_once($filepath);
7475 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7480 return $pluginfunctions;
7484 * Get a list of all the plugins that define a certain API function in a certain file.
7486 * @param string $function the part of the name of the function after the
7487 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7488 * names like report_courselist_hook.
7489 * @param string $file the name of file within the plugin that defines the
7490 * function. Defaults to lib.php.
7491 * @param bool $include Whether to include the files that contain the functions or not.
7492 * @return array with [plugintype][plugin] = functionname
7494 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7497 $cache = \cache
::make('core', 'plugin_functions');
7499 // Including both although I doubt that we will find two functions definitions with the same name.
7500 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7501 $key = $function . '_' . clean_param($file, PARAM_ALPHA
);
7503 if ($pluginfunctions = $cache->get($key)) {
7505 // Checking that the files are still available.
7506 foreach ($pluginfunctions as $plugintype => $plugins) {
7508 $allplugins = \core_component
::get_plugin_list($plugintype);
7509 foreach ($plugins as $plugin => $fullpath) {
7511 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7512 if (empty($allplugins[$plugin])) {
7513 unset($pluginfunctions[$plugintype][$plugin]);
7517 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR
. $file);
7518 if ($include && $fileexists) {
7519 // Include the files if it was requested.
7520 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR
. $file);
7521 } else if (!$fileexists) {
7522 // If the file is not available any more it should not be returned.
7523 unset($pluginfunctions[$plugintype][$plugin]);
7527 return $pluginfunctions;
7530 $pluginfunctions = array();
7532 // To fill the cached. Also, everything should continue working with cache disabled.
7533 $plugintypes = \core_component
::get_plugin_types();
7534 foreach ($plugintypes as $plugintype => $unused) {
7536 // We need to include files here.
7537 $pluginswithfile = \core_component
::get_plugin_list_with_file($plugintype, $file, true);
7538 foreach ($pluginswithfile as $plugin => $notused) {
7540 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7542 $pluginfunction = false;
7543 if (function_exists($fullfunction)) {
7544 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7545 $pluginfunction = $fullfunction;
7547 } else if ($plugintype === 'mod') {
7548 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7549 $shortfunction = $plugin . '_' . $function;
7550 if (function_exists($shortfunction)) {
7551 $pluginfunction = $shortfunction;
7555 if ($pluginfunction) {
7556 if (empty($pluginfunctions[$plugintype])) {
7557 $pluginfunctions[$plugintype] = array();
7559 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7564 $cache->set($key, $pluginfunctions);
7566 return $pluginfunctions;
7571 * Lists plugin-like directories within specified directory
7573 * This function was originally used for standard Moodle plugins, please use
7574 * new core_component::get_plugin_list() now.
7576 * This function is used for general directory listing and backwards compatility.
7578 * @param string $directory relative directory from root
7579 * @param string $exclude dir name to exclude from the list (defaults to none)
7580 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7581 * @return array Sorted array of directory names found under the requested parameters
7583 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7588 if (empty($basedir)) {
7589 $basedir = $CFG->dirroot
.'/'. $directory;
7592 $basedir = $basedir .'/'. $directory;
7595 if ($CFG->debugdeveloper
and empty($exclude)) {
7596 // Make sure devs do not use this to list normal plugins,
7597 // this is intended for general directories that are not plugins!
7599 $subtypes = core_component
::get_plugin_types();
7600 if (in_array($basedir, $subtypes)) {
7601 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER
);
7606 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7607 if (!$dirhandle = opendir($basedir)) {
7608 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER
);
7611 while (false !== ($dir = readdir($dirhandle))) {
7612 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7613 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7614 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7617 if (filetype($basedir .'/'. $dir) != 'dir') {
7622 closedir($dirhandle);
7631 * Invoke plugin's callback functions
7633 * @param string $type plugin type e.g. 'mod'
7634 * @param string $name plugin name
7635 * @param string $feature feature name
7636 * @param string $action feature's action
7637 * @param array $params parameters of callback function, should be an array
7638 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7641 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7643 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7644 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7648 * Invoke component's callback functions
7650 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7651 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7652 * @param array $params parameters of callback function
7653 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7656 function component_callback($component, $function, array $params = array(), $default = null) {
7658 $functionname = component_callback_exists($component, $function);
7660 if ($functionname) {
7661 // Function exists, so just return function result.
7662 $ret = call_user_func_array($functionname, $params);
7663 if (is_null($ret)) {
7673 * Determine if a component callback exists and return the function name to call. Note that this
7674 * function will include the required library files so that the functioname returned can be
7677 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7678 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7679 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7680 * @throws coding_exception if invalid component specfied
7682 function component_callback_exists($component, $function) {
7683 global $CFG; // This is needed for the inclusions.
7685 $cleancomponent = clean_param($component, PARAM_COMPONENT
);
7686 if (empty($cleancomponent)) {
7687 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7689 $component = $cleancomponent;
7691 list($type, $name) = core_component
::normalize_component($component);
7692 $component = $type . '_' . $name;
7694 $oldfunction = $name.'_'.$function;
7695 $function = $component.'_'.$function;
7697 $dir = core_component
::get_component_directory($component);
7699 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7702 // Load library and look for function.
7703 if (file_exists($dir.'/lib.php')) {
7704 require_once($dir.'/lib.php');
7707 if (!function_exists($function) and function_exists($oldfunction)) {
7708 if ($type !== 'mod' and $type !== 'core') {
7709 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER
);
7711 $function = $oldfunction;
7714 if (function_exists($function)) {
7721 * Checks whether a plugin supports a specified feature.
7723 * @param string $type Plugin type e.g. 'mod'
7724 * @param string $name Plugin name e.g. 'forum'
7725 * @param string $feature Feature code (FEATURE_xx constant)
7726 * @param mixed $default default value if feature support unknown
7727 * @return mixed Feature result (false if not supported, null if feature is unknown,
7728 * otherwise usually true but may have other feature-specific value such as array)
7729 * @throws coding_exception
7731 function plugin_supports($type, $name, $feature, $default = null) {
7734 if ($type === 'mod' and $name === 'NEWMODULE') {
7735 // Somebody forgot to rename the module template.
7739 $component = clean_param($type . '_' . $name, PARAM_COMPONENT
);
7740 if (empty($component)) {
7741 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7746 if ($type === 'mod') {
7747 // We need this special case because we support subplugins in modules,
7748 // otherwise it would end up in infinite loop.
7749 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7750 include_once("$CFG->dirroot/mod/$name/lib.php");
7751 $function = $component.'_supports';
7752 if (!function_exists($function)) {
7753 // Legacy non-frankenstyle function name.
7754 $function = $name.'_supports';
7759 if (!$path = core_component
::get_plugin_directory($type, $name)) {
7760 // Non existent plugin type.
7763 if (file_exists("$path/lib.php")) {
7764 include_once("$path/lib.php");
7765 $function = $component.'_supports';
7769 if ($function and function_exists($function)) {
7770 $supports = $function($feature);
7771 if (is_null($supports)) {
7772 // Plugin does not know - use default.
7779 // Plugin does not care, so use default.
7784 * Returns true if the current version of PHP is greater that the specified one.
7786 * @todo Check PHP version being required here is it too low?
7788 * @param string $version The version of php being tested.
7791 function check_php_version($version='5.2.4') {
7792 return (version_compare(phpversion(), $version) >= 0);
7796 * Determine if moodle installation requires update.
7798 * Checks version numbers of main code and all plugins to see
7799 * if there are any mismatches.
7803 function moodle_needs_upgrading() {
7806 if (empty($CFG->version
)) {
7810 // There is no need to purge plugininfo caches here because
7811 // these caches are not used during upgrade and they are purged after
7814 if (empty($CFG->allversionshash
)) {
7818 $hash = core_component
::get_all_versions_hash();
7820 return ($hash !== $CFG->allversionshash
);
7824 * Returns the major version of this site
7826 * Moodle version numbers consist of three numbers separated by a dot, for
7827 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7828 * called major version. This function extracts the major version from either
7829 * $CFG->release (default) or eventually from the $release variable defined in
7830 * the main version.php.
7832 * @param bool $fromdisk should the version if source code files be used
7833 * @return string|false the major version like '2.3', false if could not be determined
7835 function moodle_major_version($fromdisk = false) {
7840 require($CFG->dirroot
.'/version.php');
7841 if (empty($release)) {
7846 if (empty($CFG->release
)) {
7849 $release = $CFG->release
;
7852 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7862 * Sets the system locale
7865 * @param string $locale Can be used to force a locale
7867 function moodle_setlocale($locale='') {
7870 static $currentlocale = ''; // Last locale caching.
7872 $oldlocale = $currentlocale;
7874 // Fetch the correct locale based on ostype.
7875 if ($CFG->ostype
== 'WINDOWS') {
7876 $stringtofetch = 'localewin';
7878 $stringtofetch = 'locale';
7881 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7882 if (!empty($locale)) {
7883 $currentlocale = $locale;
7884 } else if (!empty($CFG->locale
)) { // Override locale for all language packs.
7885 $currentlocale = $CFG->locale
;
7887 $currentlocale = get_string($stringtofetch, 'langconfig');
7890 // Do nothing if locale already set up.
7891 if ($oldlocale == $currentlocale) {
7895 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7896 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7897 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7899 // Get current values.
7900 $monetary= setlocale (LC_MONETARY
, 0);
7901 $numeric = setlocale (LC_NUMERIC
, 0);
7902 $ctype = setlocale (LC_CTYPE
, 0);
7903 if ($CFG->ostype
!= 'WINDOWS') {
7904 $messages= setlocale (LC_MESSAGES
, 0);
7906 // Set locale to all.
7907 $result = setlocale (LC_ALL
, $currentlocale);
7908 // If setting of locale fails try the other utf8 or utf-8 variant,
7909 // some operating systems support both (Debian), others just one (OSX).
7910 if ($result === false) {
7911 if (stripos($currentlocale, '.UTF-8') !== false) {
7912 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7913 setlocale (LC_ALL
, $newlocale);
7914 } else if (stripos($currentlocale, '.UTF8') !== false) {
7915 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7916 setlocale (LC_ALL
, $newlocale);
7920 setlocale (LC_MONETARY
, $monetary);
7921 setlocale (LC_NUMERIC
, $numeric);
7922 if ($CFG->ostype
!= 'WINDOWS') {
7923 setlocale (LC_MESSAGES
, $messages);
7925 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7926 // To workaround a well-known PHP problem with Turkish letter Ii.
7927 setlocale (LC_CTYPE
, $ctype);
7932 * Count words in a string.
7934 * Words are defined as things between whitespace.
7937 * @param string $string The text to be searched for words.
7938 * @return int The count of words in the specified string
7940 function count_words($string) {
7941 $string = strip_tags($string);
7942 // Decode HTML entities.
7943 $string = html_entity_decode($string);
7944 // Replace underscores (which are classed as word characters) with spaces.
7945 $string = preg_replace('/_/u', ' ', $string);
7946 // Remove any characters that shouldn't be treated as word boundaries.
7947 $string = preg_replace('/[\'"’-]/u', '', $string);
7948 // Remove dots and commas from within numbers only.
7949 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7951 return count(preg_split('/\w\b/u', $string)) - 1;
7955 * Count letters in a string.
7957 * Letters are defined as chars not in tags and different from whitespace.
7960 * @param string $string The text to be searched for letters.
7961 * @return int The count of letters in the specified text.
7963 function count_letters($string) {
7964 $string = strip_tags($string); // Tags are out now.
7965 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7967 return core_text
::strlen($string);
7971 * Generate and return a random string of the specified length.
7973 * @param int $length The length of the string to be created.
7976 function random_string($length=15) {
7977 $randombytes = random_bytes_emulate($length);
7978 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7979 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7980 $pool .= '0123456789';
7981 $poollen = strlen($pool);
7983 for ($i = 0; $i < $length; $i++
) {
7984 $rand = ord($randombytes[$i]);
7985 $string .= substr($pool, ($rand%
($poollen)), 1);
7991 * Generate a complex random string (useful for md5 salts)
7993 * This function is based on the above {@link random_string()} however it uses a
7994 * larger pool of characters and generates a string between 24 and 32 characters
7996 * @param int $length Optional if set generates a string to exactly this length
7999 function complex_random_string($length=null) {
8000 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8001 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8002 $poollen = strlen($pool);
8003 if ($length===null) {
8004 $length = floor(rand(24, 32));
8006 $randombytes = random_bytes_emulate($length);
8008 for ($i = 0; $i < $length; $i++
) {
8009 $rand = ord($randombytes[$i]);
8010 $string .= $pool[($rand%
$poollen)];
8016 * Try to generates cryptographically secure pseudo-random bytes.
8018 * Note this is achieved by fallbacking between:
8019 * - PHP 7 random_bytes().
8020 * - OpenSSL openssl_random_pseudo_bytes().
8021 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8023 * @param int $length requested length in bytes
8024 * @return string binary data
8026 function random_bytes_emulate($length) {
8029 debugging('Invalid random bytes length', DEBUG_DEVELOPER
);
8032 if (function_exists('random_bytes')) {
8033 // Use PHP 7 goodness.
8034 $hash = @random_bytes
($length);
8035 if ($hash !== false) {
8039 if (function_exists('openssl_random_pseudo_bytes')) {
8040 // If you have the openssl extension enabled.
8041 $hash = openssl_random_pseudo_bytes($length);
8042 if ($hash !== false) {
8047 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8048 $staticdata = serialize($CFG) . serialize($_SERVER);
8051 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8052 } while (strlen($hash) < $length);
8054 return substr($hash, 0, $length);
8058 * Given some text (which may contain HTML) and an ideal length,
8059 * this function truncates the text neatly on a word boundary if possible
8062 * @param string $text text to be shortened
8063 * @param int $ideal ideal string length
8064 * @param boolean $exact if false, $text will not be cut mid-word
8065 * @param string $ending The string to append if the passed string is truncated
8066 * @return string $truncate shortened string
8068 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8069 // If the plain text is shorter than the maximum length, return the whole text.
8070 if (core_text
::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8074 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8075 // and only tag in its 'line'.
8076 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER
);
8078 $totallength = core_text
::strlen($ending);
8081 // This array stores information about open and close tags and their position
8082 // in the truncated string. Each item in the array is an object with fields
8083 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8084 // (byte position in truncated text).
8085 $tagdetails = array();
8087 foreach ($lines as $linematchings) {
8088 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8089 if (!empty($linematchings[1])) {
8090 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8091 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8092 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8093 // Record closing tag.
8094 $tagdetails[] = (object) array(
8096 'tag' => core_text
::strtolower($tagmatchings[1]),
8097 'pos' => core_text
::strlen($truncate),
8100 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8101 // Record opening tag.
8102 $tagdetails[] = (object) array(
8104 'tag' => core_text
::strtolower($tagmatchings[1]),
8105 'pos' => core_text
::strlen($truncate),
8107 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8108 $tagdetails[] = (object) array(
8110 'tag' => core_text
::strtolower('if'),
8111 'pos' => core_text
::strlen($truncate),
8113 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8114 $tagdetails[] = (object) array(
8116 'tag' => core_text
::strtolower('if'),
8117 'pos' => core_text
::strlen($truncate),
8121 // Add html-tag to $truncate'd text.
8122 $truncate .= $linematchings[1];
8125 // Calculate the length of the plain text part of the line; handle entities as one character.
8126 $contentlength = core_text
::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8127 if ($totallength +
$contentlength > $ideal) {
8128 // The number of characters which are left.
8129 $left = $ideal - $totallength;
8130 $entitieslength = 0;
8131 // Search for html entities.
8132 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
)) {
8133 // Calculate the real length of all entities in the legal range.
8134 foreach ($entities[0] as $entity) {
8135 if ($entity[1]+
1-$entitieslength <= $left) {
8137 $entitieslength +
= core_text
::strlen($entity[0]);
8139 // No more characters left.
8144 $breakpos = $left +
$entitieslength;
8146 // If the words shouldn't be cut in the middle...
8148 // Search the last occurence of a space.
8149 for (; $breakpos > 0; $breakpos--) {
8150 if ($char = core_text
::substr($linematchings[2], $breakpos, 1)) {
8151 if ($char === '.' or $char === ' ') {
8154 } else if (strlen($char) > 2) {
8155 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8162 if ($breakpos == 0) {
8163 // This deals with the test_shorten_text_no_spaces case.
8164 $breakpos = $left +
$entitieslength;
8165 } else if ($breakpos > $left +
$entitieslength) {
8166 // This deals with the previous for loop breaking on the first char.
8167 $breakpos = $left +
$entitieslength;
8170 $truncate .= core_text
::substr($linematchings[2], 0, $breakpos);
8171 // Maximum length is reached, so get off the loop.
8174 $truncate .= $linematchings[2];
8175 $totallength +
= $contentlength;
8178 // If the maximum length is reached, get off the loop.
8179 if ($totallength >= $ideal) {
8184 // Add the defined ending to the text.
8185 $truncate .= $ending;
8187 // Now calculate the list of open html tags based on the truncate position.
8188 $opentags = array();
8189 foreach ($tagdetails as $taginfo) {
8190 if ($taginfo->open
) {
8191 // Add tag to the beginning of $opentags list.
8192 array_unshift($opentags, $taginfo->tag
);
8194 // Can have multiple exact same open tags, close the last one.
8195 $pos = array_search($taginfo->tag
, array_reverse($opentags, true));
8196 if ($pos !== false) {
8197 unset($opentags[$pos]);
8202 // Close all unclosed html-tags.
8203 foreach ($opentags as $tag) {
8204 if ($tag === 'if') {
8205 $truncate .= '<!--<![endif]-->';
8207 $truncate .= '</' . $tag . '>';
8216 * Given dates in seconds, how many weeks is the date from startdate
8217 * The first week is 1, the second 2 etc ...
8219 * @param int $startdate Timestamp for the start date
8220 * @param int $thedate Timestamp for the end date
8223 function getweek ($startdate, $thedate) {
8224 if ($thedate < $startdate) {
8228 return floor(($thedate - $startdate) / WEEKSECS
) +
1;
8232 * Returns a randomly generated password of length $maxlen. inspired by
8234 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8235 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8237 * @param int $maxlen The maximum size of the password being generated.
8240 function generate_password($maxlen=10) {
8243 if (empty($CFG->passwordpolicy
)) {
8244 $fillers = PASSWORD_DIGITS
;
8245 $wordlist = file($CFG->wordlist
);
8246 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8247 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8248 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8249 $password = $word1 . $filler1 . $word2;
8251 $minlen = !empty($CFG->minpasswordlength
) ?
$CFG->minpasswordlength
: 0;
8252 $digits = $CFG->minpassworddigits
;
8253 $lower = $CFG->minpasswordlower
;
8254 $upper = $CFG->minpasswordupper
;
8255 $nonalphanum = $CFG->minpasswordnonalphanum
;
8256 $total = $lower +
$upper +
$digits +
$nonalphanum;
8257 // Var minlength should be the greater one of the two ( $minlen and $total ).
8258 $minlen = $minlen < $total ?
$total : $minlen;
8259 // Var maxlen can never be smaller than minlen.
8260 $maxlen = $minlen > $maxlen ?
$minlen : $maxlen;
8261 $additional = $maxlen - $total;
8263 // Make sure we have enough characters to fulfill
8264 // complexity requirements.
8265 $passworddigits = PASSWORD_DIGITS
;
8266 while ($digits > strlen($passworddigits)) {
8267 $passworddigits .= PASSWORD_DIGITS
;
8269 $passwordlower = PASSWORD_LOWER
;
8270 while ($lower > strlen($passwordlower)) {
8271 $passwordlower .= PASSWORD_LOWER
;
8273 $passwordupper = PASSWORD_UPPER
;
8274 while ($upper > strlen($passwordupper)) {
8275 $passwordupper .= PASSWORD_UPPER
;
8277 $passwordnonalphanum = PASSWORD_NONALPHANUM
;
8278 while ($nonalphanum > strlen($passwordnonalphanum)) {
8279 $passwordnonalphanum .= PASSWORD_NONALPHANUM
;
8282 // Now mix and shuffle it all.
8283 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8284 substr(str_shuffle ($passwordupper), 0, $upper) .
8285 substr(str_shuffle ($passworddigits), 0, $digits) .
8286 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8287 substr(str_shuffle ($passwordlower .
8290 $passwordnonalphanum), 0 , $additional));
8293 return substr ($password, 0, $maxlen);
8297 * Given a float, prints it nicely.
8298 * Localized floats must not be used in calculations!
8300 * The stripzeros feature is intended for making numbers look nicer in small
8301 * areas where it is not necessary to indicate the degree of accuracy by showing
8302 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8303 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8305 * @param float $float The float to print
8306 * @param int $decimalpoints The number of decimal places to print.
8307 * @param bool $localized use localized decimal separator
8308 * @param bool $stripzeros If true, removes final zeros after decimal point
8309 * @return string locale float
8311 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8312 if (is_null($float)) {
8316 $separator = get_string('decsep', 'langconfig');
8320 $result = number_format($float, $decimalpoints, $separator, '');
8322 // Remove zeros and final dot if not needed.
8323 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8329 * Converts locale specific floating point/comma number back to standard PHP float value
8330 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8332 * @param string $localefloat locale aware float representation
8333 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8334 * @return mixed float|bool - false or the parsed float.
8336 function unformat_float($localefloat, $strict = false) {
8337 $localefloat = trim($localefloat);
8339 if ($localefloat == '') {
8343 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8344 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8346 if ($strict && !is_numeric($localefloat)) {
8350 return (float)$localefloat;
8354 * Given a simple array, this shuffles it up just like shuffle()
8355 * Unlike PHP's shuffle() this function works on any machine.
8357 * @param array $array The array to be rearranged
8360 function swapshuffle($array) {
8362 $last = count($array) - 1;
8363 for ($i = 0; $i <= $last; $i++
) {
8364 $from = rand(0, $last);
8366 $array[$i] = $array[$from];
8367 $array[$from] = $curr;
8373 * Like {@link swapshuffle()}, but works on associative arrays
8375 * @param array $array The associative array to be rearranged
8378 function swapshuffle_assoc($array) {
8380 $newarray = array();
8381 $newkeys = swapshuffle(array_keys($array));
8383 foreach ($newkeys as $newkey) {
8384 $newarray[$newkey] = $array[$newkey];
8390 * Given an arbitrary array, and a number of draws,
8391 * this function returns an array with that amount
8392 * of items. The indexes are retained.
8394 * @todo Finish documenting this function
8396 * @param array $array
8400 function draw_rand_array($array, $draws) {
8404 $last = count($array);
8406 if ($draws > $last) {
8410 while ($draws > 0) {
8413 $keys = array_keys($array);
8414 $rand = rand(0, $last);
8416 $return[$keys[$rand]] = $array[$keys[$rand]];
8417 unset($array[$keys[$rand]]);
8426 * Calculate the difference between two microtimes
8428 * @param string $a The first Microtime
8429 * @param string $b The second Microtime
8432 function microtime_diff($a, $b) {
8433 list($adec, $asec) = explode(' ', $a);
8434 list($bdec, $bsec) = explode(' ', $b);
8435 return $bsec - $asec +
$bdec - $adec;
8439 * Given a list (eg a,b,c,d,e) this function returns
8440 * an array of 1->a, 2->b, 3->c etc
8442 * @param string $list The string to explode into array bits
8443 * @param string $separator The separator used within the list string
8444 * @return array The now assembled array
8446 function make_menu_from_list($list, $separator=',') {
8448 $array = array_reverse(explode($separator, $list), true);
8449 foreach ($array as $key => $item) {
8450 $outarray[$key+
1] = trim($item);
8456 * Creates an array that represents all the current grades that
8457 * can be chosen using the given grading type.
8460 * are scales, zero is no grade, and positive numbers are maximum
8463 * @todo Finish documenting this function or better deprecated this completely!
8465 * @param int $gradingtype
8468 function make_grades_menu($gradingtype) {
8472 if ($gradingtype < 0) {
8473 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8474 return make_menu_from_list($scale->scale
);
8476 } else if ($gradingtype > 0) {
8477 for ($i=$gradingtype; $i>=0; $i--) {
8478 $grades[$i] = $i .' / '. $gradingtype;
8486 * make_unique_id_code
8488 * @todo Finish documenting this function
8491 * @param string $extra Extra string to append to the end of the code
8494 function make_unique_id_code($extra = '') {
8496 $hostname = 'unknownhost';
8497 if (!empty($_SERVER['HTTP_HOST'])) {
8498 $hostname = $_SERVER['HTTP_HOST'];
8499 } else if (!empty($_ENV['HTTP_HOST'])) {
8500 $hostname = $_ENV['HTTP_HOST'];
8501 } else if (!empty($_SERVER['SERVER_NAME'])) {
8502 $hostname = $_SERVER['SERVER_NAME'];
8503 } else if (!empty($_ENV['SERVER_NAME'])) {
8504 $hostname = $_ENV['SERVER_NAME'];
8507 $date = gmdate("ymdHis");
8509 $random = random_string(6);
8512 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8514 return $hostname .'+'. $date .'+'. $random;
8520 * Function to check the passed address is within the passed subnet
8522 * The parameter is a comma separated string of subnet definitions.
8523 * Subnet strings can be in one of three formats:
8524 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8525 * 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)
8526 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8527 * Code for type 1 modified from user posted comments by mediator at
8528 * {@link http://au.php.net/manual/en/function.ip2long.php}
8530 * @param string $addr The address you are checking
8531 * @param string $subnetstr The string of subnet addresses
8534 function address_in_subnet($addr, $subnetstr) {
8536 if ($addr == '0.0.0.0') {
8539 $subnets = explode(',', $subnetstr);
8541 $addr = trim($addr);
8542 $addr = cleanremoteaddr($addr, false); // Normalise.
8543 if ($addr === null) {
8546 $addrparts = explode(':', $addr);
8548 $ipv6 = strpos($addr, ':');
8550 foreach ($subnets as $subnet) {
8551 $subnet = trim($subnet);
8552 if ($subnet === '') {
8556 if (strpos($subnet, '/') !== false) {
8557 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8558 list($ip, $mask) = explode('/', $subnet);
8559 $mask = trim($mask);
8560 if (!is_number($mask)) {
8561 continue; // Incorect mask number, eh?
8563 $ip = cleanremoteaddr($ip, false); // Normalise.
8567 if (strpos($ip, ':') !== false) {
8572 if ($mask > 128 or $mask < 0) {
8573 continue; // Nonsense.
8576 return true; // Any address.
8579 if ($ip === $addr) {
8584 $ipparts = explode(':', $ip);
8585 $modulo = $mask %
16;
8586 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8587 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8588 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8592 $pos = ($mask-$modulo)/16;
8593 $ipnet = hexdec($ipparts[$pos]);
8594 $addrnet = hexdec($addrparts[$pos]);
8595 $mask = 0xffff << (16 - $modulo);
8596 if (($addrnet & $mask) == ($ipnet & $mask)) {
8606 if ($mask > 32 or $mask < 0) {
8607 continue; // Nonsense.
8613 if ($ip === $addr) {
8618 $mask = 0xffffffff << (32 - $mask);
8619 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8624 } else if (strpos($subnet, '-') !== false) {
8625 // 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.
8626 $parts = explode('-', $subnet);
8627 if (count($parts) != 2) {
8631 if (strpos($subnet, ':') !== false) {
8636 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8637 if ($ipstart === null) {
8640 $ipparts = explode(':', $ipstart);
8641 $start = hexdec(array_pop($ipparts));
8642 $ipparts[] = trim($parts[1]);
8643 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8644 if ($ipend === null) {
8648 $ipnet = implode(':', $ipparts);
8649 if (strpos($addr, $ipnet) !== 0) {
8652 $ipparts = explode(':', $ipend);
8653 $end = hexdec($ipparts[7]);
8655 $addrend = hexdec($addrparts[7]);
8657 if (($addrend >= $start) and ($addrend <= $end)) {
8666 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8667 if ($ipstart === null) {
8670 $ipparts = explode('.', $ipstart);
8671 $ipparts[3] = trim($parts[1]);
8672 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8673 if ($ipend === null) {
8677 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8683 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8684 if (strpos($subnet, ':') !== false) {
8689 $parts = explode(':', $subnet);
8690 $count = count($parts);
8691 if ($parts[$count-1] === '') {
8692 unset($parts[$count-1]); // Trim trailing :'s.
8694 $subnet = implode('.', $parts);
8696 $isip = cleanremoteaddr($subnet, false); // Normalise.
8697 if ($isip !== null) {
8698 if ($isip === $addr) {
8702 } else if ($count > 8) {
8705 $zeros = array_fill(0, 8-$count, '0');
8706 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8707 if (address_in_subnet($addr, $subnet)) {
8716 $parts = explode('.', $subnet);
8717 $count = count($parts);
8718 if ($parts[$count-1] === '') {
8719 unset($parts[$count-1]); // Trim trailing .
8721 $subnet = implode('.', $parts);
8724 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8725 if ($subnet === $addr) {
8729 } else if ($count > 4) {
8732 $zeros = array_fill(0, 4-$count, '0');
8733 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8734 if (address_in_subnet($addr, $subnet)) {
8745 * For outputting debugging info
8747 * @param string $string The string to write
8748 * @param string $eol The end of line char(s) to use
8749 * @param string $sleep Period to make the application sleep
8750 * This ensures any messages have time to display before redirect
8752 function mtrace($string, $eol="\n", $sleep=0) {
8754 if (defined('STDOUT') && !PHPUNIT_TEST
&& !defined('BEHAT_TEST')) {
8755 fwrite(STDOUT
, $string.$eol);
8757 echo $string . $eol;
8762 // Delay to keep message on user's screen in case of subsequent redirect.
8769 * Replace 1 or more slashes or backslashes to 1 slash
8771 * @param string $path The path to strip
8772 * @return string the path with double slashes removed
8774 function cleardoubleslashes ($path) {
8775 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8779 * Is current ip in give list?
8781 * @param string $list
8784 function remoteip_in_list($list) {
8786 $clientip = getremoteaddr(null);
8789 // Ensure access on cli.
8793 $list = explode("\n", $list);
8794 foreach ($list as $subnet) {
8795 $subnet = trim($subnet);
8796 if (address_in_subnet($clientip, $subnet)) {
8805 * Returns most reliable client address
8807 * @param string $default If an address can't be determined, then return this
8808 * @return string The remote IP address
8810 function getremoteaddr($default='0.0.0.0') {
8813 if (empty($CFG->getremoteaddrconf
)) {
8814 // This will happen, for example, before just after the upgrade, as the
8815 // user is redirected to the admin screen.
8816 $variablestoskip = 0;
8818 $variablestoskip = $CFG->getremoteaddrconf
;
8820 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP
)) {
8821 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8822 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8823 return $address ?
$address : $default;
8826 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR
)) {
8827 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8828 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8829 $address = $forwardedaddresses[0];
8831 if (substr_count($address, ":") > 1) {
8832 // Remove port and brackets from IPv6.
8833 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8834 $address = $matches[1];
8837 // Remove port from IPv4.
8838 if (substr_count($address, ":") == 1) {
8839 $parts = explode(":", $address);
8840 $address = $parts[0];
8844 $address = cleanremoteaddr($address);
8845 return $address ?
$address : $default;
8848 if (!empty($_SERVER['REMOTE_ADDR'])) {
8849 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8850 return $address ?
$address : $default;
8857 * Cleans an ip address. Internal addresses are now allowed.
8858 * (Originally local addresses were not allowed.)
8860 * @param string $addr IPv4 or IPv6 address
8861 * @param bool $compress use IPv6 address compression
8862 * @return string normalised ip address string, null if error
8864 function cleanremoteaddr($addr, $compress=false) {
8865 $addr = trim($addr);
8867 if (strpos($addr, ':') !== false) {
8868 // Can be only IPv6.
8869 $parts = explode(':', $addr);
8870 $count = count($parts);
8872 if (strpos($parts[$count-1], '.') !== false) {
8873 // Legacy ipv4 notation.
8874 $last = array_pop($parts);
8875 $ipv4 = cleanremoteaddr($last, true);
8876 if ($ipv4 === null) {
8879 $bits = explode('.', $ipv4);
8880 $parts[] = dechex($bits[0]).dechex($bits[1]);
8881 $parts[] = dechex($bits[2]).dechex($bits[3]);
8882 $count = count($parts);
8883 $addr = implode(':', $parts);
8886 if ($count < 3 or $count > 8) {
8887 return null; // Severly malformed.
8891 if (strpos($addr, '::') === false) {
8892 return null; // Malformed.
8895 $insertat = array_search('', $parts, true);
8896 $missing = array_fill(0, 1 +
8 - $count, '0');
8897 array_splice($parts, $insertat, 1, $missing);
8898 foreach ($parts as $key => $part) {
8905 $adr = implode(':', $parts);
8906 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8907 return null; // Incorrect format - sorry.
8910 // Normalise 0s and case.
8911 $parts = array_map('hexdec', $parts);
8912 $parts = array_map('dechex', $parts);
8914 $result = implode(':', $parts);
8920 if ($result === '0:0:0:0:0:0:0:0') {
8921 return '::'; // All addresses.
8924 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8925 if ($compressed !== $result) {
8929 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8930 if ($compressed !== $result) {
8934 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8935 if ($compressed !== $result) {
8942 // First get all things that look like IPv4 addresses.
8944 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8949 foreach ($parts as $key => $match) {
8953 $parts[$key] = (int)$match; // Normalise 0s.
8956 return implode('.', $parts);
8961 * Is IP address a public address?
8963 * @param string $ip The ip to check
8964 * @return bool true if the ip is public
8966 function ip_is_public($ip) {
8967 return (bool) filter_var($ip, FILTER_VALIDATE_IP
, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
));
8971 * This function will make a complete copy of anything it's given,
8972 * regardless of whether it's an object or not.
8974 * @param mixed $thing Something you want cloned
8975 * @return mixed What ever it is you passed it
8977 function fullclone($thing) {
8978 return unserialize(serialize($thing));
8982 * Used to make sure that $min <= $value <= $max
8984 * Make sure that value is between min, and max
8986 * @param int $min The minimum value
8987 * @param int $value The value to check
8988 * @param int $max The maximum value
8991 function bounded_number($min, $value, $max) {
8992 if ($value < $min) {
8995 if ($value > $max) {
9002 * Check if there is a nested array within the passed array
9004 * @param array $array
9005 * @return bool true if there is a nested array false otherwise
9007 function array_is_nested($array) {
9008 foreach ($array as $value) {
9009 if (is_array($value)) {
9017 * get_performance_info() pairs up with init_performance_info()
9018 * loaded in setup.php. Returns an array with 'html' and 'txt'
9019 * values ready for use, and each of the individual stats provided
9020 * separately as well.
9024 function get_performance_info() {
9025 global $CFG, $PERF, $DB, $PAGE;
9028 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9031 if (!empty($CFG->themedesignermode
)) {
9032 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9033 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9035 $info['html'] .= '<ul class="list-unstyled m-l-1 row">'; // Holds userfriendly HTML representation.
9037 $info['realtime'] = microtime_diff($PERF->starttime
, microtime());
9039 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9040 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9042 if (function_exists('memory_get_usage')) {
9043 $info['memory_total'] = memory_get_usage();
9044 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory
;
9045 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9046 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9047 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9050 if (function_exists('memory_get_peak_usage')) {
9051 $info['memory_peak'] = memory_get_peak_usage();
9052 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9053 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9056 $info['html'] .= '</ul><ul class="list-unstyled m-l-1 row">';
9057 $inc = get_included_files();
9058 $info['includecount'] = count($inc);
9059 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9060 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9062 if (!empty($CFG->early_install_lang
) or empty($PAGE)) {
9063 // We can not track more performance before installation or before PAGE init, sorry.
9067 $filtermanager = filter_manager
::instance();
9068 if (method_exists($filtermanager, 'get_performance_summary')) {
9069 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9070 $info = array_merge($filterinfo, $info);
9071 foreach ($filterinfo as $key => $value) {
9072 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9073 $info['txt'] .= "$key: $value ";
9077 $stringmanager = get_string_manager();
9078 if (method_exists($stringmanager, 'get_performance_summary')) {
9079 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9080 $info = array_merge($filterinfo, $info);
9081 foreach ($filterinfo as $key => $value) {
9082 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9083 $info['txt'] .= "$key: $value ";
9087 if (!empty($PERF->logwrites
)) {
9088 $info['logwrites'] = $PERF->logwrites
;
9089 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9090 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9093 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites
);
9094 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9095 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9097 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9098 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9099 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9101 if (function_exists('posix_times')) {
9102 $ptimes = posix_times();
9103 if (is_array($ptimes)) {
9104 foreach ($ptimes as $key => $val) {
9105 $info[$key] = $ptimes[$key] - $PERF->startposixtimes
[$key];
9107 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9108 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9109 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9113 // Grab the load average for the last minute.
9114 // /proc will only work under some linux configurations
9115 // while uptime is there under MacOSX/Darwin and other unices.
9116 if (is_readable('/proc/loadavg') && $loadavg = @file
('/proc/loadavg')) {
9117 list($serverload) = explode(' ', $loadavg[0]);
9119 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `
/usr
/bin
/uptime`
) {
9120 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9121 $serverload = $matches[1];
9123 trigger_error('Could not parse uptime output!');
9126 if (!empty($serverload)) {
9127 $info['serverload'] = $serverload;
9128 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9129 $info['txt'] .= "serverload: {$info['serverload']} ";
9132 // Display size of session if session started.
9133 if ($si = \core\session\manager
::get_performance_info()) {
9134 $info['sessionsize'] = $si['size'];
9135 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9136 $info['txt'] .= $si['txt'];
9139 $info['html'] .= '</ul>';
9140 if ($stats = cache_helper
::get_stats()) {
9141 $html = '<ul class="cachesused list-unstyled m-l-1 row">';
9142 $html .= '<li class="cache-stats-heading font-weight-bold">Caches used (hits/misses/sets)</li>';
9143 $html .= '</ul><ul class="cachesused list-unstyled m-l-1">';
9144 $text = 'Caches used (hits/misses/sets): ';
9148 foreach ($stats as $definition => $details) {
9149 switch ($details['mode']) {
9150 case cache_store
::MODE_APPLICATION
:
9151 $modeclass = 'application';
9152 $mode = ' <span title="application cache">[a]</span>';
9154 case cache_store
::MODE_SESSION
:
9155 $modeclass = 'session';
9156 $mode = ' <span title="session cache">[s]</span>';
9158 case cache_store
::MODE_REQUEST
:
9159 $modeclass = 'request';
9160 $mode = ' <span title="request cache">[r]</span>';
9163 $html .= '<ul class="cache-definition-stats list-unstyled m-l-1 cache-mode-'.$modeclass.' card d-inline-block">';
9164 $html .= '<li class="cache-definition-stats-heading p-t-1 card-header bg-inverse font-weight-bold">' .
9165 $definition . $mode.'</li>';
9166 $text .= "$definition {";
9167 foreach ($details['stores'] as $store => $data) {
9168 $hits +
= $data['hits'];
9169 $misses +
= $data['misses'];
9170 $sets +
= $data['sets'];
9171 if ($data['hits'] == 0 and $data['misses'] > 0) {
9172 $cachestoreclass = 'nohits text-danger';
9173 } else if ($data['hits'] < $data['misses']) {
9174 $cachestoreclass = 'lowhits text-warning';
9176 $cachestoreclass = 'hihits text-success';
9178 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9179 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">" .
9180 "$store: $data[hits] / $data[misses] / $data[sets]</li>";
9181 // This makes boxes of same sizes.
9182 if (count($details['stores']) == 1) {
9183 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\"> </li>";
9190 $html .= "<div class='cache-total-stats row'>Total: $hits / $misses / $sets</div>";
9191 $info['cachesused'] = "$hits / $misses / $sets";
9192 $info['html'] .= $html;
9193 $info['txt'] .= $text.'. ';
9195 $info['cachesused'] = '0 / 0 / 0';
9196 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9197 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9200 $info['html'] = '<div class="performanceinfo siteinfo container-fluid">'.$info['html'].'</div>';
9205 * Delete directory or only its content
9207 * @param string $dir directory path
9208 * @param bool $contentonly
9209 * @return bool success, true also if dir does not exist
9211 function remove_dir($dir, $contentonly=false) {
9212 if (!file_exists($dir)) {
9216 if (!$handle = opendir($dir)) {
9220 while (false!==($item = readdir($handle))) {
9221 if ($item != '.' && $item != '..') {
9222 if (is_dir($dir.'/'.$item)) {
9223 $result = remove_dir($dir.'/'.$item) && $result;
9225 $result = unlink($dir.'/'.$item) && $result;
9231 clearstatcache(); // Make sure file stat cache is properly invalidated.
9234 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9235 clearstatcache(); // Make sure file stat cache is properly invalidated.
9240 * Detect if an object or a class contains a given property
9241 * will take an actual object or the name of a class
9243 * @param mix $obj Name of class or real object to test
9244 * @param string $property name of property to find
9245 * @return bool true if property exists
9247 function object_property_exists( $obj, $property ) {
9248 if (is_string( $obj )) {
9249 $properties = get_class_vars( $obj );
9251 $properties = get_object_vars( $obj );
9253 return array_key_exists( $property, $properties );
9257 * Converts an object into an associative array
9259 * This function converts an object into an associative array by iterating
9260 * over its public properties. Because this function uses the foreach
9261 * construct, Iterators are respected. It works recursively on arrays of objects.
9262 * Arrays and simple values are returned as is.
9264 * If class has magic properties, it can implement IteratorAggregate
9265 * and return all available properties in getIterator()
9270 function convert_to_array($var) {
9273 // Loop over elements/properties.
9274 foreach ($var as $key => $value) {
9275 // Recursively convert objects.
9276 if (is_object($value) ||
is_array($value)) {
9277 $result[$key] = convert_to_array($value);
9279 // Simple values are untouched.
9280 $result[$key] = $value;
9287 * Detect a custom script replacement in the data directory that will
9288 * replace an existing moodle script
9290 * @return string|bool full path name if a custom script exists, false if no custom script exists
9292 function custom_script_path() {
9293 global $CFG, $SCRIPT;
9295 if ($SCRIPT === null) {
9296 // Probably some weird external script.
9300 $scriptpath = $CFG->customscripts
. $SCRIPT;
9302 // Check the custom script exists.
9303 if (file_exists($scriptpath) and is_file($scriptpath)) {
9311 * Returns whether or not the user object is a remote MNET user. This function
9312 * is in moodlelib because it does not rely on loading any of the MNET code.
9314 * @param object $user A valid user object
9315 * @return bool True if the user is from a remote Moodle.
9317 function is_mnet_remote_user($user) {
9320 if (!isset($CFG->mnet_localhost_id
)) {
9321 include_once($CFG->dirroot
. '/mnet/lib.php');
9322 $env = new mnet_environment();
9327 return (!empty($user->mnethostid
) && $user->mnethostid
!= $CFG->mnet_localhost_id
);
9331 * This function will search for browser prefereed languages, setting Moodle
9332 * to use the best one available if $SESSION->lang is undefined
9334 function setup_lang_from_browser() {
9335 global $CFG, $SESSION, $USER;
9337 if (!empty($SESSION->lang
) or !empty($USER->lang
) or empty($CFG->autolang
)) {
9338 // Lang is defined in session or user profile, nothing to do.
9342 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9346 // Extract and clean langs from headers.
9347 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9348 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9349 $rawlangs = explode(',', $rawlangs); // Convert to array.
9353 foreach ($rawlangs as $lang) {
9354 if (strpos($lang, ';') === false) {
9355 $langs[(string)$order] = $lang;
9356 $order = $order-0.01;
9358 $parts = explode(';', $lang);
9359 $pos = strpos($parts[1], '=');
9360 $langs[substr($parts[1], $pos+
1)] = $parts[0];
9363 krsort($langs, SORT_NUMERIC
);
9365 // Look for such langs under standard locations.
9366 foreach ($langs as $lang) {
9367 // Clean it properly for include.
9368 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR
));
9369 if (get_string_manager()->translation_exists($lang, false)) {
9370 // Lang exists, set it in session.
9371 $SESSION->lang
= $lang;
9372 // We have finished. Go out.
9380 * Check if $url matches anything in proxybypass list
9382 * Any errors just result in the proxy being used (least bad)
9384 * @param string $url url to check
9385 * @return boolean true if we should bypass the proxy
9387 function is_proxybypass( $url ) {
9391 if (empty($CFG->proxyhost
) or empty($CFG->proxybypass
)) {
9395 // Get the host part out of the url.
9396 if (!$host = parse_url( $url, PHP_URL_HOST
)) {
9400 // Get the possible bypass hosts into an array.
9401 $matches = explode( ',', $CFG->proxybypass
);
9403 // Check for a match.
9404 // (IPs need to match the left hand side and hosts the right of the url,
9405 // but we can recklessly check both as there can't be a false +ve).
9406 foreach ($matches as $match) {
9407 $match = trim($match);
9409 // Try for IP match (Left side).
9410 $lhs = substr($host, 0, strlen($match));
9411 if (strcasecmp($match, $lhs)==0) {
9415 // Try for host match (Right side).
9416 $rhs = substr($host, -strlen($match));
9417 if (strcasecmp($match, $rhs)==0) {
9427 * Check if the passed navigation is of the new style
9429 * @param mixed $navigation
9430 * @return bool true for yes false for no
9432 function is_newnav($navigation) {
9433 if (is_array($navigation) && !empty($navigation['newnav'])) {
9441 * Checks whether the given variable name is defined as a variable within the given object.
9443 * This will NOT work with stdClass objects, which have no class variables.
9445 * @param string $var The variable name
9446 * @param object $object The object to check
9449 function in_object_vars($var, $object) {
9450 $classvars = get_class_vars(get_class($object));
9451 $classvars = array_keys($classvars);
9452 return in_array($var, $classvars);
9456 * Returns an array without repeated objects.
9457 * This function is similar to array_unique, but for arrays that have objects as values
9459 * @param array $array
9460 * @param bool $keepkeyassoc
9463 function object_array_unique($array, $keepkeyassoc = true) {
9464 $duplicatekeys = array();
9467 foreach ($array as $key => $val) {
9468 // Convert objects to arrays, in_array() does not support objects.
9469 if (is_object($val)) {
9473 if (!in_array($val, $tmp)) {
9476 $duplicatekeys[] = $key;
9480 foreach ($duplicatekeys as $key) {
9481 unset($array[$key]);
9484 return $keepkeyassoc ?
$array : array_values($array);
9488 * Is a userid the primary administrator?
9490 * @param int $userid int id of user to check
9493 function is_primary_admin($userid) {
9494 $primaryadmin = get_admin();
9496 if ($userid == $primaryadmin->id
) {
9504 * Returns the site identifier
9506 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9508 function get_site_identifier() {
9510 // Check to see if it is missing. If so, initialise it.
9511 if (empty($CFG->siteidentifier
)) {
9512 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9515 return $CFG->siteidentifier
;
9519 * Check whether the given password has no more than the specified
9520 * number of consecutive identical characters.
9522 * @param string $password password to be checked against the password policy
9523 * @param integer $maxchars maximum number of consecutive identical characters
9526 function check_consecutive_identical_characters($password, $maxchars) {
9528 if ($maxchars < 1) {
9529 return true; // Zero 0 is to disable this check.
9531 if (strlen($password) <= $maxchars) {
9532 return true; // Too short to fail this test.
9536 $consecutivecount = 1;
9537 foreach (str_split($password) as $char) {
9538 if ($char != $previouschar) {
9539 $consecutivecount = 1;
9541 $consecutivecount++
;
9542 if ($consecutivecount > $maxchars) {
9543 return false; // Check failed already.
9547 $previouschar = $char;
9554 * Helper function to do partial function binding.
9555 * so we can use it for preg_replace_callback, for example
9556 * this works with php functions, user functions, static methods and class methods
9557 * it returns you a callback that you can pass on like so:
9559 * $callback = partial('somefunction', $arg1, $arg2);
9561 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9563 * $obj = new someclass();
9564 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9566 * and then the arguments that are passed through at calltime are appended to the argument list.
9568 * @param mixed $function a php callback
9569 * @param mixed $arg1,... $argv arguments to partially bind with
9570 * @return array Array callback
9572 function partial() {
9573 if (!class_exists('partial')) {
9575 * Used to manage function binding.
9576 * @copyright 2009 Penny Leach
9577 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9581 public $values = array();
9582 /** @var string The function to call as a callback. */
9586 * @param string $func
9587 * @param array $args
9589 public function __construct($func, $args) {
9590 $this->values
= $args;
9591 $this->func
= $func;
9594 * Calls the callback function.
9597 public function method() {
9598 $args = func_get_args();
9599 return call_user_func_array($this->func
, array_merge($this->values
, $args));
9603 $args = func_get_args();
9604 $func = array_shift($args);
9605 $p = new partial($func, $args);
9606 return array($p, 'method');
9610 * helper function to load up and initialise the mnet environment
9611 * this must be called before you use mnet functions.
9613 * @return mnet_environment the equivalent of old $MNET global
9615 function get_mnet_environment() {
9617 require_once($CFG->dirroot
. '/mnet/lib.php');
9618 static $instance = null;
9619 if (empty($instance)) {
9620 $instance = new mnet_environment();
9627 * during xmlrpc server code execution, any code wishing to access
9628 * information about the remote peer must use this to get it.
9630 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9632 function get_mnet_remote_client() {
9633 if (!defined('MNET_SERVER')) {
9634 debugging(get_string('notinxmlrpcserver', 'mnet'));
9637 global $MNET_REMOTE_CLIENT;
9638 if (isset($MNET_REMOTE_CLIENT)) {
9639 return $MNET_REMOTE_CLIENT;
9645 * during the xmlrpc server code execution, this will be called
9646 * to setup the object returned by {@link get_mnet_remote_client}
9648 * @param mnet_remote_client $client the client to set up
9649 * @throws moodle_exception
9651 function set_mnet_remote_client($client) {
9652 if (!defined('MNET_SERVER')) {
9653 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9655 global $MNET_REMOTE_CLIENT;
9656 $MNET_REMOTE_CLIENT = $client;
9660 * return the jump url for a given remote user
9661 * this is used for rewriting forum post links in emails, etc
9663 * @param stdclass $user the user to get the idp url for
9665 function mnet_get_idp_jump_url($user) {
9668 static $mnetjumps = array();
9669 if (!array_key_exists($user->mnethostid
, $mnetjumps)) {
9670 $idp = mnet_get_peer_host($user->mnethostid
);
9671 $idpjumppath = mnet_get_app_jumppath($idp->applicationid
);
9672 $mnetjumps[$user->mnethostid
] = $idp->wwwroot
. $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot
. '&wantsurl=';
9674 return $mnetjumps[$user->mnethostid
];
9678 * Gets the homepage to use for the current user
9680 * @return int One of HOMEPAGE_*
9682 function get_home_page() {
9685 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage
)) {
9686 if ($CFG->defaulthomepage
== HOMEPAGE_MY
) {
9689 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY
);
9692 return HOMEPAGE_SITE
;
9696 * Gets the name of a course to be displayed when showing a list of courses.
9697 * By default this is just $course->fullname but user can configure it. The
9698 * result of this function should be passed through print_string.
9699 * @param stdClass|course_in_list $course Moodle course object
9700 * @return string Display name of course (either fullname or short + fullname)
9702 function get_course_display_name_for_list($course) {
9704 if (!empty($CFG->courselistshortnames
)) {
9705 if (!($course instanceof stdClass
)) {
9706 $course = (object)convert_to_array($course);
9708 return get_string('courseextendednamedisplay', '', $course);
9710 return $course->fullname
;
9715 * Safe analogue of unserialize() that can only parse arrays
9717 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
9718 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
9719 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
9721 * @param string $expression
9722 * @return array|bool either parsed array or false if parsing was impossible.
9724 function unserialize_array($expression) {
9726 // Find nested arrays, parse them and store in $subs , substitute with special string.
9727 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
9728 $key = '--SUB' . count($subs) . '--';
9729 $subs[$key] = unserialize_array($matches[2]);
9730 if ($subs[$key] === false) {
9733 $expression = str_replace($matches[2], $key . ';', $expression);
9736 // Check the expression is an array.
9737 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
9740 // Get the size and elements of an array (key;value;key;value;....).
9741 $parts = explode(';', $matches1[2]);
9742 $size = intval($matches1[1]);
9743 if (count($parts) < $size * 2 +
1) {
9746 // Analyze each part and make sure it is an integer or string or a substitute.
9748 for ($i = 0; $i < $size * 2; $i++
) {
9749 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
9750 $parts[$i] = (int)$matches2[1];
9751 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
9752 $parts[$i] = $matches3[2];
9753 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
9754 $parts[$i] = $subs[$parts[$i]];
9759 // Combine keys and values.
9760 for ($i = 0; $i < $size * 2; $i +
= 2) {
9761 $value[$parts[$i]] = $parts[$i+
1];
9767 * The lang_string class
9769 * This special class is used to create an object representation of a string request.
9770 * It is special because processing doesn't occur until the object is first used.
9771 * The class was created especially to aid performance in areas where strings were
9772 * required to be generated but were not necessarily used.
9773 * As an example the admin tree when generated uses over 1500 strings, of which
9774 * normally only 1/3 are ever actually printed at any time.
9775 * The performance advantage is achieved by not actually processing strings that
9776 * arn't being used, as such reducing the processing required for the page.
9778 * How to use the lang_string class?
9779 * There are two methods of using the lang_string class, first through the
9780 * forth argument of the get_string function, and secondly directly.
9781 * The following are examples of both.
9782 * 1. Through get_string calls e.g.
9783 * $string = get_string($identifier, $component, $a, true);
9784 * $string = get_string('yes', 'moodle', null, true);
9785 * 2. Direct instantiation
9786 * $string = new lang_string($identifier, $component, $a, $lang);
9787 * $string = new lang_string('yes');
9789 * How do I use a lang_string object?
9790 * The lang_string object makes use of a magic __toString method so that you
9791 * are able to use the object exactly as you would use a string in most cases.
9792 * This means you are able to collect it into a variable and then directly
9793 * echo it, or concatenate it into another string, or similar.
9794 * The other thing you can do is manually get the string by calling the
9795 * lang_strings out method e.g.
9796 * $string = new lang_string('yes');
9798 * Also worth noting is that the out method can take one argument, $lang which
9799 * allows the developer to change the language on the fly.
9801 * When should I use a lang_string object?
9802 * The lang_string object is designed to be used in any situation where a
9803 * string may not be needed, but needs to be generated.
9804 * The admin tree is a good example of where lang_string objects should be
9806 * A more practical example would be any class that requries strings that may
9807 * not be printed (after all classes get renderer by renderers and who knows
9808 * what they will do ;))
9810 * When should I not use a lang_string object?
9811 * Don't use lang_strings when you are going to use a string immediately.
9812 * There is no need as it will be processed immediately and there will be no
9813 * advantage, and in fact perhaps a negative hit as a class has to be
9814 * instantiated for a lang_string object, however get_string won't require
9818 * 1. You cannot use a lang_string object as an array offset. Doing so will
9819 * result in PHP throwing an error. (You can use it as an object property!)
9823 * @copyright 2011 Sam Hemelryk
9824 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9828 /** @var string The strings identifier */
9829 protected $identifier;
9830 /** @var string The strings component. Default '' */
9831 protected $component = '';
9832 /** @var array|stdClass Any arguments required for the string. Default null */
9833 protected $a = null;
9834 /** @var string The language to use when processing the string. Default null */
9835 protected $lang = null;
9837 /** @var string The processed string (once processed) */
9838 protected $string = null;
9841 * A special boolean. If set to true then the object has been woken up and
9842 * cannot be regenerated. If this is set then $this->string MUST be used.
9845 protected $forcedstring = false;
9848 * Constructs a lang_string object
9850 * This function should do as little processing as possible to ensure the best
9851 * performance for strings that won't be used.
9853 * @param string $identifier The strings identifier
9854 * @param string $component The strings component
9855 * @param stdClass|array $a Any arguments the string requires
9856 * @param string $lang The language to use when processing the string.
9857 * @throws coding_exception
9859 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9860 if (empty($component)) {
9861 $component = 'moodle';
9864 $this->identifier
= $identifier;
9865 $this->component
= $component;
9866 $this->lang
= $lang;
9868 // We MUST duplicate $a to ensure that it if it changes by reference those
9869 // changes are not carried across.
9870 // To do this we always ensure $a or its properties/values are strings
9871 // and that any properties/values that arn't convertable are forgotten.
9873 if (is_scalar($a)) {
9875 } else if ($a instanceof lang_string
) {
9876 $this->a
= $a->out();
9877 } else if (is_object($a) or is_array($a)) {
9880 foreach ($a as $key => $value) {
9881 // Make sure conversion errors don't get displayed (results in '').
9882 if (is_array($value)) {
9883 $this->a
[$key] = '';
9884 } else if (is_object($value)) {
9885 if (method_exists($value, '__toString')) {
9886 $this->a
[$key] = $value->__toString();
9888 $this->a
[$key] = '';
9891 $this->a
[$key] = (string)$value;
9897 if (debugging(false, DEBUG_DEVELOPER
)) {
9898 if (clean_param($this->identifier
, PARAM_STRINGID
) == '') {
9899 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9901 if (!empty($this->component
) && clean_param($this->component
, PARAM_COMPONENT
) == '') {
9902 throw new coding_exception('Invalid string compontent. Please check your string definition');
9904 if (!get_string_manager()->string_exists($this->identifier
, $this->component
)) {
9905 debugging('String does not exist. Please check your string definition for '.$this->identifier
.'/'.$this->component
, DEBUG_DEVELOPER
);
9911 * Processes the string.
9913 * This function actually processes the string, stores it in the string property
9914 * and then returns it.
9915 * You will notice that this function is VERY similar to the get_string method.
9916 * That is because it is pretty much doing the same thing.
9917 * However as this function is an upgrade it isn't as tolerant to backwards
9921 * @throws coding_exception
9923 protected function get_string() {
9926 // Check if we need to process the string.
9927 if ($this->string === null) {
9928 // Check the quality of the identifier.
9929 if ($CFG->debugdeveloper
&& clean_param($this->identifier
, PARAM_STRINGID
) === '') {
9930 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
);
9933 // Process the string.
9934 $this->string = get_string_manager()->get_string($this->identifier
, $this->component
, $this->a
, $this->lang
);
9935 // Debugging feature lets you display string identifier and component.
9936 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
9937 $this->string .= ' {' . $this->identifier
. '/' . $this->component
. '}';
9940 // Return the string.
9941 return $this->string;
9945 * Returns the string
9947 * @param string $lang The langauge to use when processing the string
9950 public function out($lang = null) {
9951 if ($lang !== null && $lang != $this->lang
&& ($this->lang
== null && $lang != current_language())) {
9952 if ($this->forcedstring
) {
9953 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang
.' used)', DEBUG_DEVELOPER
);
9954 return $this->get_string();
9956 $translatedstring = new lang_string($this->identifier
, $this->component
, $this->a
, $lang);
9957 return $translatedstring->out();
9959 return $this->get_string();
9963 * Magic __toString method for printing a string
9967 public function __toString() {
9968 return $this->get_string();
9972 * Magic __set_state method used for var_export
9976 public function __set_state() {
9977 return $this->get_string();
9981 * Prepares the lang_string for sleep and stores only the forcedstring and
9982 * string properties... the string cannot be regenerated so we need to ensure
9983 * it is generated for this.
9987 public function __sleep() {
9988 $this->get_string();
9989 $this->forcedstring
= true;
9990 return array('forcedstring', 'string', 'lang');