Merge branch 'wip-mdl-56616' of https://github.com/rajeshtaneja/moodle
[moodle.git] / lib / moodlelib.php
blob8bdfa86a2972a58195dc0ac66c515a1e5e6c39fa
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * moodlelib.php - Moodle main library
20 * Main library file of miscellaneous general-purpose Moodle functions.
21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - datalib.php - functions that access the database
25 * @package core
26 * @subpackage lib
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') || die();
33 // CONSTANTS (Encased in phpdoc proper comments).
35 // Date and time constants.
36 /**
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
41 /**
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
46 /**
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
51 /**
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
56 /**
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
61 /**
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
66 /**
67 * Time constant - the number of minutes in an hour
69 define('HOURMINS', 60);
71 // Parameter constants - every call to optional_param(), required_param()
72 // or clean_param() should have a specified type of parameter.
74 /**
75 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
77 define('PARAM_ALPHA', 'alpha');
79 /**
80 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
81 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
83 define('PARAM_ALPHAEXT', 'alphaext');
85 /**
86 * PARAM_ALPHANUM - expected numbers and letters only.
88 define('PARAM_ALPHANUM', 'alphanum');
90 /**
91 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
95 /**
96 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
98 define('PARAM_AUTH', 'auth');
101 * PARAM_BASE64 - Base 64 encoded format
103 define('PARAM_BASE64', 'base64');
106 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
108 define('PARAM_BOOL', 'bool');
111 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
112 * checked against the list of capabilities in the database.
114 define('PARAM_CAPABILITY', 'capability');
117 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118 * to use this. The normal mode of operation is to use PARAM_RAW when recieving
119 * the input (required/optional_param or formslib) and then sanitse the HTML
120 * using format_text on output. This is for the rare cases when you want to
121 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
123 define('PARAM_CLEANHTML', 'cleanhtml');
126 * PARAM_EMAIL - an email address following the RFC
128 define('PARAM_EMAIL', 'email');
131 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
133 define('PARAM_FILE', 'file');
136 * PARAM_FLOAT - a real/floating point number.
138 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
139 * It does not work for languages that use , as a decimal separator.
140 * Instead, do something like
141 * $rawvalue = required_param('name', PARAM_RAW);
142 * // ... other code including require_login, which sets current lang ...
143 * $realvalue = unformat_float($rawvalue);
144 * // ... then use $realvalue
146 define('PARAM_FLOAT', 'float');
149 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
151 define('PARAM_HOST', 'host');
154 * PARAM_INT - integers only, use when expecting only numbers.
156 define('PARAM_INT', 'int');
159 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
161 define('PARAM_LANG', 'lang');
164 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
165 * others! Implies PARAM_URL!)
167 define('PARAM_LOCALURL', 'localurl');
170 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
172 define('PARAM_NOTAGS', 'notags');
175 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
176 * traversals note: the leading slash is not removed, window drive letter is not allowed
178 define('PARAM_PATH', 'path');
181 * PARAM_PEM - Privacy Enhanced Mail format
183 define('PARAM_PEM', 'pem');
186 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
188 define('PARAM_PERMISSION', 'permission');
191 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
193 define('PARAM_RAW', 'raw');
196 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
198 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
201 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
203 define('PARAM_SAFEDIR', 'safedir');
206 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
208 define('PARAM_SAFEPATH', 'safepath');
211 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
213 define('PARAM_SEQUENCE', 'sequence');
216 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
218 define('PARAM_TAG', 'tag');
221 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
223 define('PARAM_TAGLIST', 'taglist');
226 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
228 define('PARAM_TEXT', 'text');
231 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
233 define('PARAM_THEME', 'theme');
236 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
237 * http://localhost.localdomain/ is ok.
239 define('PARAM_URL', 'url');
242 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
243 * accounts, do NOT use when syncing with external systems!!
245 define('PARAM_USERNAME', 'username');
248 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
250 define('PARAM_STRINGID', 'stringid');
252 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
254 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
255 * It was one of the first types, that is why it is abused so much ;-)
256 * @deprecated since 2.0
258 define('PARAM_CLEAN', 'clean');
261 * PARAM_INTEGER - deprecated alias for PARAM_INT
262 * @deprecated since 2.0
264 define('PARAM_INTEGER', 'int');
267 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
268 * @deprecated since 2.0
270 define('PARAM_NUMBER', 'float');
273 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
274 * NOTE: originally alias for PARAM_APLHA
275 * @deprecated since 2.0
277 define('PARAM_ACTION', 'alphanumext');
280 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
281 * NOTE: originally alias for PARAM_APLHA
282 * @deprecated since 2.0
284 define('PARAM_FORMAT', 'alphanumext');
287 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
288 * @deprecated since 2.0
290 define('PARAM_MULTILANG', 'text');
293 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
294 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
295 * America/Port-au-Prince)
297 define('PARAM_TIMEZONE', 'timezone');
300 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
302 define('PARAM_CLEANFILE', 'file');
305 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
306 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
307 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308 * NOTE: numbers and underscores are strongly discouraged in plugin names!
310 define('PARAM_COMPONENT', 'component');
313 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
314 * It is usually used together with context id and component.
315 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
317 define('PARAM_AREA', 'area');
320 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
321 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
324 define('PARAM_PLUGIN', 'plugin');
327 // Web Services.
330 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
332 define('VALUE_REQUIRED', 1);
335 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
337 define('VALUE_OPTIONAL', 2);
340 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
342 define('VALUE_DEFAULT', 0);
345 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
347 define('NULL_NOT_ALLOWED', false);
350 * NULL_ALLOWED - the parameter can be set to null in the database
352 define('NULL_ALLOWED', true);
354 // Page types.
357 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
359 define('PAGE_COURSE_VIEW', 'course-view');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363 /** Get remote addr constant */
364 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
366 // Blog access level constant declaration.
367 define ('BLOG_USER_LEVEL', 1);
368 define ('BLOG_GROUP_LEVEL', 2);
369 define ('BLOG_COURSE_LEVEL', 3);
370 define ('BLOG_SITE_LEVEL', 4);
371 define ('BLOG_GLOBAL_LEVEL', 5);
374 // Tag constants.
376 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
377 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
380 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
382 define('TAG_MAX_LENGTH', 50);
384 // Password policy constants.
385 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387 define ('PASSWORD_DIGITS', '0123456789');
388 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
390 // Feature constants.
391 // Used for plugin_supports() to report features that are, or are not, supported by a module.
393 /** True if module can provide a grade */
394 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
395 /** True if module supports outcomes */
396 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
397 /** True if module supports advanced grading methods */
398 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
399 /** True if module controls the grade visibility over the gradebook */
400 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
401 /** True if module supports plagiarism plugins */
402 define('FEATURE_PLAGIARISM', 'plagiarism');
404 /** True if module has code to track whether somebody viewed it */
405 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
406 /** True if module has custom completion rules */
407 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
409 /** True if module has no 'view' page (like label) */
410 define('FEATURE_NO_VIEW_LINK', 'viewlink');
411 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
418 * True if module supports groupmembersonly (which no longer exists)
419 * @deprecated Since Moodle 2.8
421 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
423 /** Type of module */
424 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
425 /** True if module supports intro editor */
426 define('FEATURE_MOD_INTRO', 'mod_intro');
427 /** True if module has default completion */
428 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
430 define('FEATURE_COMMENT', 'comment');
432 define('FEATURE_RATE', 'rate');
433 /** True if module supports backup/restore of moodle2 format */
434 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
436 /** True if module can show description on course main page */
437 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
439 /** True if module uses the question bank */
440 define('FEATURE_USES_QUESTIONS', 'usesquestions');
442 /** Unspecified module archetype */
443 define('MOD_ARCHETYPE_OTHER', 0);
444 /** Resource-like type module */
445 define('MOD_ARCHETYPE_RESOURCE', 1);
446 /** Assignment module archetype */
447 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
448 /** System (not user-addable) module archetype */
449 define('MOD_ARCHETYPE_SYSTEM', 3);
452 * Return this from modname_get_types callback to use default display in activity chooser.
453 * Deprecated, will be removed in 3.5, TODO MDL-53697.
454 * @deprecated since Moodle 3.1
456 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
459 * Security token used for allowing access
460 * from external application such as web services.
461 * Scripts do not use any session, performance is relatively
462 * low because we need to load access info in each request.
463 * Scripts are executed in parallel.
465 define('EXTERNAL_TOKEN_PERMANENT', 0);
468 * Security token used for allowing access
469 * of embedded applications, the code is executed in the
470 * active user session. Token is invalidated after user logs out.
471 * Scripts are executed serially - normal session locking is used.
473 define('EXTERNAL_TOKEN_EMBEDDED', 1);
476 * The home page should be the site home
478 define('HOMEPAGE_SITE', 0);
480 * The home page should be the users my page
482 define('HOMEPAGE_MY', 1);
484 * The home page can be chosen by the user
486 define('HOMEPAGE_USER', 2);
489 * Hub directory url (should be moodle.org)
491 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
495 * Moodle.org url (should be moodle.org)
497 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
500 * Moodle mobile app service name
502 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
505 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
507 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
510 * Course display settings: display all sections on one page.
512 define('COURSE_DISPLAY_SINGLEPAGE', 0);
514 * Course display settings: split pages into a page per section.
516 define('COURSE_DISPLAY_MULTIPAGE', 1);
519 * Authentication constant: String used in password field when password is not stored.
521 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
524 * Email from header to never include via information.
526 define('EMAIL_VIA_NEVER', 0);
529 * Email from header to always include via information.
531 define('EMAIL_VIA_ALWAYS', 1);
534 * Email from header to only include via information if the address is no-reply.
536 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
538 // PARAMETER HANDLING.
541 * Returns a particular value for the named variable, taken from
542 * POST or GET. If the parameter doesn't exist then an error is
543 * thrown because we require this variable.
545 * This function should be used to initialise all required values
546 * in a script that are based on parameters. Usually it will be
547 * used like this:
548 * $id = required_param('id', PARAM_INT);
550 * Please note the $type parameter is now required and the value can not be array.
552 * @param string $parname the name of the page parameter we want
553 * @param string $type expected type of parameter
554 * @return mixed
555 * @throws coding_exception
557 function required_param($parname, $type) {
558 if (func_num_args() != 2 or empty($parname) or empty($type)) {
559 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
561 // POST has precedence.
562 if (isset($_POST[$parname])) {
563 $param = $_POST[$parname];
564 } else if (isset($_GET[$parname])) {
565 $param = $_GET[$parname];
566 } else {
567 print_error('missingparam', '', '', $parname);
570 if (is_array($param)) {
571 debugging('Invalid array parameter detected in required_param(): '.$parname);
572 // TODO: switch to fatal error in Moodle 2.3.
573 return required_param_array($parname, $type);
576 return clean_param($param, $type);
580 * Returns a particular array value for the named variable, taken from
581 * POST or GET. If the parameter doesn't exist then an error is
582 * thrown because we require this variable.
584 * This function should be used to initialise all required values
585 * in a script that are based on parameters. Usually it will be
586 * used like this:
587 * $ids = required_param_array('ids', PARAM_INT);
589 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
591 * @param string $parname the name of the page parameter we want
592 * @param string $type expected type of parameter
593 * @return array
594 * @throws coding_exception
596 function required_param_array($parname, $type) {
597 if (func_num_args() != 2 or empty($parname) or empty($type)) {
598 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
600 // POST has precedence.
601 if (isset($_POST[$parname])) {
602 $param = $_POST[$parname];
603 } else if (isset($_GET[$parname])) {
604 $param = $_GET[$parname];
605 } else {
606 print_error('missingparam', '', '', $parname);
608 if (!is_array($param)) {
609 print_error('missingparam', '', '', $parname);
612 $result = array();
613 foreach ($param as $key => $value) {
614 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
615 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
616 continue;
618 $result[$key] = clean_param($value, $type);
621 return $result;
625 * Returns a particular value for the named variable, taken from
626 * POST or GET, otherwise returning a given default.
628 * This function should be used to initialise all optional values
629 * in a script that are based on parameters. Usually it will be
630 * used like this:
631 * $name = optional_param('name', 'Fred', PARAM_TEXT);
633 * Please note the $type parameter is now required and the value can not be array.
635 * @param string $parname the name of the page parameter we want
636 * @param mixed $default the default value to return if nothing is found
637 * @param string $type expected type of parameter
638 * @return mixed
639 * @throws coding_exception
641 function optional_param($parname, $default, $type) {
642 if (func_num_args() != 3 or empty($parname) or empty($type)) {
643 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
646 // POST has precedence.
647 if (isset($_POST[$parname])) {
648 $param = $_POST[$parname];
649 } else if (isset($_GET[$parname])) {
650 $param = $_GET[$parname];
651 } else {
652 return $default;
655 if (is_array($param)) {
656 debugging('Invalid array parameter detected in required_param(): '.$parname);
657 // TODO: switch to $default in Moodle 2.3.
658 return optional_param_array($parname, $default, $type);
661 return clean_param($param, $type);
665 * Returns a particular array value for the named variable, taken from
666 * POST or GET, otherwise returning a given default.
668 * This function should be used to initialise all optional values
669 * in a script that are based on parameters. Usually it will be
670 * used like this:
671 * $ids = optional_param('id', array(), PARAM_INT);
673 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
675 * @param string $parname the name of the page parameter we want
676 * @param mixed $default the default value to return if nothing is found
677 * @param string $type expected type of parameter
678 * @return array
679 * @throws coding_exception
681 function optional_param_array($parname, $default, $type) {
682 if (func_num_args() != 3 or empty($parname) or empty($type)) {
683 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
686 // POST has precedence.
687 if (isset($_POST[$parname])) {
688 $param = $_POST[$parname];
689 } else if (isset($_GET[$parname])) {
690 $param = $_GET[$parname];
691 } else {
692 return $default;
694 if (!is_array($param)) {
695 debugging('optional_param_array() expects array parameters only: '.$parname);
696 return $default;
699 $result = array();
700 foreach ($param as $key => $value) {
701 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
702 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
703 continue;
705 $result[$key] = clean_param($value, $type);
708 return $result;
712 * Strict validation of parameter values, the values are only converted
713 * to requested PHP type. Internally it is using clean_param, the values
714 * before and after cleaning must be equal - otherwise
715 * an invalid_parameter_exception is thrown.
716 * Objects and classes are not accepted.
718 * @param mixed $param
719 * @param string $type PARAM_ constant
720 * @param bool $allownull are nulls valid value?
721 * @param string $debuginfo optional debug information
722 * @return mixed the $param value converted to PHP type
723 * @throws invalid_parameter_exception if $param is not of given type
725 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
726 if (is_null($param)) {
727 if ($allownull == NULL_ALLOWED) {
728 return null;
729 } else {
730 throw new invalid_parameter_exception($debuginfo);
733 if (is_array($param) or is_object($param)) {
734 throw new invalid_parameter_exception($debuginfo);
737 $cleaned = clean_param($param, $type);
739 if ($type == PARAM_FLOAT) {
740 // Do not detect precision loss here.
741 if (is_float($param) or is_int($param)) {
742 // These always fit.
743 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
744 throw new invalid_parameter_exception($debuginfo);
746 } else if ((string)$param !== (string)$cleaned) {
747 // Conversion to string is usually lossless.
748 throw new invalid_parameter_exception($debuginfo);
751 return $cleaned;
755 * Makes sure array contains only the allowed types, this function does not validate array key names!
757 * <code>
758 * $options = clean_param($options, PARAM_INT);
759 * </code>
761 * @param array $param the variable array we are cleaning
762 * @param string $type expected format of param after cleaning.
763 * @param bool $recursive clean recursive arrays
764 * @return array
765 * @throws coding_exception
767 function clean_param_array(array $param = null, $type, $recursive = false) {
768 // Convert null to empty array.
769 $param = (array)$param;
770 foreach ($param as $key => $value) {
771 if (is_array($value)) {
772 if ($recursive) {
773 $param[$key] = clean_param_array($value, $type, true);
774 } else {
775 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
777 } else {
778 $param[$key] = clean_param($value, $type);
781 return $param;
785 * Used by {@link optional_param()} and {@link required_param()} to
786 * clean the variables and/or cast to specific types, based on
787 * an options field.
788 * <code>
789 * $course->format = clean_param($course->format, PARAM_ALPHA);
790 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
791 * </code>
793 * @param mixed $param the variable we are cleaning
794 * @param string $type expected format of param after cleaning.
795 * @return mixed
796 * @throws coding_exception
798 function clean_param($param, $type) {
799 global $CFG;
801 if (is_array($param)) {
802 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
803 } else if (is_object($param)) {
804 if (method_exists($param, '__toString')) {
805 $param = $param->__toString();
806 } else {
807 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
811 switch ($type) {
812 case PARAM_RAW:
813 // No cleaning at all.
814 $param = fix_utf8($param);
815 return $param;
817 case PARAM_RAW_TRIMMED:
818 // No cleaning, but strip leading and trailing whitespace.
819 $param = fix_utf8($param);
820 return trim($param);
822 case PARAM_CLEAN:
823 // General HTML cleaning, try to use more specific type if possible this is deprecated!
824 // Please use more specific type instead.
825 if (is_numeric($param)) {
826 return $param;
828 $param = fix_utf8($param);
829 // Sweep for scripts, etc.
830 return clean_text($param);
832 case PARAM_CLEANHTML:
833 // Clean html fragment.
834 $param = fix_utf8($param);
835 // Sweep for scripts, etc.
836 $param = clean_text($param, FORMAT_HTML);
837 return trim($param);
839 case PARAM_INT:
840 // Convert to integer.
841 return (int)$param;
843 case PARAM_FLOAT:
844 // Convert to float.
845 return (float)$param;
847 case PARAM_ALPHA:
848 // Remove everything not `a-z`.
849 return preg_replace('/[^a-zA-Z]/i', '', $param);
851 case PARAM_ALPHAEXT:
852 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
853 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
855 case PARAM_ALPHANUM:
856 // Remove everything not `a-zA-Z0-9`.
857 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
859 case PARAM_ALPHANUMEXT:
860 // Remove everything not `a-zA-Z0-9_-`.
861 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
863 case PARAM_SEQUENCE:
864 // Remove everything not `0-9,`.
865 return preg_replace('/[^0-9,]/i', '', $param);
867 case PARAM_BOOL:
868 // Convert to 1 or 0.
869 $tempstr = strtolower($param);
870 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
871 $param = 1;
872 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
873 $param = 0;
874 } else {
875 $param = empty($param) ? 0 : 1;
877 return $param;
879 case PARAM_NOTAGS:
880 // Strip all tags.
881 $param = fix_utf8($param);
882 return strip_tags($param);
884 case PARAM_TEXT:
885 // Leave only tags needed for multilang.
886 $param = fix_utf8($param);
887 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
888 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
889 do {
890 if (strpos($param, '</lang>') !== false) {
891 // Old and future mutilang syntax.
892 $param = strip_tags($param, '<lang>');
893 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
894 break;
896 $open = false;
897 foreach ($matches[0] as $match) {
898 if ($match === '</lang>') {
899 if ($open) {
900 $open = false;
901 continue;
902 } else {
903 break 2;
906 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
907 break 2;
908 } else {
909 $open = true;
912 if ($open) {
913 break;
915 return $param;
917 } else if (strpos($param, '</span>') !== false) {
918 // Current problematic multilang syntax.
919 $param = strip_tags($param, '<span>');
920 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
921 break;
923 $open = false;
924 foreach ($matches[0] as $match) {
925 if ($match === '</span>') {
926 if ($open) {
927 $open = false;
928 continue;
929 } else {
930 break 2;
933 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
934 break 2;
935 } else {
936 $open = true;
939 if ($open) {
940 break;
942 return $param;
944 } while (false);
945 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
946 return strip_tags($param);
948 case PARAM_COMPONENT:
949 // We do not want any guessing here, either the name is correct or not
950 // please note only normalised component names are accepted.
951 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
952 return '';
954 if (strpos($param, '__') !== false) {
955 return '';
957 if (strpos($param, 'mod_') === 0) {
958 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
959 if (substr_count($param, '_') != 1) {
960 return '';
963 return $param;
965 case PARAM_PLUGIN:
966 case PARAM_AREA:
967 // We do not want any guessing here, either the name is correct or not.
968 if (!is_valid_plugin_name($param)) {
969 return '';
971 return $param;
973 case PARAM_SAFEDIR:
974 // Remove everything not a-zA-Z0-9_- .
975 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
977 case PARAM_SAFEPATH:
978 // Remove everything not a-zA-Z0-9/_- .
979 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
981 case PARAM_FILE:
982 // Strip all suspicious characters from filename.
983 $param = fix_utf8($param);
984 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
985 if ($param === '.' || $param === '..') {
986 $param = '';
988 return $param;
990 case PARAM_PATH:
991 // Strip all suspicious characters from file path.
992 $param = fix_utf8($param);
993 $param = str_replace('\\', '/', $param);
995 // Explode the path and clean each element using the PARAM_FILE rules.
996 $breadcrumb = explode('/', $param);
997 foreach ($breadcrumb as $key => $crumb) {
998 if ($crumb === '.' && $key === 0) {
999 // Special condition to allow for relative current path such as ./currentdirfile.txt.
1000 } else {
1001 $crumb = clean_param($crumb, PARAM_FILE);
1003 $breadcrumb[$key] = $crumb;
1005 $param = implode('/', $breadcrumb);
1007 // Remove multiple current path (./././) and multiple slashes (///).
1008 $param = preg_replace('~//+~', '/', $param);
1009 $param = preg_replace('~/(\./)+~', '/', $param);
1010 return $param;
1012 case PARAM_HOST:
1013 // Allow FQDN or IPv4 dotted quad.
1014 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1015 // Match ipv4 dotted quad.
1016 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1017 // Confirm values are ok.
1018 if ( $match[0] > 255
1019 || $match[1] > 255
1020 || $match[3] > 255
1021 || $match[4] > 255 ) {
1022 // Hmmm, what kind of dotted quad is this?
1023 $param = '';
1025 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1026 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1027 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1029 // All is ok - $param is respected.
1030 } else {
1031 // All is not ok...
1032 $param='';
1034 return $param;
1036 case PARAM_URL: // Allow safe ftp, http, mailto urls.
1037 $param = fix_utf8($param);
1038 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1039 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1040 // All is ok, param is respected.
1041 } else {
1042 // Not really ok.
1043 $param ='';
1045 return $param;
1047 case PARAM_LOCALURL:
1048 // Allow http absolute, root relative and relative URLs within wwwroot.
1049 $param = clean_param($param, PARAM_URL);
1050 if (!empty($param)) {
1052 // Simulate the HTTPS version of the site.
1053 $httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot);
1055 if ($param === $CFG->wwwroot) {
1056 // Exact match;
1057 } else if (!empty($CFG->loginhttps) && $param === $httpswwwroot) {
1058 // Exact match;
1059 } else if (preg_match(':^/:', $param)) {
1060 // Root-relative, ok!
1061 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1062 // Absolute, and matches our wwwroot.
1063 } else if (!empty($CFG->loginhttps) && preg_match('/^' . preg_quote($httpswwwroot . '/', '/') . '/i', $param)) {
1064 // Absolute, and matches our httpswwwroot.
1065 } else {
1066 // Relative - let's make sure there are no tricks.
1067 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1068 // Looks ok.
1069 } else {
1070 $param = '';
1074 return $param;
1076 case PARAM_PEM:
1077 $param = trim($param);
1078 // PEM formatted strings may contain letters/numbers and the symbols:
1079 // forward slash: /
1080 // plus sign: +
1081 // equal sign: =
1082 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1083 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1084 list($wholething, $body) = $matches;
1085 unset($wholething, $matches);
1086 $b64 = clean_param($body, PARAM_BASE64);
1087 if (!empty($b64)) {
1088 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1089 } else {
1090 return '';
1093 return '';
1095 case PARAM_BASE64:
1096 if (!empty($param)) {
1097 // PEM formatted strings may contain letters/numbers and the symbols
1098 // forward slash: /
1099 // plus sign: +
1100 // equal sign: =.
1101 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1102 return '';
1104 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1105 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1106 // than (or equal to) 64 characters long.
1107 for ($i=0, $j=count($lines); $i < $j; $i++) {
1108 if ($i + 1 == $j) {
1109 if (64 < strlen($lines[$i])) {
1110 return '';
1112 continue;
1115 if (64 != strlen($lines[$i])) {
1116 return '';
1119 return implode("\n", $lines);
1120 } else {
1121 return '';
1124 case PARAM_TAG:
1125 $param = fix_utf8($param);
1126 // Please note it is not safe to use the tag name directly anywhere,
1127 // it must be processed with s(), urlencode() before embedding anywhere.
1128 // Remove some nasties.
1129 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1130 // Convert many whitespace chars into one.
1131 $param = preg_replace('/\s+/u', ' ', $param);
1132 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1133 return $param;
1135 case PARAM_TAGLIST:
1136 $param = fix_utf8($param);
1137 $tags = explode(',', $param);
1138 $result = array();
1139 foreach ($tags as $tag) {
1140 $res = clean_param($tag, PARAM_TAG);
1141 if ($res !== '') {
1142 $result[] = $res;
1145 if ($result) {
1146 return implode(',', $result);
1147 } else {
1148 return '';
1151 case PARAM_CAPABILITY:
1152 if (get_capability_info($param)) {
1153 return $param;
1154 } else {
1155 return '';
1158 case PARAM_PERMISSION:
1159 $param = (int)$param;
1160 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1161 return $param;
1162 } else {
1163 return CAP_INHERIT;
1166 case PARAM_AUTH:
1167 $param = clean_param($param, PARAM_PLUGIN);
1168 if (empty($param)) {
1169 return '';
1170 } else if (exists_auth_plugin($param)) {
1171 return $param;
1172 } else {
1173 return '';
1176 case PARAM_LANG:
1177 $param = clean_param($param, PARAM_SAFEDIR);
1178 if (get_string_manager()->translation_exists($param)) {
1179 return $param;
1180 } else {
1181 // Specified language is not installed or param malformed.
1182 return '';
1185 case PARAM_THEME:
1186 $param = clean_param($param, PARAM_PLUGIN);
1187 if (empty($param)) {
1188 return '';
1189 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1190 return $param;
1191 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1192 return $param;
1193 } else {
1194 // Specified theme is not installed.
1195 return '';
1198 case PARAM_USERNAME:
1199 $param = fix_utf8($param);
1200 $param = trim($param);
1201 // Convert uppercase to lowercase MDL-16919.
1202 $param = core_text::strtolower($param);
1203 if (empty($CFG->extendedusernamechars)) {
1204 $param = str_replace(" " , "", $param);
1205 // Regular expression, eliminate all chars EXCEPT:
1206 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1207 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1209 return $param;
1211 case PARAM_EMAIL:
1212 $param = fix_utf8($param);
1213 if (validate_email($param)) {
1214 return $param;
1215 } else {
1216 return '';
1219 case PARAM_STRINGID:
1220 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1221 return $param;
1222 } else {
1223 return '';
1226 case PARAM_TIMEZONE:
1227 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1228 $param = fix_utf8($param);
1229 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1230 if (preg_match($timezonepattern, $param)) {
1231 return $param;
1232 } else {
1233 return '';
1236 default:
1237 // Doh! throw error, switched parameters in optional_param or another serious problem.
1238 print_error("unknownparamtype", '', '', $type);
1243 * Whether the PARAM_* type is compatible in RTL.
1245 * Being compatible with RTL means that the data they contain can flow
1246 * from right-to-left or left-to-right without compromising the user experience.
1248 * Take URLs for example, they are not RTL compatible as they should always
1249 * flow from the left to the right. This also applies to numbers, email addresses,
1250 * configuration snippets, base64 strings, etc...
1252 * This function tries to best guess which parameters can contain localised strings.
1254 * @param string $paramtype Constant PARAM_*.
1255 * @return bool
1257 function is_rtl_compatible($paramtype) {
1258 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1262 * Makes sure the data is using valid utf8, invalid characters are discarded.
1264 * Note: this function is not intended for full objects with methods and private properties.
1266 * @param mixed $value
1267 * @return mixed with proper utf-8 encoding
1269 function fix_utf8($value) {
1270 if (is_null($value) or $value === '') {
1271 return $value;
1273 } else if (is_string($value)) {
1274 if ((string)(int)$value === $value) {
1275 // Shortcut.
1276 return $value;
1278 // No null bytes expected in our data, so let's remove it.
1279 $value = str_replace("\0", '', $value);
1281 // Note: this duplicates min_fix_utf8() intentionally.
1282 static $buggyiconv = null;
1283 if ($buggyiconv === null) {
1284 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1287 if ($buggyiconv) {
1288 if (function_exists('mb_convert_encoding')) {
1289 $subst = mb_substitute_character();
1290 mb_substitute_character('');
1291 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1292 mb_substitute_character($subst);
1294 } else {
1295 // Warn admins on admin/index.php page.
1296 $result = $value;
1299 } else {
1300 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1303 return $result;
1305 } else if (is_array($value)) {
1306 foreach ($value as $k => $v) {
1307 $value[$k] = fix_utf8($v);
1309 return $value;
1311 } else if (is_object($value)) {
1312 // Do not modify original.
1313 $value = clone($value);
1314 foreach ($value as $k => $v) {
1315 $value->$k = fix_utf8($v);
1317 return $value;
1319 } else {
1320 // This is some other type, no utf-8 here.
1321 return $value;
1326 * Return true if given value is integer or string with integer value
1328 * @param mixed $value String or Int
1329 * @return bool true if number, false if not
1331 function is_number($value) {
1332 if (is_int($value)) {
1333 return true;
1334 } else if (is_string($value)) {
1335 return ((string)(int)$value) === $value;
1336 } else {
1337 return false;
1342 * Returns host part from url.
1344 * @param string $url full url
1345 * @return string host, null if not found
1347 function get_host_from_url($url) {
1348 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1349 if ($matches) {
1350 return $matches[1];
1352 return null;
1356 * Tests whether anything was returned by text editor
1358 * This function is useful for testing whether something you got back from
1359 * the HTML editor actually contains anything. Sometimes the HTML editor
1360 * appear to be empty, but actually you get back a <br> tag or something.
1362 * @param string $string a string containing HTML.
1363 * @return boolean does the string contain any actual content - that is text,
1364 * images, objects, etc.
1366 function html_is_blank($string) {
1367 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1371 * Set a key in global configuration
1373 * Set a key/value pair in both this session's {@link $CFG} global variable
1374 * and in the 'config' database table for future sessions.
1376 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1377 * In that case it doesn't affect $CFG.
1379 * A NULL value will delete the entry.
1381 * NOTE: this function is called from lib/db/upgrade.php
1383 * @param string $name the key to set
1384 * @param string $value the value to set (without magic quotes)
1385 * @param string $plugin (optional) the plugin scope, default null
1386 * @return bool true or exception
1388 function set_config($name, $value, $plugin=null) {
1389 global $CFG, $DB;
1391 if (empty($plugin)) {
1392 if (!array_key_exists($name, $CFG->config_php_settings)) {
1393 // So it's defined for this invocation at least.
1394 if (is_null($value)) {
1395 unset($CFG->$name);
1396 } else {
1397 // Settings from db are always strings.
1398 $CFG->$name = (string)$value;
1402 if ($DB->get_field('config', 'name', array('name' => $name))) {
1403 if ($value === null) {
1404 $DB->delete_records('config', array('name' => $name));
1405 } else {
1406 $DB->set_field('config', 'value', $value, array('name' => $name));
1408 } else {
1409 if ($value !== null) {
1410 $config = new stdClass();
1411 $config->name = $name;
1412 $config->value = $value;
1413 $DB->insert_record('config', $config, false);
1416 if ($name === 'siteidentifier') {
1417 cache_helper::update_site_identifier($value);
1419 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1420 } else {
1421 // Plugin scope.
1422 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1423 if ($value===null) {
1424 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1425 } else {
1426 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1428 } else {
1429 if ($value !== null) {
1430 $config = new stdClass();
1431 $config->plugin = $plugin;
1432 $config->name = $name;
1433 $config->value = $value;
1434 $DB->insert_record('config_plugins', $config, false);
1437 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1440 return true;
1444 * Get configuration values from the global config table
1445 * or the config_plugins table.
1447 * If called with one parameter, it will load all the config
1448 * variables for one plugin, and return them as an object.
1450 * If called with 2 parameters it will return a string single
1451 * value or false if the value is not found.
1453 * NOTE: this function is called from lib/db/upgrade.php
1455 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1456 * that we need only fetch it once per request.
1457 * @param string $plugin full component name
1458 * @param string $name default null
1459 * @return mixed hash-like object or single value, return false no config found
1460 * @throws dml_exception
1462 function get_config($plugin, $name = null) {
1463 global $CFG, $DB;
1465 static $siteidentifier = null;
1467 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1468 $forced =& $CFG->config_php_settings;
1469 $iscore = true;
1470 $plugin = 'core';
1471 } else {
1472 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1473 $forced =& $CFG->forced_plugin_settings[$plugin];
1474 } else {
1475 $forced = array();
1477 $iscore = false;
1480 if ($siteidentifier === null) {
1481 try {
1482 // This may fail during installation.
1483 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1484 // install the database.
1485 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1486 } catch (dml_exception $ex) {
1487 // Set siteidentifier to false. We don't want to trip this continually.
1488 $siteidentifier = false;
1489 throw $ex;
1493 if (!empty($name)) {
1494 if (array_key_exists($name, $forced)) {
1495 return (string)$forced[$name];
1496 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1497 return $siteidentifier;
1501 $cache = cache::make('core', 'config');
1502 $result = $cache->get($plugin);
1503 if ($result === false) {
1504 // The user is after a recordset.
1505 if (!$iscore) {
1506 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1507 } else {
1508 // This part is not really used any more, but anyway...
1509 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1511 $cache->set($plugin, $result);
1514 if (!empty($name)) {
1515 if (array_key_exists($name, $result)) {
1516 return $result[$name];
1518 return false;
1521 if ($plugin === 'core') {
1522 $result['siteidentifier'] = $siteidentifier;
1525 foreach ($forced as $key => $value) {
1526 if (is_null($value) or is_array($value) or is_object($value)) {
1527 // We do not want any extra mess here, just real settings that could be saved in db.
1528 unset($result[$key]);
1529 } else {
1530 // Convert to string as if it went through the DB.
1531 $result[$key] = (string)$value;
1535 return (object)$result;
1539 * Removes a key from global configuration.
1541 * NOTE: this function is called from lib/db/upgrade.php
1543 * @param string $name the key to set
1544 * @param string $plugin (optional) the plugin scope
1545 * @return boolean whether the operation succeeded.
1547 function unset_config($name, $plugin=null) {
1548 global $CFG, $DB;
1550 if (empty($plugin)) {
1551 unset($CFG->$name);
1552 $DB->delete_records('config', array('name' => $name));
1553 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1554 } else {
1555 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1556 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1559 return true;
1563 * Remove all the config variables for a given plugin.
1565 * NOTE: this function is called from lib/db/upgrade.php
1567 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1568 * @return boolean whether the operation succeeded.
1570 function unset_all_config_for_plugin($plugin) {
1571 global $DB;
1572 // Delete from the obvious config_plugins first.
1573 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1574 // Next delete any suspect settings from config.
1575 $like = $DB->sql_like('name', '?', true, true, false, '|');
1576 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1577 $DB->delete_records_select('config', $like, $params);
1578 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1579 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1581 return true;
1585 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1587 * All users are verified if they still have the necessary capability.
1589 * @param string $value the value of the config setting.
1590 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1591 * @param bool $includeadmins include administrators.
1592 * @return array of user objects.
1594 function get_users_from_config($value, $capability, $includeadmins = true) {
1595 if (empty($value) or $value === '$@NONE@$') {
1596 return array();
1599 // We have to make sure that users still have the necessary capability,
1600 // it should be faster to fetch them all first and then test if they are present
1601 // instead of validating them one-by-one.
1602 $users = get_users_by_capability(context_system::instance(), $capability);
1603 if ($includeadmins) {
1604 $admins = get_admins();
1605 foreach ($admins as $admin) {
1606 $users[$admin->id] = $admin;
1610 if ($value === '$@ALL@$') {
1611 return $users;
1614 $result = array(); // Result in correct order.
1615 $allowed = explode(',', $value);
1616 foreach ($allowed as $uid) {
1617 if (isset($users[$uid])) {
1618 $user = $users[$uid];
1619 $result[$user->id] = $user;
1623 return $result;
1628 * Invalidates browser caches and cached data in temp.
1630 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1631 * {@link phpunit_util::reset_dataroot()}
1633 * @return void
1635 function purge_all_caches() {
1636 global $CFG, $DB;
1638 reset_text_filters_cache();
1639 js_reset_all_caches();
1640 theme_reset_all_caches();
1641 get_string_manager()->reset_caches();
1642 core_text::reset_caches();
1643 if (class_exists('core_plugin_manager')) {
1644 core_plugin_manager::reset_caches();
1647 // Bump up cacherev field for all courses.
1648 try {
1649 increment_revision_number('course', 'cacherev', '');
1650 } catch (moodle_exception $e) {
1651 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1654 $DB->reset_caches();
1655 cache_helper::purge_all();
1657 // Purge all other caches: rss, simplepie, etc.
1658 clearstatcache();
1659 remove_dir($CFG->cachedir.'', true);
1661 // Make sure cache dir is writable, throws exception if not.
1662 make_cache_directory('');
1664 // This is the only place where we purge local caches, we are only adding files there.
1665 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1666 remove_dir($CFG->localcachedir, true);
1667 set_config('localcachedirpurged', time());
1668 make_localcache_directory('', true);
1669 \core\task\manager::clear_static_caches();
1673 * Get volatile flags
1675 * @param string $type
1676 * @param int $changedsince default null
1677 * @return array records array
1679 function get_cache_flags($type, $changedsince = null) {
1680 global $DB;
1682 $params = array('type' => $type, 'expiry' => time());
1683 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1684 if ($changedsince !== null) {
1685 $params['changedsince'] = $changedsince;
1686 $sqlwhere .= " AND timemodified > :changedsince";
1688 $cf = array();
1689 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1690 foreach ($flags as $flag) {
1691 $cf[$flag->name] = $flag->value;
1694 return $cf;
1698 * Get volatile flags
1700 * @param string $type
1701 * @param string $name
1702 * @param int $changedsince default null
1703 * @return string|false The cache flag value or false
1705 function get_cache_flag($type, $name, $changedsince=null) {
1706 global $DB;
1708 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1710 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1711 if ($changedsince !== null) {
1712 $params['changedsince'] = $changedsince;
1713 $sqlwhere .= " AND timemodified > :changedsince";
1716 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1720 * Set a volatile flag
1722 * @param string $type the "type" namespace for the key
1723 * @param string $name the key to set
1724 * @param string $value the value to set (without magic quotes) - null will remove the flag
1725 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1726 * @return bool Always returns true
1728 function set_cache_flag($type, $name, $value, $expiry = null) {
1729 global $DB;
1731 $timemodified = time();
1732 if ($expiry === null || $expiry < $timemodified) {
1733 $expiry = $timemodified + 24 * 60 * 60;
1734 } else {
1735 $expiry = (int)$expiry;
1738 if ($value === null) {
1739 unset_cache_flag($type, $name);
1740 return true;
1743 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1744 // This is a potential problem in DEBUG_DEVELOPER.
1745 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1746 return true; // No need to update.
1748 $f->value = $value;
1749 $f->expiry = $expiry;
1750 $f->timemodified = $timemodified;
1751 $DB->update_record('cache_flags', $f);
1752 } else {
1753 $f = new stdClass();
1754 $f->flagtype = $type;
1755 $f->name = $name;
1756 $f->value = $value;
1757 $f->expiry = $expiry;
1758 $f->timemodified = $timemodified;
1759 $DB->insert_record('cache_flags', $f);
1761 return true;
1765 * Removes a single volatile flag
1767 * @param string $type the "type" namespace for the key
1768 * @param string $name the key to set
1769 * @return bool
1771 function unset_cache_flag($type, $name) {
1772 global $DB;
1773 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1774 return true;
1778 * Garbage-collect volatile flags
1780 * @return bool Always returns true
1782 function gc_cache_flags() {
1783 global $DB;
1784 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1785 return true;
1788 // USER PREFERENCE API.
1791 * Refresh user preference cache. This is used most often for $USER
1792 * object that is stored in session, but it also helps with performance in cron script.
1794 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1796 * @package core
1797 * @category preference
1798 * @access public
1799 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1800 * @param int $cachelifetime Cache life time on the current page (in seconds)
1801 * @throws coding_exception
1802 * @return null
1804 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1805 global $DB;
1806 // Static cache, we need to check on each page load, not only every 2 minutes.
1807 static $loadedusers = array();
1809 if (!isset($user->id)) {
1810 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1813 if (empty($user->id) or isguestuser($user->id)) {
1814 // No permanent storage for not-logged-in users and guest.
1815 if (!isset($user->preference)) {
1816 $user->preference = array();
1818 return;
1821 $timenow = time();
1823 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1824 // Already loaded at least once on this page. Are we up to date?
1825 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1826 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1827 return;
1829 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1830 // No change since the lastcheck on this page.
1831 $user->preference['_lastloaded'] = $timenow;
1832 return;
1836 // OK, so we have to reload all preferences.
1837 $loadedusers[$user->id] = true;
1838 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1839 $user->preference['_lastloaded'] = $timenow;
1843 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1845 * NOTE: internal function, do not call from other code.
1847 * @package core
1848 * @access private
1849 * @param integer $userid the user whose prefs were changed.
1851 function mark_user_preferences_changed($userid) {
1852 global $CFG;
1854 if (empty($userid) or isguestuser($userid)) {
1855 // No cache flags for guest and not-logged-in users.
1856 return;
1859 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1863 * Sets a preference for the specified user.
1865 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1867 * @package core
1868 * @category preference
1869 * @access public
1870 * @param string $name The key to set as preference for the specified user
1871 * @param string $value The value to set for the $name key in the specified user's
1872 * record, null means delete current value.
1873 * @param stdClass|int|null $user A moodle user object or id, null means current user
1874 * @throws coding_exception
1875 * @return bool Always true or exception
1877 function set_user_preference($name, $value, $user = null) {
1878 global $USER, $DB;
1880 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1881 throw new coding_exception('Invalid preference name in set_user_preference() call');
1884 if (is_null($value)) {
1885 // Null means delete current.
1886 return unset_user_preference($name, $user);
1887 } else if (is_object($value)) {
1888 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1889 } else if (is_array($value)) {
1890 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1892 // Value column maximum length is 1333 characters.
1893 $value = (string)$value;
1894 if (core_text::strlen($value) > 1333) {
1895 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1898 if (is_null($user)) {
1899 $user = $USER;
1900 } else if (isset($user->id)) {
1901 // It is a valid object.
1902 } else if (is_numeric($user)) {
1903 $user = (object)array('id' => (int)$user);
1904 } else {
1905 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1908 check_user_preferences_loaded($user);
1910 if (empty($user->id) or isguestuser($user->id)) {
1911 // No permanent storage for not-logged-in users and guest.
1912 $user->preference[$name] = $value;
1913 return true;
1916 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1917 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1918 // Preference already set to this value.
1919 return true;
1921 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1923 } else {
1924 $preference = new stdClass();
1925 $preference->userid = $user->id;
1926 $preference->name = $name;
1927 $preference->value = $value;
1928 $DB->insert_record('user_preferences', $preference);
1931 // Update value in cache.
1932 $user->preference[$name] = $value;
1934 // Set reload flag for other sessions.
1935 mark_user_preferences_changed($user->id);
1937 return true;
1941 * Sets a whole array of preferences for the current user
1943 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1945 * @package core
1946 * @category preference
1947 * @access public
1948 * @param array $prefarray An array of key/value pairs to be set
1949 * @param stdClass|int|null $user A moodle user object or id, null means current user
1950 * @return bool Always true or exception
1952 function set_user_preferences(array $prefarray, $user = null) {
1953 foreach ($prefarray as $name => $value) {
1954 set_user_preference($name, $value, $user);
1956 return true;
1960 * Unsets a preference completely by deleting it from the database
1962 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1964 * @package core
1965 * @category preference
1966 * @access public
1967 * @param string $name The key to unset as preference for the specified user
1968 * @param stdClass|int|null $user A moodle user object or id, null means current user
1969 * @throws coding_exception
1970 * @return bool Always true or exception
1972 function unset_user_preference($name, $user = null) {
1973 global $USER, $DB;
1975 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1976 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1979 if (is_null($user)) {
1980 $user = $USER;
1981 } else if (isset($user->id)) {
1982 // It is a valid object.
1983 } else if (is_numeric($user)) {
1984 $user = (object)array('id' => (int)$user);
1985 } else {
1986 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1989 check_user_preferences_loaded($user);
1991 if (empty($user->id) or isguestuser($user->id)) {
1992 // No permanent storage for not-logged-in user and guest.
1993 unset($user->preference[$name]);
1994 return true;
1997 // Delete from DB.
1998 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2000 // Delete the preference from cache.
2001 unset($user->preference[$name]);
2003 // Set reload flag for other sessions.
2004 mark_user_preferences_changed($user->id);
2006 return true;
2010 * Used to fetch user preference(s)
2012 * If no arguments are supplied this function will return
2013 * all of the current user preferences as an array.
2015 * If a name is specified then this function
2016 * attempts to return that particular preference value. If
2017 * none is found, then the optional value $default is returned,
2018 * otherwise null.
2020 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2022 * @package core
2023 * @category preference
2024 * @access public
2025 * @param string $name Name of the key to use in finding a preference value
2026 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2027 * @param stdClass|int|null $user A moodle user object or id, null means current user
2028 * @throws coding_exception
2029 * @return string|mixed|null A string containing the value of a single preference. An
2030 * array with all of the preferences or null
2032 function get_user_preferences($name = null, $default = null, $user = null) {
2033 global $USER;
2035 if (is_null($name)) {
2036 // All prefs.
2037 } else if (is_numeric($name) or $name === '_lastloaded') {
2038 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2041 if (is_null($user)) {
2042 $user = $USER;
2043 } else if (isset($user->id)) {
2044 // Is a valid object.
2045 } else if (is_numeric($user)) {
2046 $user = (object)array('id' => (int)$user);
2047 } else {
2048 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2051 check_user_preferences_loaded($user);
2053 if (empty($name)) {
2054 // All values.
2055 return $user->preference;
2056 } else if (isset($user->preference[$name])) {
2057 // The single string value.
2058 return $user->preference[$name];
2059 } else {
2060 // Default value (null if not specified).
2061 return $default;
2065 // FUNCTIONS FOR HANDLING TIME.
2068 * Given Gregorian date parts in user time produce a GMT timestamp.
2070 * @package core
2071 * @category time
2072 * @param int $year The year part to create timestamp of
2073 * @param int $month The month part to create timestamp of
2074 * @param int $day The day part to create timestamp of
2075 * @param int $hour The hour part to create timestamp of
2076 * @param int $minute The minute part to create timestamp of
2077 * @param int $second The second part to create timestamp of
2078 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2079 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2080 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2081 * applied only if timezone is 99 or string.
2082 * @return int GMT timestamp
2084 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2085 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2086 $date->setDate((int)$year, (int)$month, (int)$day);
2087 $date->setTime((int)$hour, (int)$minute, (int)$second);
2089 $time = $date->getTimestamp();
2091 if ($time === false) {
2092 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2093 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2096 // Moodle BC DST stuff.
2097 if (!$applydst) {
2098 $time += dst_offset_on($time, $timezone);
2101 return $time;
2106 * Format a date/time (seconds) as weeks, days, hours etc as needed
2108 * Given an amount of time in seconds, returns string
2109 * formatted nicely as weeks, days, hours etc as needed
2111 * @package core
2112 * @category time
2113 * @uses MINSECS
2114 * @uses HOURSECS
2115 * @uses DAYSECS
2116 * @uses YEARSECS
2117 * @param int $totalsecs Time in seconds
2118 * @param stdClass $str Should be a time object
2119 * @return string A nicely formatted date/time string
2121 function format_time($totalsecs, $str = null) {
2123 $totalsecs = abs($totalsecs);
2125 if (!$str) {
2126 // Create the str structure the slow way.
2127 $str = new stdClass();
2128 $str->day = get_string('day');
2129 $str->days = get_string('days');
2130 $str->hour = get_string('hour');
2131 $str->hours = get_string('hours');
2132 $str->min = get_string('min');
2133 $str->mins = get_string('mins');
2134 $str->sec = get_string('sec');
2135 $str->secs = get_string('secs');
2136 $str->year = get_string('year');
2137 $str->years = get_string('years');
2140 $years = floor($totalsecs/YEARSECS);
2141 $remainder = $totalsecs - ($years*YEARSECS);
2142 $days = floor($remainder/DAYSECS);
2143 $remainder = $totalsecs - ($days*DAYSECS);
2144 $hours = floor($remainder/HOURSECS);
2145 $remainder = $remainder - ($hours*HOURSECS);
2146 $mins = floor($remainder/MINSECS);
2147 $secs = $remainder - ($mins*MINSECS);
2149 $ss = ($secs == 1) ? $str->sec : $str->secs;
2150 $sm = ($mins == 1) ? $str->min : $str->mins;
2151 $sh = ($hours == 1) ? $str->hour : $str->hours;
2152 $sd = ($days == 1) ? $str->day : $str->days;
2153 $sy = ($years == 1) ? $str->year : $str->years;
2155 $oyears = '';
2156 $odays = '';
2157 $ohours = '';
2158 $omins = '';
2159 $osecs = '';
2161 if ($years) {
2162 $oyears = $years .' '. $sy;
2164 if ($days) {
2165 $odays = $days .' '. $sd;
2167 if ($hours) {
2168 $ohours = $hours .' '. $sh;
2170 if ($mins) {
2171 $omins = $mins .' '. $sm;
2173 if ($secs) {
2174 $osecs = $secs .' '. $ss;
2177 if ($years) {
2178 return trim($oyears .' '. $odays);
2180 if ($days) {
2181 return trim($odays .' '. $ohours);
2183 if ($hours) {
2184 return trim($ohours .' '. $omins);
2186 if ($mins) {
2187 return trim($omins .' '. $osecs);
2189 if ($secs) {
2190 return $osecs;
2192 return get_string('now');
2196 * Returns a formatted string that represents a date in user time.
2198 * @package core
2199 * @category time
2200 * @param int $date the timestamp in UTC, as obtained from the database.
2201 * @param string $format strftime format. You should probably get this using
2202 * get_string('strftime...', 'langconfig');
2203 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2204 * not 99 then daylight saving will not be added.
2205 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2206 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2207 * If false then the leading zero is maintained.
2208 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2209 * @return string the formatted date/time.
2211 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2212 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2213 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2217 * Returns a formatted date ensuring it is UTF-8.
2219 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2220 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2222 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2223 * @param string $format strftime format.
2224 * @param int|float|string $tz the user timezone
2225 * @return string the formatted date/time.
2226 * @since Moodle 2.3.3
2228 function date_format_string($date, $format, $tz = 99) {
2229 global $CFG;
2231 $localewincharset = null;
2232 // Get the calendar type user is using.
2233 if ($CFG->ostype == 'WINDOWS') {
2234 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2235 $localewincharset = $calendartype->locale_win_charset();
2238 if ($localewincharset) {
2239 $format = core_text::convert($format, 'utf-8', $localewincharset);
2242 date_default_timezone_set(core_date::get_user_timezone($tz));
2243 $datestring = strftime($format, $date);
2244 core_date::set_default_server_timezone();
2246 if ($localewincharset) {
2247 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2250 return $datestring;
2254 * Given a $time timestamp in GMT (seconds since epoch),
2255 * returns an array that represents the Gregorian date in user time
2257 * @package core
2258 * @category time
2259 * @param int $time Timestamp in GMT
2260 * @param float|int|string $timezone user timezone
2261 * @return array An array that represents the date in user time
2263 function usergetdate($time, $timezone=99) {
2264 date_default_timezone_set(core_date::get_user_timezone($timezone));
2265 $result = getdate($time);
2266 core_date::set_default_server_timezone();
2268 return $result;
2272 * Given a GMT timestamp (seconds since epoch), offsets it by
2273 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2275 * NOTE: this function does not include DST properly,
2276 * you should use the PHP date stuff instead!
2278 * @package core
2279 * @category time
2280 * @param int $date Timestamp in GMT
2281 * @param float|int|string $timezone user timezone
2282 * @return int
2284 function usertime($date, $timezone=99) {
2285 $userdate = new DateTime('@' . $date);
2286 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2287 $dst = dst_offset_on($date, $timezone);
2289 return $date - $userdate->getOffset() + $dst;
2293 * Given a time, return the GMT timestamp of the most recent midnight
2294 * for the current user.
2296 * @package core
2297 * @category time
2298 * @param int $date Timestamp in GMT
2299 * @param float|int|string $timezone user timezone
2300 * @return int Returns a GMT timestamp
2302 function usergetmidnight($date, $timezone=99) {
2304 $userdate = usergetdate($date, $timezone);
2306 // Time of midnight of this user's day, in GMT.
2307 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2312 * Returns a string that prints the user's timezone
2314 * @package core
2315 * @category time
2316 * @param float|int|string $timezone user timezone
2317 * @return string
2319 function usertimezone($timezone=99) {
2320 $tz = core_date::get_user_timezone($timezone);
2321 return core_date::get_localised_timezone($tz);
2325 * Returns a float or a string which denotes the user's timezone
2326 * A float value means that a simple offset from GMT is used, while a string (it will be the name of a timezone in the database)
2327 * means that for this timezone there are also DST rules to be taken into account
2328 * Checks various settings and picks the most dominant of those which have a value
2330 * @package core
2331 * @category time
2332 * @param float|int|string $tz timezone to calculate GMT time offset before
2333 * calculating user timezone, 99 is default user timezone
2334 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2335 * @return float|string
2337 function get_user_timezone($tz = 99) {
2338 global $USER, $CFG;
2340 $timezones = array(
2341 $tz,
2342 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2343 isset($USER->timezone) ? $USER->timezone : 99,
2344 isset($CFG->timezone) ? $CFG->timezone : 99,
2347 $tz = 99;
2349 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2350 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2351 $tz = $next['value'];
2353 return is_numeric($tz) ? (float) $tz : $tz;
2357 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2358 * - Note: Daylight saving only works for string timezones and not for float.
2360 * @package core
2361 * @category time
2362 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2363 * @param int|float|string $strtimezone user timezone
2364 * @return int
2366 function dst_offset_on($time, $strtimezone = null) {
2367 $tz = core_date::get_user_timezone($strtimezone);
2368 $date = new DateTime('@' . $time);
2369 $date->setTimezone(new DateTimeZone($tz));
2370 if ($date->format('I') == '1') {
2371 if ($tz === 'Australia/Lord_Howe') {
2372 return 1800;
2374 return 3600;
2376 return 0;
2380 * Calculates when the day appears in specific month
2382 * @package core
2383 * @category time
2384 * @param int $startday starting day of the month
2385 * @param int $weekday The day when week starts (normally taken from user preferences)
2386 * @param int $month The month whose day is sought
2387 * @param int $year The year of the month whose day is sought
2388 * @return int
2390 function find_day_in_month($startday, $weekday, $month, $year) {
2391 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2393 $daysinmonth = days_in_month($month, $year);
2394 $daysinweek = count($calendartype->get_weekdays());
2396 if ($weekday == -1) {
2397 // Don't care about weekday, so return:
2398 // abs($startday) if $startday != -1
2399 // $daysinmonth otherwise.
2400 return ($startday == -1) ? $daysinmonth : abs($startday);
2403 // From now on we 're looking for a specific weekday.
2404 // Give "end of month" its actual value, since we know it.
2405 if ($startday == -1) {
2406 $startday = -1 * $daysinmonth;
2409 // Starting from day $startday, the sign is the direction.
2410 if ($startday < 1) {
2411 $startday = abs($startday);
2412 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2414 // This is the last such weekday of the month.
2415 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2416 if ($lastinmonth > $daysinmonth) {
2417 $lastinmonth -= $daysinweek;
2420 // Find the first such weekday <= $startday.
2421 while ($lastinmonth > $startday) {
2422 $lastinmonth -= $daysinweek;
2425 return $lastinmonth;
2426 } else {
2427 $indexweekday = dayofweek($startday, $month, $year);
2429 $diff = $weekday - $indexweekday;
2430 if ($diff < 0) {
2431 $diff += $daysinweek;
2434 // This is the first such weekday of the month equal to or after $startday.
2435 $firstfromindex = $startday + $diff;
2437 return $firstfromindex;
2442 * Calculate the number of days in a given month
2444 * @package core
2445 * @category time
2446 * @param int $month The month whose day count is sought
2447 * @param int $year The year of the month whose day count is sought
2448 * @return int
2450 function days_in_month($month, $year) {
2451 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2452 return $calendartype->get_num_days_in_month($year, $month);
2456 * Calculate the position in the week of a specific calendar day
2458 * @package core
2459 * @category time
2460 * @param int $day The day of the date whose position in the week is sought
2461 * @param int $month The month of the date whose position in the week is sought
2462 * @param int $year The year of the date whose position in the week is sought
2463 * @return int
2465 function dayofweek($day, $month, $year) {
2466 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2467 return $calendartype->get_weekday($year, $month, $day);
2470 // USER AUTHENTICATION AND LOGIN.
2473 * Returns full login url.
2475 * @return string login url
2477 function get_login_url() {
2478 global $CFG;
2480 $url = "$CFG->wwwroot/login/index.php";
2482 if (!empty($CFG->loginhttps)) {
2483 $url = str_replace('http:', 'https:', $url);
2486 return $url;
2490 * This function checks that the current user is logged in and has the
2491 * required privileges
2493 * This function checks that the current user is logged in, and optionally
2494 * whether they are allowed to be in a particular course and view a particular
2495 * course module.
2496 * If they are not logged in, then it redirects them to the site login unless
2497 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2498 * case they are automatically logged in as guests.
2499 * If $courseid is given and the user is not enrolled in that course then the
2500 * user is redirected to the course enrolment page.
2501 * If $cm is given and the course module is hidden and the user is not a teacher
2502 * in the course then the user is redirected to the course home page.
2504 * When $cm parameter specified, this function sets page layout to 'module'.
2505 * You need to change it manually later if some other layout needed.
2507 * @package core_access
2508 * @category access
2510 * @param mixed $courseorid id of the course or course object
2511 * @param bool $autologinguest default true
2512 * @param object $cm course module object
2513 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2514 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2515 * in order to keep redirects working properly. MDL-14495
2516 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2517 * @return mixed Void, exit, and die depending on path
2518 * @throws coding_exception
2519 * @throws require_login_exception
2520 * @throws moodle_exception
2522 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2523 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2525 // Must not redirect when byteserving already started.
2526 if (!empty($_SERVER['HTTP_RANGE'])) {
2527 $preventredirect = true;
2530 if (AJAX_SCRIPT) {
2531 // We cannot redirect for AJAX scripts either.
2532 $preventredirect = true;
2535 // Setup global $COURSE, themes, language and locale.
2536 if (!empty($courseorid)) {
2537 if (is_object($courseorid)) {
2538 $course = $courseorid;
2539 } else if ($courseorid == SITEID) {
2540 $course = clone($SITE);
2541 } else {
2542 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2544 if ($cm) {
2545 if ($cm->course != $course->id) {
2546 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2548 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2549 if (!($cm instanceof cm_info)) {
2550 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2551 // db queries so this is not really a performance concern, however it is obviously
2552 // better if you use get_fast_modinfo to get the cm before calling this.
2553 $modinfo = get_fast_modinfo($course);
2554 $cm = $modinfo->get_cm($cm->id);
2557 } else {
2558 // Do not touch global $COURSE via $PAGE->set_course(),
2559 // the reasons is we need to be able to call require_login() at any time!!
2560 $course = $SITE;
2561 if ($cm) {
2562 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2566 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2567 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2568 // risk leading the user back to the AJAX request URL.
2569 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2570 $setwantsurltome = false;
2573 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2574 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2575 if ($preventredirect) {
2576 throw new require_login_session_timeout_exception();
2577 } else {
2578 if ($setwantsurltome) {
2579 $SESSION->wantsurl = qualified_me();
2581 redirect(get_login_url());
2585 // If the user is not even logged in yet then make sure they are.
2586 if (!isloggedin()) {
2587 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2588 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2589 // Misconfigured site guest, just redirect to login page.
2590 redirect(get_login_url());
2591 exit; // Never reached.
2593 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2594 complete_user_login($guest);
2595 $USER->autologinguest = true;
2596 $SESSION->lang = $lang;
2597 } else {
2598 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2599 if ($preventredirect) {
2600 throw new require_login_exception('You are not logged in');
2603 if ($setwantsurltome) {
2604 $SESSION->wantsurl = qualified_me();
2607 $referer = get_local_referer(false);
2608 if (!empty($referer)) {
2609 $SESSION->fromurl = $referer;
2612 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2613 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2614 foreach($authsequence as $authname) {
2615 $authplugin = get_auth_plugin($authname);
2616 $authplugin->pre_loginpage_hook();
2617 if (isloggedin()) {
2618 break;
2622 // If we're still not logged in then go to the login page
2623 if (!isloggedin()) {
2624 redirect(get_login_url());
2625 exit; // Never reached.
2630 // Loginas as redirection if needed.
2631 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2632 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2633 if ($USER->loginascontext->instanceid != $course->id) {
2634 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2639 // Check whether the user should be changing password (but only if it is REALLY them).
2640 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2641 $userauth = get_auth_plugin($USER->auth);
2642 if ($userauth->can_change_password() and !$preventredirect) {
2643 if ($setwantsurltome) {
2644 $SESSION->wantsurl = qualified_me();
2646 if ($changeurl = $userauth->change_password_url()) {
2647 // Use plugin custom url.
2648 redirect($changeurl);
2649 } else {
2650 // Use moodle internal method.
2651 if (empty($CFG->loginhttps)) {
2652 redirect($CFG->wwwroot .'/login/change_password.php');
2653 } else {
2654 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2655 redirect($wwwroot .'/login/change_password.php');
2658 } else if ($userauth->can_change_password()) {
2659 throw new moodle_exception('forcepasswordchangenotice');
2660 } else {
2661 throw new moodle_exception('nopasswordchangeforced', 'auth');
2665 // Check that the user account is properly set up. If we can't redirect to
2666 // edit their profile, perform just the lax check. It will allow them to
2667 // use filepicker on the profile edit page.
2669 if ($preventredirect) {
2670 $usernotfullysetup = user_not_fully_set_up($USER, false);
2671 } else {
2672 $usernotfullysetup = user_not_fully_set_up($USER, true);
2675 if ($usernotfullysetup) {
2676 if ($preventredirect) {
2677 throw new moodle_exception('usernotfullysetup');
2679 if ($setwantsurltome) {
2680 $SESSION->wantsurl = qualified_me();
2682 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2685 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2686 sesskey();
2688 // Do not bother admins with any formalities, except for activities pending deletion.
2689 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2690 // Set the global $COURSE.
2691 if ($cm) {
2692 $PAGE->set_cm($cm, $course);
2693 $PAGE->set_pagelayout('incourse');
2694 } else if (!empty($courseorid)) {
2695 $PAGE->set_course($course);
2697 // Set accesstime or the user will appear offline which messes up messaging.
2698 user_accesstime_log($course->id);
2699 return;
2702 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2703 if (!$USER->policyagreed and !is_siteadmin()) {
2704 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2705 if ($preventredirect) {
2706 throw new moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicy);
2708 if ($setwantsurltome) {
2709 $SESSION->wantsurl = qualified_me();
2711 redirect($CFG->wwwroot .'/user/policy.php');
2712 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2713 if ($preventredirect) {
2714 throw new moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicyguest);
2716 if ($setwantsurltome) {
2717 $SESSION->wantsurl = qualified_me();
2719 redirect($CFG->wwwroot .'/user/policy.php');
2723 // Fetch the system context, the course context, and prefetch its child contexts.
2724 $sysctx = context_system::instance();
2725 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2726 if ($cm) {
2727 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2728 } else {
2729 $cmcontext = null;
2732 // If the site is currently under maintenance, then print a message.
2733 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2734 if ($preventredirect) {
2735 throw new require_login_exception('Maintenance in progress');
2737 $PAGE->set_context(null);
2738 print_maintenance_message();
2741 // Make sure the course itself is not hidden.
2742 if ($course->id == SITEID) {
2743 // Frontpage can not be hidden.
2744 } else {
2745 if (is_role_switched($course->id)) {
2746 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2747 } else {
2748 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2749 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2750 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2751 if ($preventredirect) {
2752 throw new require_login_exception('Course is hidden');
2754 $PAGE->set_context(null);
2755 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2756 // the navigation will mess up when trying to find it.
2757 navigation_node::override_active_url(new moodle_url('/'));
2758 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2763 // Is the user enrolled?
2764 if ($course->id == SITEID) {
2765 // Everybody is enrolled on the frontpage.
2766 } else {
2767 if (\core\session\manager::is_loggedinas()) {
2768 // Make sure the REAL person can access this course first.
2769 $realuser = \core\session\manager::get_realuser();
2770 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2771 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2772 if ($preventredirect) {
2773 throw new require_login_exception('Invalid course login-as access');
2775 $PAGE->set_context(null);
2776 echo $OUTPUT->header();
2777 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2781 $access = false;
2783 if (is_role_switched($course->id)) {
2784 // Ok, user had to be inside this course before the switch.
2785 $access = true;
2787 } else if (is_viewing($coursecontext, $USER)) {
2788 // Ok, no need to mess with enrol.
2789 $access = true;
2791 } else {
2792 if (isset($USER->enrol['enrolled'][$course->id])) {
2793 if ($USER->enrol['enrolled'][$course->id] > time()) {
2794 $access = true;
2795 if (isset($USER->enrol['tempguest'][$course->id])) {
2796 unset($USER->enrol['tempguest'][$course->id]);
2797 remove_temp_course_roles($coursecontext);
2799 } else {
2800 // Expired.
2801 unset($USER->enrol['enrolled'][$course->id]);
2804 if (isset($USER->enrol['tempguest'][$course->id])) {
2805 if ($USER->enrol['tempguest'][$course->id] == 0) {
2806 $access = true;
2807 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2808 $access = true;
2809 } else {
2810 // Expired.
2811 unset($USER->enrol['tempguest'][$course->id]);
2812 remove_temp_course_roles($coursecontext);
2816 if (!$access) {
2817 // Cache not ok.
2818 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2819 if ($until !== false) {
2820 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2821 if ($until == 0) {
2822 $until = ENROL_MAX_TIMESTAMP;
2824 $USER->enrol['enrolled'][$course->id] = $until;
2825 $access = true;
2827 } else {
2828 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2829 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2830 $enrols = enrol_get_plugins(true);
2831 // First ask all enabled enrol instances in course if they want to auto enrol user.
2832 foreach ($instances as $instance) {
2833 if (!isset($enrols[$instance->enrol])) {
2834 continue;
2836 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2837 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2838 if ($until !== false) {
2839 if ($until == 0) {
2840 $until = ENROL_MAX_TIMESTAMP;
2842 $USER->enrol['enrolled'][$course->id] = $until;
2843 $access = true;
2844 break;
2847 // If not enrolled yet try to gain temporary guest access.
2848 if (!$access) {
2849 foreach ($instances as $instance) {
2850 if (!isset($enrols[$instance->enrol])) {
2851 continue;
2853 // Get a duration for the guest access, a timestamp in the future or false.
2854 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2855 if ($until !== false and $until > time()) {
2856 $USER->enrol['tempguest'][$course->id] = $until;
2857 $access = true;
2858 break;
2866 if (!$access) {
2867 if ($preventredirect) {
2868 throw new require_login_exception('Not enrolled');
2870 if ($setwantsurltome) {
2871 $SESSION->wantsurl = qualified_me();
2873 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2877 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
2878 if ($cm && $cm->deletioninprogress) {
2879 if ($preventredirect) {
2880 throw new moodle_exception('activityisscheduledfordeletion');
2882 require_once($CFG->dirroot . '/course/lib.php');
2883 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
2886 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2887 if ($cm && !$cm->uservisible) {
2888 if ($preventredirect) {
2889 throw new require_login_exception('Activity is hidden');
2891 if ($course->id != SITEID) {
2892 $url = new moodle_url('/course/view.php', array('id' => $course->id));
2893 } else {
2894 $url = new moodle_url('/');
2896 redirect($url, get_string('activityiscurrentlyhidden'), null,
2897 \core\output\notification::NOTIFY_ERROR);
2900 // Set the global $COURSE.
2901 if ($cm) {
2902 $PAGE->set_cm($cm, $course);
2903 $PAGE->set_pagelayout('incourse');
2904 } else if (!empty($courseorid)) {
2905 $PAGE->set_course($course);
2908 // Finally access granted, update lastaccess times.
2909 user_accesstime_log($course->id);
2914 * This function just makes sure a user is logged out.
2916 * @package core_access
2917 * @category access
2919 function require_logout() {
2920 global $USER, $DB;
2922 if (!isloggedin()) {
2923 // This should not happen often, no need for hooks or events here.
2924 \core\session\manager::terminate_current();
2925 return;
2928 // Execute hooks before action.
2929 $authplugins = array();
2930 $authsequence = get_enabled_auth_plugins();
2931 foreach ($authsequence as $authname) {
2932 $authplugins[$authname] = get_auth_plugin($authname);
2933 $authplugins[$authname]->prelogout_hook();
2936 // Store info that gets removed during logout.
2937 $sid = session_id();
2938 $event = \core\event\user_loggedout::create(
2939 array(
2940 'userid' => $USER->id,
2941 'objectid' => $USER->id,
2942 'other' => array('sessionid' => $sid),
2945 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2946 $event->add_record_snapshot('sessions', $session);
2949 // Clone of $USER object to be used by auth plugins.
2950 $user = fullclone($USER);
2952 // Delete session record and drop $_SESSION content.
2953 \core\session\manager::terminate_current();
2955 // Trigger event AFTER action.
2956 $event->trigger();
2958 // Hook to execute auth plugins redirection after event trigger.
2959 foreach ($authplugins as $authplugin) {
2960 $authplugin->postlogout_hook($user);
2965 * Weaker version of require_login()
2967 * This is a weaker version of {@link require_login()} which only requires login
2968 * when called from within a course rather than the site page, unless
2969 * the forcelogin option is turned on.
2970 * @see require_login()
2972 * @package core_access
2973 * @category access
2975 * @param mixed $courseorid The course object or id in question
2976 * @param bool $autologinguest Allow autologin guests if that is wanted
2977 * @param object $cm Course activity module if known
2978 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2979 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2980 * in order to keep redirects working properly. MDL-14495
2981 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2982 * @return void
2983 * @throws coding_exception
2985 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2986 global $CFG, $PAGE, $SITE;
2987 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
2988 or (!is_object($courseorid) and $courseorid == SITEID));
2989 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2990 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2991 // db queries so this is not really a performance concern, however it is obviously
2992 // better if you use get_fast_modinfo to get the cm before calling this.
2993 if (is_object($courseorid)) {
2994 $course = $courseorid;
2995 } else {
2996 $course = clone($SITE);
2998 $modinfo = get_fast_modinfo($course);
2999 $cm = $modinfo->get_cm($cm->id);
3001 if (!empty($CFG->forcelogin)) {
3002 // Login required for both SITE and courses.
3003 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3005 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3006 // Always login for hidden activities.
3007 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3009 } else if ($issite) {
3010 // Login for SITE not required.
3011 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3012 if (!empty($courseorid)) {
3013 if (is_object($courseorid)) {
3014 $course = $courseorid;
3015 } else {
3016 $course = clone $SITE;
3018 if ($cm) {
3019 if ($cm->course != $course->id) {
3020 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3022 $PAGE->set_cm($cm, $course);
3023 $PAGE->set_pagelayout('incourse');
3024 } else {
3025 $PAGE->set_course($course);
3027 } else {
3028 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3029 $PAGE->set_course($PAGE->course);
3031 user_accesstime_log(SITEID);
3032 return;
3034 } else {
3035 // Course login always required.
3036 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3041 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3043 * @param string $keyvalue the key value
3044 * @param string $script unique script identifier
3045 * @param int $instance instance id
3046 * @return stdClass the key entry in the user_private_key table
3047 * @since Moodle 3.2
3048 * @throws moodle_exception
3050 function validate_user_key($keyvalue, $script, $instance) {
3051 global $DB;
3053 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3054 print_error('invalidkey');
3057 if (!empty($key->validuntil) and $key->validuntil < time()) {
3058 print_error('expiredkey');
3061 if ($key->iprestriction) {
3062 $remoteaddr = getremoteaddr(null);
3063 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3064 print_error('ipmismatch');
3067 return $key;
3071 * Require key login. Function terminates with error if key not found or incorrect.
3073 * @uses NO_MOODLE_COOKIES
3074 * @uses PARAM_ALPHANUM
3075 * @param string $script unique script identifier
3076 * @param int $instance optional instance id
3077 * @return int Instance ID
3079 function require_user_key_login($script, $instance=null) {
3080 global $DB;
3082 if (!NO_MOODLE_COOKIES) {
3083 print_error('sessioncookiesdisable');
3086 // Extra safety.
3087 \core\session\manager::write_close();
3089 $keyvalue = required_param('key', PARAM_ALPHANUM);
3091 $key = validate_user_key($keyvalue, $script, $instance);
3093 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3094 print_error('invaliduserid');
3097 // Emulate normal session.
3098 enrol_check_plugins($user);
3099 \core\session\manager::set_user($user);
3101 // Note we are not using normal login.
3102 if (!defined('USER_KEY_LOGIN')) {
3103 define('USER_KEY_LOGIN', true);
3106 // Return instance id - it might be empty.
3107 return $key->instance;
3111 * Creates a new private user access key.
3113 * @param string $script unique target identifier
3114 * @param int $userid
3115 * @param int $instance optional instance id
3116 * @param string $iprestriction optional ip restricted access
3117 * @param int $validuntil key valid only until given data
3118 * @return string access key value
3120 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3121 global $DB;
3123 $key = new stdClass();
3124 $key->script = $script;
3125 $key->userid = $userid;
3126 $key->instance = $instance;
3127 $key->iprestriction = $iprestriction;
3128 $key->validuntil = $validuntil;
3129 $key->timecreated = time();
3131 // Something long and unique.
3132 $key->value = md5($userid.'_'.time().random_string(40));
3133 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3134 // Must be unique.
3135 $key->value = md5($userid.'_'.time().random_string(40));
3137 $DB->insert_record('user_private_key', $key);
3138 return $key->value;
3142 * Delete the user's new private user access keys for a particular script.
3144 * @param string $script unique target identifier
3145 * @param int $userid
3146 * @return void
3148 function delete_user_key($script, $userid) {
3149 global $DB;
3150 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3154 * Gets a private user access key (and creates one if one doesn't exist).
3156 * @param string $script unique target identifier
3157 * @param int $userid
3158 * @param int $instance optional instance id
3159 * @param string $iprestriction optional ip restricted access
3160 * @param int $validuntil key valid only until given date
3161 * @return string access key value
3163 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3164 global $DB;
3166 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3167 'instance' => $instance, 'iprestriction' => $iprestriction,
3168 'validuntil' => $validuntil))) {
3169 return $key->value;
3170 } else {
3171 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3177 * Modify the user table by setting the currently logged in user's last login to now.
3179 * @return bool Always returns true
3181 function update_user_login_times() {
3182 global $USER, $DB;
3184 if (isguestuser()) {
3185 // Do not update guest access times/ips for performance.
3186 return true;
3189 $now = time();
3191 $user = new stdClass();
3192 $user->id = $USER->id;
3194 // Make sure all users that logged in have some firstaccess.
3195 if ($USER->firstaccess == 0) {
3196 $USER->firstaccess = $user->firstaccess = $now;
3199 // Store the previous current as lastlogin.
3200 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3202 $USER->currentlogin = $user->currentlogin = $now;
3204 // Function user_accesstime_log() may not update immediately, better do it here.
3205 $USER->lastaccess = $user->lastaccess = $now;
3206 $USER->lastip = $user->lastip = getremoteaddr();
3208 // Note: do not call user_update_user() here because this is part of the login process,
3209 // the login event means that these fields were updated.
3210 $DB->update_record('user', $user);
3211 return true;
3215 * Determines if a user has completed setting up their account.
3217 * The lax mode (with $strict = false) has been introduced for special cases
3218 * only where we want to skip certain checks intentionally. This is valid in
3219 * certain mnet or ajax scenarios when the user cannot / should not be
3220 * redirected to edit their profile. In most cases, you should perform the
3221 * strict check.
3223 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3224 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3225 * @return bool
3227 function user_not_fully_set_up($user, $strict = true) {
3228 global $CFG;
3229 require_once($CFG->dirroot.'/user/profile/lib.php');
3231 if (isguestuser($user)) {
3232 return false;
3235 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3236 return true;
3239 if ($strict) {
3240 if (empty($user->id)) {
3241 // Strict mode can be used with existing accounts only.
3242 return true;
3244 if (!profile_has_required_custom_fields_set($user->id)) {
3245 return true;
3249 return false;
3253 * Check whether the user has exceeded the bounce threshold
3255 * @param stdClass $user A {@link $USER} object
3256 * @return bool true => User has exceeded bounce threshold
3258 function over_bounce_threshold($user) {
3259 global $CFG, $DB;
3261 if (empty($CFG->handlebounces)) {
3262 return false;
3265 if (empty($user->id)) {
3266 // No real (DB) user, nothing to do here.
3267 return false;
3270 // Set sensible defaults.
3271 if (empty($CFG->minbounces)) {
3272 $CFG->minbounces = 10;
3274 if (empty($CFG->bounceratio)) {
3275 $CFG->bounceratio = .20;
3277 $bouncecount = 0;
3278 $sendcount = 0;
3279 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3280 $bouncecount = $bounce->value;
3282 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3283 $sendcount = $send->value;
3285 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3289 * Used to increment or reset email sent count
3291 * @param stdClass $user object containing an id
3292 * @param bool $reset will reset the count to 0
3293 * @return void
3295 function set_send_count($user, $reset=false) {
3296 global $DB;
3298 if (empty($user->id)) {
3299 // No real (DB) user, nothing to do here.
3300 return;
3303 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3304 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3305 $DB->update_record('user_preferences', $pref);
3306 } else if (!empty($reset)) {
3307 // If it's not there and we're resetting, don't bother. Make a new one.
3308 $pref = new stdClass();
3309 $pref->name = 'email_send_count';
3310 $pref->value = 1;
3311 $pref->userid = $user->id;
3312 $DB->insert_record('user_preferences', $pref, false);
3317 * Increment or reset user's email bounce count
3319 * @param stdClass $user object containing an id
3320 * @param bool $reset will reset the count to 0
3322 function set_bounce_count($user, $reset=false) {
3323 global $DB;
3325 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3326 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3327 $DB->update_record('user_preferences', $pref);
3328 } else if (!empty($reset)) {
3329 // If it's not there and we're resetting, don't bother. Make a new one.
3330 $pref = new stdClass();
3331 $pref->name = 'email_bounce_count';
3332 $pref->value = 1;
3333 $pref->userid = $user->id;
3334 $DB->insert_record('user_preferences', $pref, false);
3339 * Determines if the logged in user is currently moving an activity
3341 * @param int $courseid The id of the course being tested
3342 * @return bool
3344 function ismoving($courseid) {
3345 global $USER;
3347 if (!empty($USER->activitycopy)) {
3348 return ($USER->activitycopycourse == $courseid);
3350 return false;
3354 * Returns a persons full name
3356 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3357 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3358 * specify one.
3360 * @param stdClass $user A {@link $USER} object to get full name of.
3361 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3362 * @return string
3364 function fullname($user, $override=false) {
3365 global $CFG, $SESSION;
3367 if (!isset($user->firstname) and !isset($user->lastname)) {
3368 return '';
3371 // Get all of the name fields.
3372 $allnames = get_all_user_name_fields();
3373 if ($CFG->debugdeveloper) {
3374 foreach ($allnames as $allname) {
3375 if (!property_exists($user, $allname)) {
3376 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3377 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3378 // Message has been sent, no point in sending the message multiple times.
3379 break;
3384 if (!$override) {
3385 if (!empty($CFG->forcefirstname)) {
3386 $user->firstname = $CFG->forcefirstname;
3388 if (!empty($CFG->forcelastname)) {
3389 $user->lastname = $CFG->forcelastname;
3393 if (!empty($SESSION->fullnamedisplay)) {
3394 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3397 $template = null;
3398 // If the fullnamedisplay setting is available, set the template to that.
3399 if (isset($CFG->fullnamedisplay)) {
3400 $template = $CFG->fullnamedisplay;
3402 // If the template is empty, or set to language, return the language string.
3403 if ((empty($template) || $template == 'language') && !$override) {
3404 return get_string('fullnamedisplay', null, $user);
3407 // Check to see if we are displaying according to the alternative full name format.
3408 if ($override) {
3409 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3410 // Default to show just the user names according to the fullnamedisplay string.
3411 return get_string('fullnamedisplay', null, $user);
3412 } else {
3413 // If the override is true, then change the template to use the complete name.
3414 $template = $CFG->alternativefullnameformat;
3418 $requirednames = array();
3419 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3420 foreach ($allnames as $allname) {
3421 if (strpos($template, $allname) !== false) {
3422 $requirednames[] = $allname;
3426 $displayname = $template;
3427 // Switch in the actual data into the template.
3428 foreach ($requirednames as $altname) {
3429 if (isset($user->$altname)) {
3430 // Using empty() on the below if statement causes breakages.
3431 if ((string)$user->$altname == '') {
3432 $displayname = str_replace($altname, 'EMPTY', $displayname);
3433 } else {
3434 $displayname = str_replace($altname, $user->$altname, $displayname);
3436 } else {
3437 $displayname = str_replace($altname, 'EMPTY', $displayname);
3440 // Tidy up any misc. characters (Not perfect, but gets most characters).
3441 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3442 // katakana and parenthesis.
3443 $patterns = array();
3444 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3445 // filled in by a user.
3446 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3447 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3448 // This regular expression is to remove any double spaces in the display name.
3449 $patterns[] = '/\s{2,}/u';
3450 foreach ($patterns as $pattern) {
3451 $displayname = preg_replace($pattern, ' ', $displayname);
3454 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3455 $displayname = trim($displayname);
3456 if (empty($displayname)) {
3457 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3458 // people in general feel is a good setting to fall back on.
3459 $displayname = $user->firstname;
3461 return $displayname;
3465 * A centralised location for the all name fields. Returns an array / sql string snippet.
3467 * @param bool $returnsql True for an sql select field snippet.
3468 * @param string $tableprefix table query prefix to use in front of each field.
3469 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3470 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3471 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3472 * @return array|string All name fields.
3474 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3475 // This array is provided in this order because when called by fullname() (above) if firstname is before
3476 // firstnamephonetic str_replace() will change the wrong placeholder.
3477 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3478 'lastnamephonetic' => 'lastnamephonetic',
3479 'middlename' => 'middlename',
3480 'alternatename' => 'alternatename',
3481 'firstname' => 'firstname',
3482 'lastname' => 'lastname');
3484 // Let's add a prefix to the array of user name fields if provided.
3485 if ($prefix) {
3486 foreach ($alternatenames as $key => $altname) {
3487 $alternatenames[$key] = $prefix . $altname;
3491 // If we want the end result to have firstname and lastname at the front / top of the result.
3492 if ($order) {
3493 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3494 for ($i = 0; $i < 2; $i++) {
3495 // Get the last element.
3496 $lastelement = end($alternatenames);
3497 // Remove it from the array.
3498 unset($alternatenames[$lastelement]);
3499 // Put the element back on the top of the array.
3500 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3504 // Create an sql field snippet if requested.
3505 if ($returnsql) {
3506 if ($tableprefix) {
3507 if ($fieldprefix) {
3508 foreach ($alternatenames as $key => $altname) {
3509 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3511 } else {
3512 foreach ($alternatenames as $key => $altname) {
3513 $alternatenames[$key] = $tableprefix . '.' . $altname;
3517 $alternatenames = implode(',', $alternatenames);
3519 return $alternatenames;
3523 * Reduces lines of duplicated code for getting user name fields.
3525 * See also {@link user_picture::unalias()}
3527 * @param object $addtoobject Object to add user name fields to.
3528 * @param object $secondobject Object that contains user name field information.
3529 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3530 * @param array $additionalfields Additional fields to be matched with data in the second object.
3531 * The key can be set to the user table field name.
3532 * @return object User name fields.
3534 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3535 $fields = get_all_user_name_fields(false, null, $prefix);
3536 if ($additionalfields) {
3537 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3538 // the key is a number and then sets the key to the array value.
3539 foreach ($additionalfields as $key => $value) {
3540 if (is_numeric($key)) {
3541 $additionalfields[$value] = $prefix . $value;
3542 unset($additionalfields[$key]);
3543 } else {
3544 $additionalfields[$key] = $prefix . $value;
3547 $fields = array_merge($fields, $additionalfields);
3549 foreach ($fields as $key => $field) {
3550 // Important that we have all of the user name fields present in the object that we are sending back.
3551 $addtoobject->$key = '';
3552 if (isset($secondobject->$field)) {
3553 $addtoobject->$key = $secondobject->$field;
3556 return $addtoobject;
3560 * Returns an array of values in order of occurance in a provided string.
3561 * The key in the result is the character postion in the string.
3563 * @param array $values Values to be found in the string format
3564 * @param string $stringformat The string which may contain values being searched for.
3565 * @return array An array of values in order according to placement in the string format.
3567 function order_in_string($values, $stringformat) {
3568 $valuearray = array();
3569 foreach ($values as $value) {
3570 $pattern = "/$value\b/";
3571 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3572 if (preg_match($pattern, $stringformat)) {
3573 $replacement = "thing";
3574 // Replace the value with something more unique to ensure we get the right position when using strpos().
3575 $newformat = preg_replace($pattern, $replacement, $stringformat);
3576 $position = strpos($newformat, $replacement);
3577 $valuearray[$position] = $value;
3580 ksort($valuearray);
3581 return $valuearray;
3585 * Checks if current user is shown any extra fields when listing users.
3587 * @param object $context Context
3588 * @param array $already Array of fields that we're going to show anyway
3589 * so don't bother listing them
3590 * @return array Array of field names from user table, not including anything
3591 * listed in $already
3593 function get_extra_user_fields($context, $already = array()) {
3594 global $CFG;
3596 // Only users with permission get the extra fields.
3597 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3598 return array();
3601 // Split showuseridentity on comma.
3602 if (empty($CFG->showuseridentity)) {
3603 // Explode gives wrong result with empty string.
3604 $extra = array();
3605 } else {
3606 $extra = explode(',', $CFG->showuseridentity);
3608 $renumber = false;
3609 foreach ($extra as $key => $field) {
3610 if (in_array($field, $already)) {
3611 unset($extra[$key]);
3612 $renumber = true;
3615 if ($renumber) {
3616 // For consistency, if entries are removed from array, renumber it
3617 // so they are numbered as you would expect.
3618 $extra = array_merge($extra);
3620 return $extra;
3624 * If the current user is to be shown extra user fields when listing or
3625 * selecting users, returns a string suitable for including in an SQL select
3626 * clause to retrieve those fields.
3628 * @param context $context Context
3629 * @param string $alias Alias of user table, e.g. 'u' (default none)
3630 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3631 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3632 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3634 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3635 $fields = get_extra_user_fields($context, $already);
3636 $result = '';
3637 // Add punctuation for alias.
3638 if ($alias !== '') {
3639 $alias .= '.';
3641 foreach ($fields as $field) {
3642 $result .= ', ' . $alias . $field;
3643 if ($prefix) {
3644 $result .= ' AS ' . $prefix . $field;
3647 return $result;
3651 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3652 * @param string $field Field name, e.g. 'phone1'
3653 * @return string Text description taken from language file, e.g. 'Phone number'
3655 function get_user_field_name($field) {
3656 // Some fields have language strings which are not the same as field name.
3657 switch ($field) {
3658 case 'url' : {
3659 return get_string('webpage');
3661 case 'icq' : {
3662 return get_string('icqnumber');
3664 case 'skype' : {
3665 return get_string('skypeid');
3667 case 'aim' : {
3668 return get_string('aimid');
3670 case 'yahoo' : {
3671 return get_string('yahooid');
3673 case 'msn' : {
3674 return get_string('msnid');
3677 // Otherwise just use the same lang string.
3678 return get_string($field);
3682 * Returns whether a given authentication plugin exists.
3684 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3685 * @return boolean Whether the plugin is available.
3687 function exists_auth_plugin($auth) {
3688 global $CFG;
3690 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3691 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3693 return false;
3697 * Checks if a given plugin is in the list of enabled authentication plugins.
3699 * @param string $auth Authentication plugin.
3700 * @return boolean Whether the plugin is enabled.
3702 function is_enabled_auth($auth) {
3703 if (empty($auth)) {
3704 return false;
3707 $enabled = get_enabled_auth_plugins();
3709 return in_array($auth, $enabled);
3713 * Returns an authentication plugin instance.
3715 * @param string $auth name of authentication plugin
3716 * @return auth_plugin_base An instance of the required authentication plugin.
3718 function get_auth_plugin($auth) {
3719 global $CFG;
3721 // Check the plugin exists first.
3722 if (! exists_auth_plugin($auth)) {
3723 print_error('authpluginnotfound', 'debug', '', $auth);
3726 // Return auth plugin instance.
3727 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3728 $class = "auth_plugin_$auth";
3729 return new $class;
3733 * Returns array of active auth plugins.
3735 * @param bool $fix fix $CFG->auth if needed
3736 * @return array
3738 function get_enabled_auth_plugins($fix=false) {
3739 global $CFG;
3741 $default = array('manual', 'nologin');
3743 if (empty($CFG->auth)) {
3744 $auths = array();
3745 } else {
3746 $auths = explode(',', $CFG->auth);
3749 if ($fix) {
3750 $auths = array_unique($auths);
3751 foreach ($auths as $k => $authname) {
3752 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3753 unset($auths[$k]);
3756 $newconfig = implode(',', $auths);
3757 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3758 set_config('auth', $newconfig);
3762 return (array_merge($default, $auths));
3766 * Returns true if an internal authentication method is being used.
3767 * if method not specified then, global default is assumed
3769 * @param string $auth Form of authentication required
3770 * @return bool
3772 function is_internal_auth($auth) {
3773 // Throws error if bad $auth.
3774 $authplugin = get_auth_plugin($auth);
3775 return $authplugin->is_internal();
3779 * Returns true if the user is a 'restored' one.
3781 * Used in the login process to inform the user and allow him/her to reset the password
3783 * @param string $username username to be checked
3784 * @return bool
3786 function is_restored_user($username) {
3787 global $CFG, $DB;
3789 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3793 * Returns an array of user fields
3795 * @return array User field/column names
3797 function get_user_fieldnames() {
3798 global $DB;
3800 $fieldarray = $DB->get_columns('user');
3801 unset($fieldarray['id']);
3802 $fieldarray = array_keys($fieldarray);
3804 return $fieldarray;
3808 * Creates a bare-bones user record
3810 * @todo Outline auth types and provide code example
3812 * @param string $username New user's username to add to record
3813 * @param string $password New user's password to add to record
3814 * @param string $auth Form of authentication required
3815 * @return stdClass A complete user object
3817 function create_user_record($username, $password, $auth = 'manual') {
3818 global $CFG, $DB;
3819 require_once($CFG->dirroot.'/user/profile/lib.php');
3820 require_once($CFG->dirroot.'/user/lib.php');
3822 // Just in case check text case.
3823 $username = trim(core_text::strtolower($username));
3825 $authplugin = get_auth_plugin($auth);
3826 $customfields = $authplugin->get_custom_user_profile_fields();
3827 $newuser = new stdClass();
3828 if ($newinfo = $authplugin->get_userinfo($username)) {
3829 $newinfo = truncate_userinfo($newinfo);
3830 foreach ($newinfo as $key => $value) {
3831 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3832 $newuser->$key = $value;
3837 if (!empty($newuser->email)) {
3838 if (email_is_not_allowed($newuser->email)) {
3839 unset($newuser->email);
3843 if (!isset($newuser->city)) {
3844 $newuser->city = '';
3847 $newuser->auth = $auth;
3848 $newuser->username = $username;
3850 // Fix for MDL-8480
3851 // user CFG lang for user if $newuser->lang is empty
3852 // or $user->lang is not an installed language.
3853 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3854 $newuser->lang = $CFG->lang;
3856 $newuser->confirmed = 1;
3857 $newuser->lastip = getremoteaddr();
3858 $newuser->timecreated = time();
3859 $newuser->timemodified = $newuser->timecreated;
3860 $newuser->mnethostid = $CFG->mnet_localhost_id;
3862 $newuser->id = user_create_user($newuser, false, false);
3864 // Save user profile data.
3865 profile_save_data($newuser);
3867 $user = get_complete_user_data('id', $newuser->id);
3868 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3869 set_user_preference('auth_forcepasswordchange', 1, $user);
3871 // Set the password.
3872 update_internal_user_password($user, $password);
3874 // Trigger event.
3875 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3877 return $user;
3881 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3883 * @param string $username user's username to update the record
3884 * @return stdClass A complete user object
3886 function update_user_record($username) {
3887 global $DB, $CFG;
3888 // Just in case check text case.
3889 $username = trim(core_text::strtolower($username));
3891 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3892 return update_user_record_by_id($oldinfo->id);
3896 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3898 * @param int $id user id
3899 * @return stdClass A complete user object
3901 function update_user_record_by_id($id) {
3902 global $DB, $CFG;
3903 require_once($CFG->dirroot."/user/profile/lib.php");
3904 require_once($CFG->dirroot.'/user/lib.php');
3906 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3907 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3909 $newuser = array();
3910 $userauth = get_auth_plugin($oldinfo->auth);
3912 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3913 $newinfo = truncate_userinfo($newinfo);
3914 $customfields = $userauth->get_custom_user_profile_fields();
3916 foreach ($newinfo as $key => $value) {
3917 $iscustom = in_array($key, $customfields);
3918 if (!$iscustom) {
3919 $key = strtolower($key);
3921 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3922 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3923 // Unknown or must not be changed.
3924 continue;
3926 $confval = $userauth->config->{'field_updatelocal_' . $key};
3927 $lockval = $userauth->config->{'field_lock_' . $key};
3928 if (empty($confval) || empty($lockval)) {
3929 continue;
3931 if ($confval === 'onlogin') {
3932 // MDL-4207 Don't overwrite modified user profile values with
3933 // empty LDAP values when 'unlocked if empty' is set. The purpose
3934 // of the setting 'unlocked if empty' is to allow the user to fill
3935 // in a value for the selected field _if LDAP is giving
3936 // nothing_ for this field. Thus it makes sense to let this value
3937 // stand in until LDAP is giving a value for this field.
3938 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3939 if ($iscustom || (in_array($key, $userauth->userfields) &&
3940 ((string)$oldinfo->$key !== (string)$value))) {
3941 $newuser[$key] = (string)$value;
3946 if ($newuser) {
3947 $newuser['id'] = $oldinfo->id;
3948 $newuser['timemodified'] = time();
3949 user_update_user((object) $newuser, false, false);
3951 // Save user profile data.
3952 profile_save_data((object) $newuser);
3954 // Trigger event.
3955 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
3959 return get_complete_user_data('id', $oldinfo->id);
3963 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
3965 * @param array $info Array of user properties to truncate if needed
3966 * @return array The now truncated information that was passed in
3968 function truncate_userinfo(array $info) {
3969 // Define the limits.
3970 $limit = array(
3971 'username' => 100,
3972 'idnumber' => 255,
3973 'firstname' => 100,
3974 'lastname' => 100,
3975 'email' => 100,
3976 'icq' => 15,
3977 'phone1' => 20,
3978 'phone2' => 20,
3979 'institution' => 255,
3980 'department' => 255,
3981 'address' => 255,
3982 'city' => 120,
3983 'country' => 2,
3984 'url' => 255,
3987 // Apply where needed.
3988 foreach (array_keys($info) as $key) {
3989 if (!empty($limit[$key])) {
3990 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
3994 return $info;
3998 * Marks user deleted in internal user database and notifies the auth plugin.
3999 * Also unenrols user from all roles and does other cleanup.
4001 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4003 * @param stdClass $user full user object before delete
4004 * @return boolean success
4005 * @throws coding_exception if invalid $user parameter detected
4007 function delete_user(stdClass $user) {
4008 global $CFG, $DB;
4009 require_once($CFG->libdir.'/grouplib.php');
4010 require_once($CFG->libdir.'/gradelib.php');
4011 require_once($CFG->dirroot.'/message/lib.php');
4012 require_once($CFG->dirroot.'/user/lib.php');
4014 // Make sure nobody sends bogus record type as parameter.
4015 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4016 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4019 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4020 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4021 debugging('Attempt to delete unknown user account.');
4022 return false;
4025 // There must be always exactly one guest record, originally the guest account was identified by username only,
4026 // now we use $CFG->siteguest for performance reasons.
4027 if ($user->username === 'guest' or isguestuser($user)) {
4028 debugging('Guest user account can not be deleted.');
4029 return false;
4032 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4033 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4034 if ($user->auth === 'manual' and is_siteadmin($user)) {
4035 debugging('Local administrator accounts can not be deleted.');
4036 return false;
4039 // Allow plugins to use this user object before we completely delete it.
4040 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4041 foreach ($pluginsfunction as $plugintype => $plugins) {
4042 foreach ($plugins as $pluginfunction) {
4043 $pluginfunction($user);
4048 // Keep user record before updating it, as we have to pass this to user_deleted event.
4049 $olduser = clone $user;
4051 // Keep a copy of user context, we need it for event.
4052 $usercontext = context_user::instance($user->id);
4054 // Delete all grades - backup is kept in grade_grades_history table.
4055 grade_user_delete($user->id);
4057 // Move unread messages from this user to read.
4058 message_move_userfrom_unread2read($user->id);
4060 // TODO: remove from cohorts using standard API here.
4062 // Remove user tags.
4063 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4065 // Unconditionally unenrol from all courses.
4066 enrol_user_delete($user);
4068 // Unenrol from all roles in all contexts.
4069 // This might be slow but it is really needed - modules might do some extra cleanup!
4070 role_unassign_all(array('userid' => $user->id));
4072 // Now do a brute force cleanup.
4074 // Remove from all cohorts.
4075 $DB->delete_records('cohort_members', array('userid' => $user->id));
4077 // Remove from all groups.
4078 $DB->delete_records('groups_members', array('userid' => $user->id));
4080 // Brute force unenrol from all courses.
4081 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4083 // Purge user preferences.
4084 $DB->delete_records('user_preferences', array('userid' => $user->id));
4086 // Purge user extra profile info.
4087 $DB->delete_records('user_info_data', array('userid' => $user->id));
4089 // Purge log of previous password hashes.
4090 $DB->delete_records('user_password_history', array('userid' => $user->id));
4092 // Last course access not necessary either.
4093 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4094 // Remove all user tokens.
4095 $DB->delete_records('external_tokens', array('userid' => $user->id));
4097 // Unauthorise the user for all services.
4098 $DB->delete_records('external_services_users', array('userid' => $user->id));
4100 // Remove users private keys.
4101 $DB->delete_records('user_private_key', array('userid' => $user->id));
4103 // Remove users customised pages.
4104 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4106 // Force logout - may fail if file based sessions used, sorry.
4107 \core\session\manager::kill_user_sessions($user->id);
4109 // Generate username from email address, or a fake email.
4110 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4111 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
4113 // Workaround for bulk deletes of users with the same email address.
4114 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4115 $delname++;
4118 // Mark internal user record as "deleted".
4119 $updateuser = new stdClass();
4120 $updateuser->id = $user->id;
4121 $updateuser->deleted = 1;
4122 $updateuser->username = $delname; // Remember it just in case.
4123 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4124 $updateuser->idnumber = ''; // Clear this field to free it up.
4125 $updateuser->picture = 0;
4126 $updateuser->timemodified = time();
4128 // Don't trigger update event, as user is being deleted.
4129 user_update_user($updateuser, false, false);
4131 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4132 context_helper::delete_instance(CONTEXT_USER, $user->id);
4134 // Any plugin that needs to cleanup should register this event.
4135 // Trigger event.
4136 $event = \core\event\user_deleted::create(
4137 array(
4138 'objectid' => $user->id,
4139 'relateduserid' => $user->id,
4140 'context' => $usercontext,
4141 'other' => array(
4142 'username' => $user->username,
4143 'email' => $user->email,
4144 'idnumber' => $user->idnumber,
4145 'picture' => $user->picture,
4146 'mnethostid' => $user->mnethostid
4150 $event->add_record_snapshot('user', $olduser);
4151 $event->trigger();
4153 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4154 // should know about this updated property persisted to the user's table.
4155 $user->timemodified = $updateuser->timemodified;
4157 // Notify auth plugin - do not block the delete even when plugin fails.
4158 $authplugin = get_auth_plugin($user->auth);
4159 $authplugin->user_delete($user);
4161 return true;
4165 * Retrieve the guest user object.
4167 * @return stdClass A {@link $USER} object
4169 function guest_user() {
4170 global $CFG, $DB;
4172 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4173 $newuser->confirmed = 1;
4174 $newuser->lang = $CFG->lang;
4175 $newuser->lastip = getremoteaddr();
4178 return $newuser;
4182 * Authenticates a user against the chosen authentication mechanism
4184 * Given a username and password, this function looks them
4185 * up using the currently selected authentication mechanism,
4186 * and if the authentication is successful, it returns a
4187 * valid $user object from the 'user' table.
4189 * Uses auth_ functions from the currently active auth module
4191 * After authenticate_user_login() returns success, you will need to
4192 * log that the user has logged in, and call complete_user_login() to set
4193 * the session up.
4195 * Note: this function works only with non-mnet accounts!
4197 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4198 * @param string $password User's password
4199 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4200 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4201 * @return stdClass|false A {@link $USER} object or false if error
4203 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4204 global $CFG, $DB;
4205 require_once("$CFG->libdir/authlib.php");
4207 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4208 // we have found the user
4210 } else if (!empty($CFG->authloginviaemail)) {
4211 if ($email = clean_param($username, PARAM_EMAIL)) {
4212 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4213 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4214 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4215 if (count($users) === 1) {
4216 // Use email for login only if unique.
4217 $user = reset($users);
4218 $user = get_complete_user_data('id', $user->id);
4219 $username = $user->username;
4221 unset($users);
4225 $authsenabled = get_enabled_auth_plugins();
4227 if ($user) {
4228 // Use manual if auth not set.
4229 $auth = empty($user->auth) ? 'manual' : $user->auth;
4231 if (in_array($user->auth, $authsenabled)) {
4232 $authplugin = get_auth_plugin($user->auth);
4233 $authplugin->pre_user_login_hook($user);
4236 if (!empty($user->suspended)) {
4237 $failurereason = AUTH_LOGIN_SUSPENDED;
4239 // Trigger login failed event.
4240 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4241 'other' => array('username' => $username, 'reason' => $failurereason)));
4242 $event->trigger();
4243 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4244 return false;
4246 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4247 // Legacy way to suspend user.
4248 $failurereason = AUTH_LOGIN_SUSPENDED;
4250 // Trigger login failed event.
4251 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4252 'other' => array('username' => $username, 'reason' => $failurereason)));
4253 $event->trigger();
4254 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4255 return false;
4257 $auths = array($auth);
4259 } else {
4260 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4261 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4262 $failurereason = AUTH_LOGIN_NOUSER;
4264 // Trigger login failed event.
4265 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4266 'reason' => $failurereason)));
4267 $event->trigger();
4268 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4269 return false;
4272 // User does not exist.
4273 $auths = $authsenabled;
4274 $user = new stdClass();
4275 $user->id = 0;
4278 if ($ignorelockout) {
4279 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4280 // or this function is called from a SSO script.
4281 } else if ($user->id) {
4282 // Verify login lockout after other ways that may prevent user login.
4283 if (login_is_lockedout($user)) {
4284 $failurereason = AUTH_LOGIN_LOCKOUT;
4286 // Trigger login failed event.
4287 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4288 'other' => array('username' => $username, 'reason' => $failurereason)));
4289 $event->trigger();
4291 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4292 return false;
4294 } else {
4295 // We can not lockout non-existing accounts.
4298 foreach ($auths as $auth) {
4299 $authplugin = get_auth_plugin($auth);
4301 // On auth fail fall through to the next plugin.
4302 if (!$authplugin->user_login($username, $password)) {
4303 continue;
4306 // Successful authentication.
4307 if ($user->id) {
4308 // User already exists in database.
4309 if (empty($user->auth)) {
4310 // For some reason auth isn't set yet.
4311 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4312 $user->auth = $auth;
4315 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4316 // the current hash algorithm while we have access to the user's password.
4317 update_internal_user_password($user, $password);
4319 if ($authplugin->is_synchronised_with_external()) {
4320 // Update user record from external DB.
4321 $user = update_user_record_by_id($user->id);
4323 } else {
4324 // The user is authenticated but user creation may be disabled.
4325 if (!empty($CFG->authpreventaccountcreation)) {
4326 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4328 // Trigger login failed event.
4329 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4330 'reason' => $failurereason)));
4331 $event->trigger();
4333 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4334 $_SERVER['HTTP_USER_AGENT']);
4335 return false;
4336 } else {
4337 $user = create_user_record($username, $password, $auth);
4341 $authplugin->sync_roles($user);
4343 foreach ($authsenabled as $hau) {
4344 $hauth = get_auth_plugin($hau);
4345 $hauth->user_authenticated_hook($user, $username, $password);
4348 if (empty($user->id)) {
4349 $failurereason = AUTH_LOGIN_NOUSER;
4350 // Trigger login failed event.
4351 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4352 'reason' => $failurereason)));
4353 $event->trigger();
4354 return false;
4357 if (!empty($user->suspended)) {
4358 // Just in case some auth plugin suspended account.
4359 $failurereason = AUTH_LOGIN_SUSPENDED;
4360 // Trigger login failed event.
4361 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4362 'other' => array('username' => $username, 'reason' => $failurereason)));
4363 $event->trigger();
4364 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4365 return false;
4368 login_attempt_valid($user);
4369 $failurereason = AUTH_LOGIN_OK;
4370 return $user;
4373 // Failed if all the plugins have failed.
4374 if (debugging('', DEBUG_ALL)) {
4375 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4378 if ($user->id) {
4379 login_attempt_failed($user);
4380 $failurereason = AUTH_LOGIN_FAILED;
4381 // Trigger login failed event.
4382 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4383 'other' => array('username' => $username, 'reason' => $failurereason)));
4384 $event->trigger();
4385 } else {
4386 $failurereason = AUTH_LOGIN_NOUSER;
4387 // Trigger login failed event.
4388 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4389 'reason' => $failurereason)));
4390 $event->trigger();
4393 return false;
4397 * Call to complete the user login process after authenticate_user_login()
4398 * has succeeded. It will setup the $USER variable and other required bits
4399 * and pieces.
4401 * NOTE:
4402 * - It will NOT log anything -- up to the caller to decide what to log.
4403 * - this function does not set any cookies any more!
4405 * @param stdClass $user
4406 * @return stdClass A {@link $USER} object - BC only, do not use
4408 function complete_user_login($user) {
4409 global $CFG, $USER, $SESSION;
4411 \core\session\manager::login_user($user);
4413 // Reload preferences from DB.
4414 unset($USER->preference);
4415 check_user_preferences_loaded($USER);
4417 // Update login times.
4418 update_user_login_times();
4420 // Extra session prefs init.
4421 set_login_session_preferences();
4423 // Trigger login event.
4424 $event = \core\event\user_loggedin::create(
4425 array(
4426 'userid' => $USER->id,
4427 'objectid' => $USER->id,
4428 'other' => array('username' => $USER->username),
4431 $event->trigger();
4433 if (isguestuser()) {
4434 // No need to continue when user is THE guest.
4435 return $USER;
4438 if (CLI_SCRIPT) {
4439 // We can redirect to password change URL only in browser.
4440 return $USER;
4443 // Select password change url.
4444 $userauth = get_auth_plugin($USER->auth);
4446 // Check whether the user should be changing password.
4447 if (get_user_preferences('auth_forcepasswordchange', false)) {
4448 if ($userauth->can_change_password()) {
4449 if ($changeurl = $userauth->change_password_url()) {
4450 redirect($changeurl);
4451 } else {
4452 require_once($CFG->dirroot . '/login/lib.php');
4453 $SESSION->wantsurl = core_login_get_return_url();
4454 redirect($CFG->httpswwwroot.'/login/change_password.php');
4456 } else {
4457 print_error('nopasswordchangeforced', 'auth');
4460 return $USER;
4464 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4466 * @param string $password String to check.
4467 * @return boolean True if the $password matches the format of an md5 sum.
4469 function password_is_legacy_hash($password) {
4470 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4474 * Compare password against hash stored in user object to determine if it is valid.
4476 * If necessary it also updates the stored hash to the current format.
4478 * @param stdClass $user (Password property may be updated).
4479 * @param string $password Plain text password.
4480 * @return bool True if password is valid.
4482 function validate_internal_user_password($user, $password) {
4483 global $CFG;
4485 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4486 // Internal password is not used at all, it can not validate.
4487 return false;
4490 // If hash isn't a legacy (md5) hash, validate using the library function.
4491 if (!password_is_legacy_hash($user->password)) {
4492 return password_verify($password, $user->password);
4495 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4496 // is valid we can then update it to the new algorithm.
4498 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4499 $validated = false;
4501 if ($user->password === md5($password.$sitesalt)
4502 or $user->password === md5($password)
4503 or $user->password === md5(addslashes($password).$sitesalt)
4504 or $user->password === md5(addslashes($password))) {
4505 // Note: we are intentionally using the addslashes() here because we
4506 // need to accept old password hashes of passwords with magic quotes.
4507 $validated = true;
4509 } else {
4510 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4511 $alt = 'passwordsaltalt'.$i;
4512 if (!empty($CFG->$alt)) {
4513 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4514 $validated = true;
4515 break;
4521 if ($validated) {
4522 // If the password matches the existing md5 hash, update to the
4523 // current hash algorithm while we have access to the user's password.
4524 update_internal_user_password($user, $password);
4527 return $validated;
4531 * Calculate hash for a plain text password.
4533 * @param string $password Plain text password to be hashed.
4534 * @param bool $fasthash If true, use a low cost factor when generating the hash
4535 * This is much faster to generate but makes the hash
4536 * less secure. It is used when lots of hashes need to
4537 * be generated quickly.
4538 * @return string The hashed password.
4540 * @throws moodle_exception If a problem occurs while generating the hash.
4542 function hash_internal_user_password($password, $fasthash = false) {
4543 global $CFG;
4545 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4546 $options = ($fasthash) ? array('cost' => 4) : array();
4548 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4550 if ($generatedhash === false || $generatedhash === null) {
4551 throw new moodle_exception('Failed to generate password hash.');
4554 return $generatedhash;
4558 * Update password hash in user object (if necessary).
4560 * The password is updated if:
4561 * 1. The password has changed (the hash of $user->password is different
4562 * to the hash of $password).
4563 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4564 * md5 algorithm).
4566 * Updating the password will modify the $user object and the database
4567 * record to use the current hashing algorithm.
4568 * It will remove Web Services user tokens too.
4570 * @param stdClass $user User object (password property may be updated).
4571 * @param string $password Plain text password.
4572 * @param bool $fasthash If true, use a low cost factor when generating the hash
4573 * This is much faster to generate but makes the hash
4574 * less secure. It is used when lots of hashes need to
4575 * be generated quickly.
4576 * @return bool Always returns true.
4578 function update_internal_user_password($user, $password, $fasthash = false) {
4579 global $CFG, $DB;
4581 // Figure out what the hashed password should be.
4582 if (!isset($user->auth)) {
4583 debugging('User record in update_internal_user_password() must include field auth',
4584 DEBUG_DEVELOPER);
4585 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4587 $authplugin = get_auth_plugin($user->auth);
4588 if ($authplugin->prevent_local_passwords()) {
4589 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4590 } else {
4591 $hashedpassword = hash_internal_user_password($password, $fasthash);
4594 $algorithmchanged = false;
4596 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4597 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4598 $passwordchanged = ($user->password !== $hashedpassword);
4600 } else if (isset($user->password)) {
4601 // If verification fails then it means the password has changed.
4602 $passwordchanged = !password_verify($password, $user->password);
4603 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4604 } else {
4605 // While creating new user, password in unset in $user object, to avoid
4606 // saving it with user_create()
4607 $passwordchanged = true;
4610 if ($passwordchanged || $algorithmchanged) {
4611 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4612 $user->password = $hashedpassword;
4614 // Trigger event.
4615 $user = $DB->get_record('user', array('id' => $user->id));
4616 \core\event\user_password_updated::create_from_user($user)->trigger();
4618 // Remove WS user tokens.
4619 if (!empty($CFG->passwordchangetokendeletion)) {
4620 require_once($CFG->dirroot.'/webservice/lib.php');
4621 webservice::delete_user_ws_tokens($user->id);
4625 return true;
4629 * Get a complete user record, which includes all the info in the user record.
4631 * Intended for setting as $USER session variable
4633 * @param string $field The user field to be checked for a given value.
4634 * @param string $value The value to match for $field.
4635 * @param int $mnethostid
4636 * @return mixed False, or A {@link $USER} object.
4638 function get_complete_user_data($field, $value, $mnethostid = null) {
4639 global $CFG, $DB;
4641 if (!$field || !$value) {
4642 return false;
4645 // Build the WHERE clause for an SQL query.
4646 $params = array('fieldval' => $value);
4647 $constraints = "$field = :fieldval AND deleted <> 1";
4649 // If we are loading user data based on anything other than id,
4650 // we must also restrict our search based on mnet host.
4651 if ($field != 'id') {
4652 if (empty($mnethostid)) {
4653 // If empty, we restrict to local users.
4654 $mnethostid = $CFG->mnet_localhost_id;
4657 if (!empty($mnethostid)) {
4658 $params['mnethostid'] = $mnethostid;
4659 $constraints .= " AND mnethostid = :mnethostid";
4662 // Get all the basic user data.
4663 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4664 return false;
4667 // Get various settings and preferences.
4669 // Preload preference cache.
4670 check_user_preferences_loaded($user);
4672 // Load course enrolment related stuff.
4673 $user->lastcourseaccess = array(); // During last session.
4674 $user->currentcourseaccess = array(); // During current session.
4675 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4676 foreach ($lastaccesses as $lastaccess) {
4677 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4681 $sql = "SELECT g.id, g.courseid
4682 FROM {groups} g, {groups_members} gm
4683 WHERE gm.groupid=g.id AND gm.userid=?";
4685 // This is a special hack to speedup calendar display.
4686 $user->groupmember = array();
4687 if (!isguestuser($user)) {
4688 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4689 foreach ($groups as $group) {
4690 if (!array_key_exists($group->courseid, $user->groupmember)) {
4691 $user->groupmember[$group->courseid] = array();
4693 $user->groupmember[$group->courseid][$group->id] = $group->id;
4698 // Add the custom profile fields to the user record.
4699 $user->profile = array();
4700 if (!isguestuser($user)) {
4701 require_once($CFG->dirroot.'/user/profile/lib.php');
4702 profile_load_custom_fields($user);
4705 // Rewrite some variables if necessary.
4706 if (!empty($user->description)) {
4707 // No need to cart all of it around.
4708 $user->description = true;
4710 if (isguestuser($user)) {
4711 // Guest language always same as site.
4712 $user->lang = $CFG->lang;
4713 // Name always in current language.
4714 $user->firstname = get_string('guestuser');
4715 $user->lastname = ' ';
4718 return $user;
4722 * Validate a password against the configured password policy
4724 * @param string $password the password to be checked against the password policy
4725 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4726 * @return bool true if the password is valid according to the policy. false otherwise.
4728 function check_password_policy($password, &$errmsg) {
4729 global $CFG;
4731 if (empty($CFG->passwordpolicy)) {
4732 return true;
4735 $errmsg = '';
4736 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4737 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4740 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4741 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4744 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4745 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4748 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4749 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4752 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4753 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4755 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4756 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4759 if ($errmsg == '') {
4760 return true;
4761 } else {
4762 return false;
4768 * When logging in, this function is run to set certain preferences for the current SESSION.
4770 function set_login_session_preferences() {
4771 global $SESSION;
4773 $SESSION->justloggedin = true;
4775 unset($SESSION->lang);
4776 unset($SESSION->forcelang);
4777 unset($SESSION->load_navigation_admin);
4782 * Delete a course, including all related data from the database, and any associated files.
4784 * @param mixed $courseorid The id of the course or course object to delete.
4785 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4786 * @return bool true if all the removals succeeded. false if there were any failures. If this
4787 * method returns false, some of the removals will probably have succeeded, and others
4788 * failed, but you have no way of knowing which.
4790 function delete_course($courseorid, $showfeedback = true) {
4791 global $DB;
4793 if (is_object($courseorid)) {
4794 $courseid = $courseorid->id;
4795 $course = $courseorid;
4796 } else {
4797 $courseid = $courseorid;
4798 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4799 return false;
4802 $context = context_course::instance($courseid);
4804 // Frontpage course can not be deleted!!
4805 if ($courseid == SITEID) {
4806 return false;
4809 // Allow plugins to use this course before we completely delete it.
4810 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
4811 foreach ($pluginsfunction as $plugintype => $plugins) {
4812 foreach ($plugins as $pluginfunction) {
4813 $pluginfunction($course);
4818 // Make the course completely empty.
4819 remove_course_contents($courseid, $showfeedback);
4821 // Delete the course and related context instance.
4822 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4824 $DB->delete_records("course", array("id" => $courseid));
4825 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4827 // Reset all course related caches here.
4828 if (class_exists('format_base', false)) {
4829 format_base::reset_course_cache($courseid);
4832 // Trigger a course deleted event.
4833 $event = \core\event\course_deleted::create(array(
4834 'objectid' => $course->id,
4835 'context' => $context,
4836 'other' => array(
4837 'shortname' => $course->shortname,
4838 'fullname' => $course->fullname,
4839 'idnumber' => $course->idnumber
4842 $event->add_record_snapshot('course', $course);
4843 $event->trigger();
4845 return true;
4849 * Clear a course out completely, deleting all content but don't delete the course itself.
4851 * This function does not verify any permissions.
4853 * Please note this function also deletes all user enrolments,
4854 * enrolment instances and role assignments by default.
4856 * $options:
4857 * - 'keep_roles_and_enrolments' - false by default
4858 * - 'keep_groups_and_groupings' - false by default
4860 * @param int $courseid The id of the course that is being deleted
4861 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4862 * @param array $options extra options
4863 * @return bool true if all the removals succeeded. false if there were any failures. If this
4864 * method returns false, some of the removals will probably have succeeded, and others
4865 * failed, but you have no way of knowing which.
4867 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4868 global $CFG, $DB, $OUTPUT;
4870 require_once($CFG->libdir.'/badgeslib.php');
4871 require_once($CFG->libdir.'/completionlib.php');
4872 require_once($CFG->libdir.'/questionlib.php');
4873 require_once($CFG->libdir.'/gradelib.php');
4874 require_once($CFG->dirroot.'/group/lib.php');
4875 require_once($CFG->dirroot.'/comment/lib.php');
4876 require_once($CFG->dirroot.'/rating/lib.php');
4877 require_once($CFG->dirroot.'/notes/lib.php');
4879 // Handle course badges.
4880 badges_handle_course_deletion($courseid);
4882 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4883 $strdeleted = get_string('deleted').' - ';
4885 // Some crazy wishlist of stuff we should skip during purging of course content.
4886 $options = (array)$options;
4888 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
4889 $coursecontext = context_course::instance($courseid);
4890 $fs = get_file_storage();
4892 // Delete course completion information, this has to be done before grades and enrols.
4893 $cc = new completion_info($course);
4894 $cc->clear_criteria();
4895 if ($showfeedback) {
4896 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4899 // Remove all data from gradebook - this needs to be done before course modules
4900 // because while deleting this information, the system may need to reference
4901 // the course modules that own the grades.
4902 remove_course_grades($courseid, $showfeedback);
4903 remove_grade_letters($coursecontext, $showfeedback);
4905 // Delete course blocks in any all child contexts,
4906 // they may depend on modules so delete them first.
4907 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4908 foreach ($childcontexts as $childcontext) {
4909 blocks_delete_all_for_context($childcontext->id);
4911 unset($childcontexts);
4912 blocks_delete_all_for_context($coursecontext->id);
4913 if ($showfeedback) {
4914 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4917 // Get the list of all modules that are properly installed.
4918 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
4920 // Delete every instance of every module,
4921 // this has to be done before deleting of course level stuff.
4922 $locations = core_component::get_plugin_list('mod');
4923 foreach ($locations as $modname => $moddir) {
4924 if ($modname === 'NEWMODULE') {
4925 continue;
4927 if (array_key_exists($modname, $allmodules)) {
4928 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
4929 FROM {".$modname."} m
4930 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
4931 WHERE m.course = :courseid";
4932 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
4933 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
4935 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
4936 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
4937 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
4939 if ($instances) {
4940 foreach ($instances as $cm) {
4941 if ($cm->id) {
4942 // Delete activity context questions and question categories.
4943 question_delete_activity($cm, $showfeedback);
4944 // Notify the competency subsystem.
4945 \core_competency\api::hook_course_module_deleted($cm);
4947 if (function_exists($moddelete)) {
4948 // This purges all module data in related tables, extra user prefs, settings, etc.
4949 $moddelete($cm->modinstance);
4950 } else {
4951 // NOTE: we should not allow installation of modules with missing delete support!
4952 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
4953 $DB->delete_records($modname, array('id' => $cm->modinstance));
4956 if ($cm->id) {
4957 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
4958 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4959 $DB->delete_records('course_modules', array('id' => $cm->id));
4963 if (function_exists($moddeletecourse)) {
4964 // Execute optional course cleanup callback. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
4965 debugging("Callback delete_course is deprecated. Function $moddeletecourse should be converted " .
4966 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER);
4967 $moddeletecourse($course, $showfeedback);
4969 if ($instances and $showfeedback) {
4970 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
4972 } else {
4973 // Ooops, this module is not properly installed, force-delete it in the next block.
4977 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
4979 // Remove all data from availability and completion tables that is associated
4980 // with course-modules belonging to this course. Note this is done even if the
4981 // features are not enabled now, in case they were enabled previously.
4982 $DB->delete_records_select('course_modules_completion',
4983 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4984 array($courseid));
4986 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
4987 $cms = $DB->get_records('course_modules', array('course' => $course->id));
4988 $allmodulesbyid = array_flip($allmodules);
4989 foreach ($cms as $cm) {
4990 if (array_key_exists($cm->module, $allmodulesbyid)) {
4991 try {
4992 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
4993 } catch (Exception $e) {
4994 // Ignore weird or missing table problems.
4997 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4998 $DB->delete_records('course_modules', array('id' => $cm->id));
5001 if ($showfeedback) {
5002 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5005 // Cleanup the rest of plugins. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
5006 $cleanuplugintypes = array('report', 'coursereport', 'format');
5007 $callbacks = get_plugins_with_function('delete_course', 'lib.php');
5008 foreach ($cleanuplugintypes as $type) {
5009 if (!empty($callbacks[$type])) {
5010 foreach ($callbacks[$type] as $pluginfunction) {
5011 debugging("Callback delete_course is deprecated. Function $pluginfunction should be converted " .
5012 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER);
5013 $pluginfunction($course->id, $showfeedback);
5015 if ($showfeedback) {
5016 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5021 // Delete questions and question categories.
5022 question_delete_course($course, $showfeedback);
5023 if ($showfeedback) {
5024 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5027 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5028 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5029 foreach ($childcontexts as $childcontext) {
5030 $childcontext->delete();
5032 unset($childcontexts);
5034 // Remove all roles and enrolments by default.
5035 if (empty($options['keep_roles_and_enrolments'])) {
5036 // This hack is used in restore when deleting contents of existing course.
5037 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5038 enrol_course_delete($course);
5039 if ($showfeedback) {
5040 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5044 // Delete any groups, removing members and grouping/course links first.
5045 if (empty($options['keep_groups_and_groupings'])) {
5046 groups_delete_groupings($course->id, $showfeedback);
5047 groups_delete_groups($course->id, $showfeedback);
5050 // Filters be gone!
5051 filter_delete_all_for_context($coursecontext->id);
5053 // Notes, you shall not pass!
5054 note_delete_all($course->id);
5056 // Die comments!
5057 comment::delete_comments($coursecontext->id);
5059 // Ratings are history too.
5060 $delopt = new stdclass();
5061 $delopt->contextid = $coursecontext->id;
5062 $rm = new rating_manager();
5063 $rm->delete_ratings($delopt);
5065 // Delete course tags.
5066 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5068 // Notify the competency subsystem.
5069 \core_competency\api::hook_course_deleted($course);
5071 // Delete calendar events.
5072 $DB->delete_records('event', array('courseid' => $course->id));
5073 $fs->delete_area_files($coursecontext->id, 'calendar');
5075 // Delete all related records in other core tables that may have a courseid
5076 // This array stores the tables that need to be cleared, as
5077 // table_name => column_name that contains the course id.
5078 $tablestoclear = array(
5079 'backup_courses' => 'courseid', // Scheduled backup stuff.
5080 'user_lastaccess' => 'courseid', // User access info.
5082 foreach ($tablestoclear as $table => $col) {
5083 $DB->delete_records($table, array($col => $course->id));
5086 // Delete all course backup files.
5087 $fs->delete_area_files($coursecontext->id, 'backup');
5089 // Cleanup course record - remove links to deleted stuff.
5090 $oldcourse = new stdClass();
5091 $oldcourse->id = $course->id;
5092 $oldcourse->summary = '';
5093 $oldcourse->cacherev = 0;
5094 $oldcourse->legacyfiles = 0;
5095 if (!empty($options['keep_groups_and_groupings'])) {
5096 $oldcourse->defaultgroupingid = 0;
5098 $DB->update_record('course', $oldcourse);
5100 // Delete course sections.
5101 $DB->delete_records('course_sections', array('course' => $course->id));
5103 // Delete legacy, section and any other course files.
5104 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5106 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5107 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5108 // Easy, do not delete the context itself...
5109 $coursecontext->delete_content();
5110 } else {
5111 // Hack alert!!!!
5112 // We can not drop all context stuff because it would bork enrolments and roles,
5113 // there might be also files used by enrol plugins...
5116 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5117 // also some non-standard unsupported plugins may try to store something there.
5118 fulldelete($CFG->dataroot.'/'.$course->id);
5120 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5121 $cachemodinfo = cache::make('core', 'coursemodinfo');
5122 $cachemodinfo->delete($courseid);
5124 // Trigger a course content deleted event.
5125 $event = \core\event\course_content_deleted::create(array(
5126 'objectid' => $course->id,
5127 'context' => $coursecontext,
5128 'other' => array('shortname' => $course->shortname,
5129 'fullname' => $course->fullname,
5130 'options' => $options) // Passing this for legacy reasons.
5132 $event->add_record_snapshot('course', $course);
5133 $event->trigger();
5135 return true;
5139 * Change dates in module - used from course reset.
5141 * @param string $modname forum, assignment, etc
5142 * @param array $fields array of date fields from mod table
5143 * @param int $timeshift time difference
5144 * @param int $courseid
5145 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5146 * @return bool success
5148 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5149 global $CFG, $DB;
5150 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5152 $return = true;
5153 $params = array($timeshift, $courseid);
5154 foreach ($fields as $field) {
5155 $updatesql = "UPDATE {".$modname."}
5156 SET $field = $field + ?
5157 WHERE course=? AND $field<>0";
5158 if ($modid) {
5159 $updatesql .= ' AND id=?';
5160 $params[] = $modid;
5162 $return = $DB->execute($updatesql, $params) && $return;
5165 $refreshfunction = $modname.'_refresh_events';
5166 if (function_exists($refreshfunction)) {
5167 $refreshfunction($courseid);
5170 return $return;
5174 * This function will empty a course of user data.
5175 * It will retain the activities and the structure of the course.
5177 * @param object $data an object containing all the settings including courseid (without magic quotes)
5178 * @return array status array of array component, item, error
5180 function reset_course_userdata($data) {
5181 global $CFG, $DB;
5182 require_once($CFG->libdir.'/gradelib.php');
5183 require_once($CFG->libdir.'/completionlib.php');
5184 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5185 require_once($CFG->dirroot.'/group/lib.php');
5187 $data->courseid = $data->id;
5188 $context = context_course::instance($data->courseid);
5190 $eventparams = array(
5191 'context' => $context,
5192 'courseid' => $data->id,
5193 'other' => array(
5194 'reset_options' => (array) $data
5197 $event = \core\event\course_reset_started::create($eventparams);
5198 $event->trigger();
5200 // Calculate the time shift of dates.
5201 if (!empty($data->reset_start_date)) {
5202 // Time part of course startdate should be zero.
5203 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5204 } else {
5205 $data->timeshift = 0;
5208 // Result array: component, item, error.
5209 $status = array();
5211 // Start the resetting.
5212 $componentstr = get_string('general');
5214 // Move the course start time.
5215 if (!empty($data->reset_start_date) and $data->timeshift) {
5216 // Change course start data.
5217 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5218 // Update all course and group events - do not move activity events.
5219 $updatesql = "UPDATE {event}
5220 SET timestart = timestart + ?
5221 WHERE courseid=? AND instance=0";
5222 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5224 // Update any date activity restrictions.
5225 if ($CFG->enableavailability) {
5226 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5229 // Update completion expected dates.
5230 if ($CFG->enablecompletion) {
5231 $modinfo = get_fast_modinfo($data->courseid);
5232 $changed = false;
5233 foreach ($modinfo->get_cms() as $cm) {
5234 if ($cm->completion && !empty($cm->completionexpected)) {
5235 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5236 array('id' => $cm->id));
5237 $changed = true;
5241 // Clear course cache if changes made.
5242 if ($changed) {
5243 rebuild_course_cache($data->courseid, true);
5246 // Update course date completion criteria.
5247 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5250 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5253 if (!empty($data->reset_end_date)) {
5254 // If the user set a end date value respect it.
5255 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5256 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5257 // If there is a time shift apply it to the end date as well.
5258 $enddate = $data->reset_end_date_old + $data->timeshift;
5259 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5262 if (!empty($data->reset_events)) {
5263 $DB->delete_records('event', array('courseid' => $data->courseid));
5264 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5267 if (!empty($data->reset_notes)) {
5268 require_once($CFG->dirroot.'/notes/lib.php');
5269 note_delete_all($data->courseid);
5270 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5273 if (!empty($data->delete_blog_associations)) {
5274 require_once($CFG->dirroot.'/blog/lib.php');
5275 blog_remove_associations_for_course($data->courseid);
5276 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5279 if (!empty($data->reset_completion)) {
5280 // Delete course and activity completion information.
5281 $course = $DB->get_record('course', array('id' => $data->courseid));
5282 $cc = new completion_info($course);
5283 $cc->delete_all_completion_data();
5284 $status[] = array('component' => $componentstr,
5285 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5288 if (!empty($data->reset_competency_ratings)) {
5289 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5290 $status[] = array('component' => $componentstr,
5291 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5294 $componentstr = get_string('roles');
5296 if (!empty($data->reset_roles_overrides)) {
5297 $children = $context->get_child_contexts();
5298 foreach ($children as $child) {
5299 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5301 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5302 // Force refresh for logged in users.
5303 $context->mark_dirty();
5304 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5307 if (!empty($data->reset_roles_local)) {
5308 $children = $context->get_child_contexts();
5309 foreach ($children as $child) {
5310 role_unassign_all(array('contextid' => $child->id));
5312 // Force refresh for logged in users.
5313 $context->mark_dirty();
5314 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5317 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5318 $data->unenrolled = array();
5319 if (!empty($data->unenrol_users)) {
5320 $plugins = enrol_get_plugins(true);
5321 $instances = enrol_get_instances($data->courseid, true);
5322 foreach ($instances as $key => $instance) {
5323 if (!isset($plugins[$instance->enrol])) {
5324 unset($instances[$key]);
5325 continue;
5329 foreach ($data->unenrol_users as $withroleid) {
5330 if ($withroleid) {
5331 $sql = "SELECT ue.*
5332 FROM {user_enrolments} ue
5333 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5334 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5335 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5336 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5338 } else {
5339 // Without any role assigned at course context.
5340 $sql = "SELECT ue.*
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 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5345 WHERE ra.id IS null";
5346 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5349 $rs = $DB->get_recordset_sql($sql, $params);
5350 foreach ($rs as $ue) {
5351 if (!isset($instances[$ue->enrolid])) {
5352 continue;
5354 $instance = $instances[$ue->enrolid];
5355 $plugin = $plugins[$instance->enrol];
5356 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5357 continue;
5360 $plugin->unenrol_user($instance, $ue->userid);
5361 $data->unenrolled[$ue->userid] = $ue->userid;
5363 $rs->close();
5366 if (!empty($data->unenrolled)) {
5367 $status[] = array(
5368 'component' => $componentstr,
5369 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5370 'error' => false
5374 $componentstr = get_string('groups');
5376 // Remove all group members.
5377 if (!empty($data->reset_groups_members)) {
5378 groups_delete_group_members($data->courseid);
5379 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5382 // Remove all groups.
5383 if (!empty($data->reset_groups_remove)) {
5384 groups_delete_groups($data->courseid, false);
5385 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5388 // Remove all grouping members.
5389 if (!empty($data->reset_groupings_members)) {
5390 groups_delete_groupings_groups($data->courseid, false);
5391 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5394 // Remove all groupings.
5395 if (!empty($data->reset_groupings_remove)) {
5396 groups_delete_groupings($data->courseid, false);
5397 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5400 // Look in every instance of every module for data to delete.
5401 $unsupportedmods = array();
5402 if ($allmods = $DB->get_records('modules') ) {
5403 foreach ($allmods as $mod) {
5404 $modname = $mod->name;
5405 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5406 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5407 if (file_exists($modfile)) {
5408 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5409 continue; // Skip mods with no instances.
5411 include_once($modfile);
5412 if (function_exists($moddeleteuserdata)) {
5413 $modstatus = $moddeleteuserdata($data);
5414 if (is_array($modstatus)) {
5415 $status = array_merge($status, $modstatus);
5416 } else {
5417 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5419 } else {
5420 $unsupportedmods[] = $mod;
5422 } else {
5423 debugging('Missing lib.php in '.$modname.' module!');
5428 // Mention unsupported mods.
5429 if (!empty($unsupportedmods)) {
5430 foreach ($unsupportedmods as $mod) {
5431 $status[] = array(
5432 'component' => get_string('modulenameplural', $mod->name),
5433 'item' => '',
5434 'error' => get_string('resetnotimplemented')
5439 $componentstr = get_string('gradebook', 'grades');
5440 // Reset gradebook,.
5441 if (!empty($data->reset_gradebook_items)) {
5442 remove_course_grades($data->courseid, false);
5443 grade_grab_course_grades($data->courseid);
5444 grade_regrade_final_grades($data->courseid);
5445 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5447 } else if (!empty($data->reset_gradebook_grades)) {
5448 grade_course_reset($data->courseid);
5449 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5451 // Reset comments.
5452 if (!empty($data->reset_comments)) {
5453 require_once($CFG->dirroot.'/comment/lib.php');
5454 comment::reset_course_page_comments($context);
5457 $event = \core\event\course_reset_ended::create($eventparams);
5458 $event->trigger();
5460 return $status;
5464 * Generate an email processing address.
5466 * @param int $modid
5467 * @param string $modargs
5468 * @return string Returns email processing address
5470 function generate_email_processing_address($modid, $modargs) {
5471 global $CFG;
5473 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5474 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5480 * @todo Finish documenting this function
5482 * @param string $modargs
5483 * @param string $body Currently unused
5485 function moodle_process_email($modargs, $body) {
5486 global $DB;
5488 // The first char should be an unencoded letter. We'll take this as an action.
5489 switch ($modargs{0}) {
5490 case 'B': { // Bounce.
5491 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5492 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5493 // Check the half md5 of their email.
5494 $md5check = substr(md5($user->email), 0, 16);
5495 if ($md5check == substr($modargs, -16)) {
5496 set_bounce_count($user);
5498 // Else maybe they've already changed it?
5501 break;
5502 // Maybe more later?
5506 // CORRESPONDENCE.
5509 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5511 * @param string $action 'get', 'buffer', 'close' or 'flush'
5512 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5514 function get_mailer($action='get') {
5515 global $CFG;
5517 /** @var moodle_phpmailer $mailer */
5518 static $mailer = null;
5519 static $counter = 0;
5521 if (!isset($CFG->smtpmaxbulk)) {
5522 $CFG->smtpmaxbulk = 1;
5525 if ($action == 'get') {
5526 $prevkeepalive = false;
5528 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5529 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5530 $counter++;
5531 // Reset the mailer.
5532 $mailer->Priority = 3;
5533 $mailer->CharSet = 'UTF-8'; // Our default.
5534 $mailer->ContentType = "text/plain";
5535 $mailer->Encoding = "8bit";
5536 $mailer->From = "root@localhost";
5537 $mailer->FromName = "Root User";
5538 $mailer->Sender = "";
5539 $mailer->Subject = "";
5540 $mailer->Body = "";
5541 $mailer->AltBody = "";
5542 $mailer->ConfirmReadingTo = "";
5544 $mailer->clearAllRecipients();
5545 $mailer->clearReplyTos();
5546 $mailer->clearAttachments();
5547 $mailer->clearCustomHeaders();
5548 return $mailer;
5551 $prevkeepalive = $mailer->SMTPKeepAlive;
5552 get_mailer('flush');
5555 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5556 $mailer = new moodle_phpmailer();
5558 $counter = 1;
5560 if ($CFG->smtphosts == 'qmail') {
5561 // Use Qmail system.
5562 $mailer->isQmail();
5564 } else if (empty($CFG->smtphosts)) {
5565 // Use PHP mail() = sendmail.
5566 $mailer->isMail();
5568 } else {
5569 // Use SMTP directly.
5570 $mailer->isSMTP();
5571 if (!empty($CFG->debugsmtp)) {
5572 $mailer->SMTPDebug = true;
5574 // Specify main and backup servers.
5575 $mailer->Host = $CFG->smtphosts;
5576 // Specify secure connection protocol.
5577 $mailer->SMTPSecure = $CFG->smtpsecure;
5578 // Use previous keepalive.
5579 $mailer->SMTPKeepAlive = $prevkeepalive;
5581 if ($CFG->smtpuser) {
5582 // Use SMTP authentication.
5583 $mailer->SMTPAuth = true;
5584 $mailer->Username = $CFG->smtpuser;
5585 $mailer->Password = $CFG->smtppass;
5589 return $mailer;
5592 $nothing = null;
5594 // Keep smtp session open after sending.
5595 if ($action == 'buffer') {
5596 if (!empty($CFG->smtpmaxbulk)) {
5597 get_mailer('flush');
5598 $m = get_mailer();
5599 if ($m->Mailer == 'smtp') {
5600 $m->SMTPKeepAlive = true;
5603 return $nothing;
5606 // Close smtp session, but continue buffering.
5607 if ($action == 'flush') {
5608 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5609 if (!empty($mailer->SMTPDebug)) {
5610 echo '<pre>'."\n";
5612 $mailer->SmtpClose();
5613 if (!empty($mailer->SMTPDebug)) {
5614 echo '</pre>';
5617 return $nothing;
5620 // Close smtp session, do not buffer anymore.
5621 if ($action == 'close') {
5622 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5623 get_mailer('flush');
5624 $mailer->SMTPKeepAlive = false;
5626 $mailer = null; // Better force new instance.
5627 return $nothing;
5632 * A helper function to test for email diversion
5634 * @param string $email
5635 * @return bool Returns true if the email should be diverted
5637 function email_should_be_diverted($email) {
5638 global $CFG;
5640 if (empty($CFG->divertallemailsto)) {
5641 return false;
5644 if (empty($CFG->divertallemailsexcept)) {
5645 return true;
5648 $patterns = array_map('trim', explode(',', $CFG->divertallemailsexcept));
5649 foreach ($patterns as $pattern) {
5650 if (preg_match("/$pattern/", $email)) {
5651 return false;
5655 return true;
5659 * Generate a unique email Message-ID using the moodle domain and install path
5661 * @param string $localpart An optional unique message id prefix.
5662 * @return string The formatted ID ready for appending to the email headers.
5664 function generate_email_messageid($localpart = null) {
5665 global $CFG;
5667 $urlinfo = parse_url($CFG->wwwroot);
5668 $base = '@' . $urlinfo['host'];
5670 // If multiple moodles are on the same domain we want to tell them
5671 // apart so we add the install path to the local part. This means
5672 // that the id local part should never contain a / character so
5673 // we can correctly parse the id to reassemble the wwwroot.
5674 if (isset($urlinfo['path'])) {
5675 $base = $urlinfo['path'] . $base;
5678 if (empty($localpart)) {
5679 $localpart = uniqid('', true);
5682 // Because we may have an option /installpath suffix to the local part
5683 // of the id we need to escape any / chars which are in the $localpart.
5684 $localpart = str_replace('/', '%2F', $localpart);
5686 return '<' . $localpart . $base . '>';
5690 * Send an email to a specified user
5692 * @param stdClass $user A {@link $USER} object
5693 * @param stdClass $from A {@link $USER} object
5694 * @param string $subject plain text subject line of the email
5695 * @param string $messagetext plain text version of the message
5696 * @param string $messagehtml complete html version of the message (optional)
5697 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5698 * @param string $attachname the name of the file (extension indicates MIME)
5699 * @param bool $usetrueaddress determines whether $from email address should
5700 * be sent out. Will be overruled by user profile setting for maildisplay
5701 * @param string $replyto Email address to reply to
5702 * @param string $replytoname Name of reply to recipient
5703 * @param int $wordwrapwidth custom word wrap width, default 79
5704 * @return bool Returns true if mail was sent OK and false if there was an error.
5706 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5707 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5709 global $CFG, $PAGE, $SITE;
5711 if (empty($user) or empty($user->id)) {
5712 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5713 return false;
5716 if (empty($user->email)) {
5717 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5718 return false;
5721 if (!empty($user->deleted)) {
5722 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5723 return false;
5726 if (defined('BEHAT_SITE_RUNNING')) {
5727 // Fake email sending in behat.
5728 return true;
5731 if (!empty($CFG->noemailever)) {
5732 // Hidden setting for development sites, set in config.php if needed.
5733 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5734 return true;
5737 if (email_should_be_diverted($user->email)) {
5738 $subject = "[DIVERTED {$user->email}] $subject";
5739 $user = clone($user);
5740 $user->email = $CFG->divertallemailsto;
5743 // Skip mail to suspended users.
5744 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5745 return true;
5748 if (!validate_email($user->email)) {
5749 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5750 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5751 return false;
5754 if (over_bounce_threshold($user)) {
5755 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5756 return false;
5759 // TLD .invalid is specifically reserved for invalid domain names.
5760 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5761 if (substr($user->email, -8) == '.invalid') {
5762 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5763 return true; // This is not an error.
5766 // If the user is a remote mnet user, parse the email text for URL to the
5767 // wwwroot and modify the url to direct the user's browser to login at their
5768 // home site (identity provider - idp) before hitting the link itself.
5769 if (is_mnet_remote_user($user)) {
5770 require_once($CFG->dirroot.'/mnet/lib.php');
5772 $jumpurl = mnet_get_idp_jump_url($user);
5773 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5775 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5776 $callback,
5777 $messagetext);
5778 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5779 $callback,
5780 $messagehtml);
5782 $mail = get_mailer();
5784 if (!empty($mail->SMTPDebug)) {
5785 echo '<pre>' . "\n";
5788 $temprecipients = array();
5789 $tempreplyto = array();
5791 // Make sure that we fall back onto some reasonable no-reply address.
5792 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
5793 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
5795 if (!validate_email($noreplyaddress)) {
5796 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
5797 $noreplyaddress = $noreplyaddressdefault;
5800 // Make up an email address for handling bounces.
5801 if (!empty($CFG->handlebounces)) {
5802 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5803 $mail->Sender = generate_email_processing_address(0, $modargs);
5804 } else {
5805 $mail->Sender = $noreplyaddress;
5808 // Make sure that the explicit replyto is valid, fall back to the implicit one.
5809 if (!empty($replyto) && !validate_email($replyto)) {
5810 debugging('email_to_user: Invalid replyto-email '.s($replyto));
5811 $replyto = $noreplyaddress;
5814 $alloweddomains = null;
5815 if (!empty($CFG->allowedemaildomains)) {
5816 $alloweddomains = explode(PHP_EOL, $CFG->allowedemaildomains);
5819 // Email will be sent using no reply address.
5820 if (empty($alloweddomains)) {
5821 $usetrueaddress = false;
5824 if (is_string($from)) { // So we can pass whatever we want if there is need.
5825 $mail->From = $noreplyaddress;
5826 $mail->FromName = $from;
5827 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
5828 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
5829 // in a course with the sender.
5830 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user, $alloweddomains)) {
5831 if (!validate_email($from->email)) {
5832 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
5833 // Better not to use $noreplyaddress in this case.
5834 return false;
5836 $mail->From = $from->email;
5837 $fromdetails = new stdClass();
5838 $fromdetails->name = fullname($from);
5839 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5840 $fromdetails->siteshortname = format_string($SITE->shortname);
5841 $fromstring = $fromdetails->name;
5842 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
5843 $fromstring = get_string('emailvia', 'core', $fromdetails);
5845 $mail->FromName = $fromstring;
5846 if (empty($replyto)) {
5847 $tempreplyto[] = array($from->email, fullname($from));
5849 } else {
5850 $mail->From = $noreplyaddress;
5851 $fromdetails = new stdClass();
5852 $fromdetails->name = fullname($from);
5853 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5854 $fromdetails->siteshortname = format_string($SITE->shortname);
5855 $fromstring = $fromdetails->name;
5856 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
5857 $fromstring = get_string('emailvia', 'core', $fromdetails);
5859 $mail->FromName = $fromstring;
5860 if (empty($replyto)) {
5861 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
5865 if (!empty($replyto)) {
5866 $tempreplyto[] = array($replyto, $replytoname);
5869 $temprecipients[] = array($user->email, fullname($user));
5871 // Set word wrap.
5872 $mail->WordWrap = $wordwrapwidth;
5874 if (!empty($from->customheaders)) {
5875 // Add custom headers.
5876 if (is_array($from->customheaders)) {
5877 foreach ($from->customheaders as $customheader) {
5878 $mail->addCustomHeader($customheader);
5880 } else {
5881 $mail->addCustomHeader($from->customheaders);
5885 // If the X-PHP-Originating-Script email header is on then also add an additional
5886 // header with details of where exactly in moodle the email was triggered from,
5887 // either a call to message_send() or to email_to_user().
5888 if (ini_get('mail.add_x_header')) {
5890 $stack = debug_backtrace(false);
5891 $origin = $stack[0];
5893 foreach ($stack as $depth => $call) {
5894 if ($call['function'] == 'message_send') {
5895 $origin = $call;
5899 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
5900 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
5901 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
5904 if (!empty($from->priority)) {
5905 $mail->Priority = $from->priority;
5908 $renderer = $PAGE->get_renderer('core');
5909 $context = array(
5910 'sitefullname' => $SITE->fullname,
5911 'siteshortname' => $SITE->shortname,
5912 'sitewwwroot' => $CFG->wwwroot,
5913 'subject' => $subject,
5914 'to' => $user->email,
5915 'toname' => fullname($user),
5916 'from' => $mail->From,
5917 'fromname' => $mail->FromName,
5919 if (!empty($tempreplyto[0])) {
5920 $context['replyto'] = $tempreplyto[0][0];
5921 $context['replytoname'] = $tempreplyto[0][1];
5923 if ($user->id > 0) {
5924 $context['touserid'] = $user->id;
5925 $context['tousername'] = $user->username;
5928 if (!empty($user->mailformat) && $user->mailformat == 1) {
5929 // Only process html templates if the user preferences allow html email.
5931 if ($messagehtml) {
5932 // If html has been given then pass it through the template.
5933 $context['body'] = $messagehtml;
5934 $messagehtml = $renderer->render_from_template('core/email_html', $context);
5936 } else {
5937 // If no html has been given, BUT there is an html wrapping template then
5938 // auto convert the text to html and then wrap it.
5939 $autohtml = trim(text_to_html($messagetext));
5940 $context['body'] = $autohtml;
5941 $temphtml = $renderer->render_from_template('core/email_html', $context);
5942 if ($autohtml != $temphtml) {
5943 $messagehtml = $temphtml;
5948 $context['body'] = $messagetext;
5949 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
5950 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
5951 $messagetext = $renderer->render_from_template('core/email_text', $context);
5953 // Autogenerate a MessageID if it's missing.
5954 if (empty($mail->MessageID)) {
5955 $mail->MessageID = generate_email_messageid();
5958 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5959 // Don't ever send HTML to users who don't want it.
5960 $mail->isHTML(true);
5961 $mail->Encoding = 'quoted-printable';
5962 $mail->Body = $messagehtml;
5963 $mail->AltBody = "\n$messagetext\n";
5964 } else {
5965 $mail->IsHTML(false);
5966 $mail->Body = "\n$messagetext\n";
5969 if ($attachment && $attachname) {
5970 if (preg_match( "~\\.\\.~" , $attachment )) {
5971 // Security check for ".." in dir path.
5972 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5973 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5974 } else {
5975 require_once($CFG->libdir.'/filelib.php');
5976 $mimetype = mimeinfo('type', $attachname);
5978 $attachmentpath = $attachment;
5980 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5981 $attachpath = str_replace('\\', '/', $attachmentpath);
5982 // Make sure both variables are normalised before comparing.
5983 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
5985 // If the attachment is a full path to a file in the tempdir, use it as is,
5986 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5987 if (strpos($attachpath, $temppath) !== 0) {
5988 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
5991 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5995 // Check if the email should be sent in an other charset then the default UTF-8.
5996 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5998 // Use the defined site mail charset or eventually the one preferred by the recipient.
5999 $charset = $CFG->sitemailcharset;
6000 if (!empty($CFG->allowusermailcharset)) {
6001 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6002 $charset = $useremailcharset;
6006 // Convert all the necessary strings if the charset is supported.
6007 $charsets = get_list_of_charsets();
6008 unset($charsets['UTF-8']);
6009 if (in_array($charset, $charsets)) {
6010 $mail->CharSet = $charset;
6011 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6012 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6013 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6014 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6016 foreach ($temprecipients as $key => $values) {
6017 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6019 foreach ($tempreplyto as $key => $values) {
6020 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6025 foreach ($temprecipients as $values) {
6026 $mail->addAddress($values[0], $values[1]);
6028 foreach ($tempreplyto as $values) {
6029 $mail->addReplyTo($values[0], $values[1]);
6032 if ($mail->send()) {
6033 set_send_count($user);
6034 if (!empty($mail->SMTPDebug)) {
6035 echo '</pre>';
6037 return true;
6038 } else {
6039 // Trigger event for failing to send email.
6040 $event = \core\event\email_failed::create(array(
6041 'context' => context_system::instance(),
6042 'userid' => $from->id,
6043 'relateduserid' => $user->id,
6044 'other' => array(
6045 'subject' => $subject,
6046 'message' => $messagetext,
6047 'errorinfo' => $mail->ErrorInfo
6050 $event->trigger();
6051 if (CLI_SCRIPT) {
6052 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6054 if (!empty($mail->SMTPDebug)) {
6055 echo '</pre>';
6057 return false;
6062 * Check to see if a user's real email address should be used for the "From" field.
6064 * @param object $from The user object for the user we are sending the email from.
6065 * @param object $user The user object that we are sending the email to.
6066 * @param array $alloweddomains An array of allowed domains that we can send email from.
6067 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6069 function can_send_from_real_email_address($from, $user, $alloweddomains) {
6070 // Email is in the list of allowed domains for sending email,
6071 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6072 // in a course with the sender.
6073 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6074 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6075 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6076 && enrol_get_shared_courses($user, $from, false, true)))) {
6077 return true;
6079 return false;
6083 * Generate a signoff for emails based on support settings
6085 * @return string
6087 function generate_email_signoff() {
6088 global $CFG;
6090 $signoff = "\n";
6091 if (!empty($CFG->supportname)) {
6092 $signoff .= $CFG->supportname."\n";
6094 if (!empty($CFG->supportemail)) {
6095 $signoff .= $CFG->supportemail."\n";
6097 if (!empty($CFG->supportpage)) {
6098 $signoff .= $CFG->supportpage."\n";
6100 return $signoff;
6104 * Sets specified user's password and send the new password to the user via email.
6106 * @param stdClass $user A {@link $USER} object
6107 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6108 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6110 function setnew_password_and_mail($user, $fasthash = false) {
6111 global $CFG, $DB;
6113 // We try to send the mail in language the user understands,
6114 // unfortunately the filter_string() does not support alternative langs yet
6115 // so multilang will not work properly for site->fullname.
6116 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6118 $site = get_site();
6120 $supportuser = core_user::get_support_user();
6122 $newpassword = generate_password();
6124 update_internal_user_password($user, $newpassword, $fasthash);
6126 $a = new stdClass();
6127 $a->firstname = fullname($user, true);
6128 $a->sitename = format_string($site->fullname);
6129 $a->username = $user->username;
6130 $a->newpassword = $newpassword;
6131 $a->link = $CFG->wwwroot .'/login/';
6132 $a->signoff = generate_email_signoff();
6134 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6136 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6138 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6139 return email_to_user($user, $supportuser, $subject, $message);
6144 * Resets specified user's password and send the new password to the user via email.
6146 * @param stdClass $user A {@link $USER} object
6147 * @return bool Returns true if mail was sent OK and false if there was an error.
6149 function reset_password_and_mail($user) {
6150 global $CFG;
6152 $site = get_site();
6153 $supportuser = core_user::get_support_user();
6155 $userauth = get_auth_plugin($user->auth);
6156 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6157 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6158 return false;
6161 $newpassword = generate_password();
6163 if (!$userauth->user_update_password($user, $newpassword)) {
6164 print_error("cannotsetpassword");
6167 $a = new stdClass();
6168 $a->firstname = $user->firstname;
6169 $a->lastname = $user->lastname;
6170 $a->sitename = format_string($site->fullname);
6171 $a->username = $user->username;
6172 $a->newpassword = $newpassword;
6173 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
6174 $a->signoff = generate_email_signoff();
6176 $message = get_string('newpasswordtext', '', $a);
6178 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6180 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6182 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6183 return email_to_user($user, $supportuser, $subject, $message);
6187 * Send email to specified user with confirmation text and activation link.
6189 * @param stdClass $user A {@link $USER} object
6190 * @param string $confirmationurl user confirmation URL
6191 * @return bool Returns true if mail was sent OK and false if there was an error.
6193 function send_confirmation_email($user, $confirmationurl = null) {
6194 global $CFG;
6196 $site = get_site();
6197 $supportuser = core_user::get_support_user();
6199 $data = new stdClass();
6200 $data->firstname = fullname($user);
6201 $data->sitename = format_string($site->fullname);
6202 $data->admin = generate_email_signoff();
6204 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6206 if (empty($confirmationurl)) {
6207 $confirmationurl = '/login/confirm.php';
6210 $confirmationurl = new moodle_url($confirmationurl);
6211 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6212 $confirmationurl->remove_params('data');
6213 $confirmationpath = $confirmationurl->out(false);
6215 // We need to custom encode the username to include trailing dots in the link.
6216 // Because of this custom encoding we can't use moodle_url directly.
6217 // Determine if a query string is present in the confirmation url.
6218 $hasquerystring = strpos($confirmationpath, '?') !== false;
6219 // Perform normal url encoding of the username first.
6220 $username = urlencode($user->username);
6221 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6222 $username = str_replace('.', '%2E', $username);
6224 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6226 $message = get_string('emailconfirmation', '', $data);
6227 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6229 $user->mailformat = 1; // Always send HTML version as well.
6231 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6232 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6236 * Sends a password change confirmation email.
6238 * @param stdClass $user A {@link $USER} object
6239 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6240 * @return bool Returns true if mail was sent OK and false if there was an error.
6242 function send_password_change_confirmation_email($user, $resetrecord) {
6243 global $CFG;
6245 $site = get_site();
6246 $supportuser = core_user::get_support_user();
6247 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6249 $data = new stdClass();
6250 $data->firstname = $user->firstname;
6251 $data->lastname = $user->lastname;
6252 $data->username = $user->username;
6253 $data->sitename = format_string($site->fullname);
6254 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6255 $data->admin = generate_email_signoff();
6256 $data->resetminutes = $pwresetmins;
6258 $message = get_string('emailresetconfirmation', '', $data);
6259 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6261 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6262 return email_to_user($user, $supportuser, $subject, $message);
6267 * Sends an email containinginformation on how to change your password.
6269 * @param stdClass $user A {@link $USER} object
6270 * @return bool Returns true if mail was sent OK and false if there was an error.
6272 function send_password_change_info($user) {
6273 global $CFG;
6275 $site = get_site();
6276 $supportuser = core_user::get_support_user();
6277 $systemcontext = context_system::instance();
6279 $data = new stdClass();
6280 $data->firstname = $user->firstname;
6281 $data->lastname = $user->lastname;
6282 $data->sitename = format_string($site->fullname);
6283 $data->admin = generate_email_signoff();
6285 $userauth = get_auth_plugin($user->auth);
6287 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6288 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6289 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6290 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6291 return email_to_user($user, $supportuser, $subject, $message);
6294 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6295 // We have some external url for password changing.
6296 $data->link .= $userauth->change_password_url();
6298 } else {
6299 // No way to change password, sorry.
6300 $data->link = '';
6303 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6304 $message = get_string('emailpasswordchangeinfo', '', $data);
6305 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6306 } else {
6307 $message = get_string('emailpasswordchangeinfofail', '', $data);
6308 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6311 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6312 return email_to_user($user, $supportuser, $subject, $message);
6317 * Check that an email is allowed. It returns an error message if there was a problem.
6319 * @param string $email Content of email
6320 * @return string|false
6322 function email_is_not_allowed($email) {
6323 global $CFG;
6325 if (!empty($CFG->allowemailaddresses)) {
6326 $allowed = explode(' ', $CFG->allowemailaddresses);
6327 foreach ($allowed as $allowedpattern) {
6328 $allowedpattern = trim($allowedpattern);
6329 if (!$allowedpattern) {
6330 continue;
6332 if (strpos($allowedpattern, '.') === 0) {
6333 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6334 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6335 return false;
6338 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6339 return false;
6342 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6344 } else if (!empty($CFG->denyemailaddresses)) {
6345 $denied = explode(' ', $CFG->denyemailaddresses);
6346 foreach ($denied as $deniedpattern) {
6347 $deniedpattern = trim($deniedpattern);
6348 if (!$deniedpattern) {
6349 continue;
6351 if (strpos($deniedpattern, '.') === 0) {
6352 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6353 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6354 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6357 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6358 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6363 return false;
6366 // FILE HANDLING.
6369 * Returns local file storage instance
6371 * @return file_storage
6373 function get_file_storage($reset = false) {
6374 global $CFG;
6376 static $fs = null;
6378 if ($reset) {
6379 $fs = null;
6380 return;
6383 if ($fs) {
6384 return $fs;
6387 require_once("$CFG->libdir/filelib.php");
6389 $fs = new file_storage();
6391 return $fs;
6395 * Returns local file storage instance
6397 * @return file_browser
6399 function get_file_browser() {
6400 global $CFG;
6402 static $fb = null;
6404 if ($fb) {
6405 return $fb;
6408 require_once("$CFG->libdir/filelib.php");
6410 $fb = new file_browser();
6412 return $fb;
6416 * Returns file packer
6418 * @param string $mimetype default application/zip
6419 * @return file_packer
6421 function get_file_packer($mimetype='application/zip') {
6422 global $CFG;
6424 static $fp = array();
6426 if (isset($fp[$mimetype])) {
6427 return $fp[$mimetype];
6430 switch ($mimetype) {
6431 case 'application/zip':
6432 case 'application/vnd.moodle.profiling':
6433 $classname = 'zip_packer';
6434 break;
6436 case 'application/x-gzip' :
6437 $classname = 'tgz_packer';
6438 break;
6440 case 'application/vnd.moodle.backup':
6441 $classname = 'mbz_packer';
6442 break;
6444 default:
6445 return false;
6448 require_once("$CFG->libdir/filestorage/$classname.php");
6449 $fp[$mimetype] = new $classname();
6451 return $fp[$mimetype];
6455 * Returns current name of file on disk if it exists.
6457 * @param string $newfile File to be verified
6458 * @return string Current name of file on disk if true
6460 function valid_uploaded_file($newfile) {
6461 if (empty($newfile)) {
6462 return '';
6464 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6465 return $newfile['tmp_name'];
6466 } else {
6467 return '';
6472 * Returns the maximum size for uploading files.
6474 * There are seven possible upload limits:
6475 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6476 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6477 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6478 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6479 * 5. by the Moodle admin in $CFG->maxbytes
6480 * 6. by the teacher in the current course $course->maxbytes
6481 * 7. by the teacher for the current module, eg $assignment->maxbytes
6483 * These last two are passed to this function as arguments (in bytes).
6484 * Anything defined as 0 is ignored.
6485 * The smallest of all the non-zero numbers is returned.
6487 * @todo Finish documenting this function
6489 * @param int $sitebytes Set maximum size
6490 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6491 * @param int $modulebytes Current module ->maxbytes (in bytes)
6492 * @param bool $unused This parameter has been deprecated and is not used any more.
6493 * @return int The maximum size for uploading files.
6495 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6497 if (! $filesize = ini_get('upload_max_filesize')) {
6498 $filesize = '5M';
6500 $minimumsize = get_real_size($filesize);
6502 if ($postsize = ini_get('post_max_size')) {
6503 $postsize = get_real_size($postsize);
6504 if ($postsize < $minimumsize) {
6505 $minimumsize = $postsize;
6509 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6510 $minimumsize = $sitebytes;
6513 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6514 $minimumsize = $coursebytes;
6517 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6518 $minimumsize = $modulebytes;
6521 return $minimumsize;
6525 * Returns the maximum size for uploading files for the current user
6527 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6529 * @param context $context The context in which to check user capabilities
6530 * @param int $sitebytes Set maximum size
6531 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6532 * @param int $modulebytes Current module ->maxbytes (in bytes)
6533 * @param stdClass $user The user
6534 * @param bool $unused This parameter has been deprecated and is not used any more.
6535 * @return int The maximum size for uploading files.
6537 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6538 $unused = false) {
6539 global $USER;
6541 if (empty($user)) {
6542 $user = $USER;
6545 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6546 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6549 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6553 * Returns an array of possible sizes in local language
6555 * Related to {@link get_max_upload_file_size()} - this function returns an
6556 * array of possible sizes in an array, translated to the
6557 * local language.
6559 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6561 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6562 * with the value set to 0. This option will be the first in the list.
6564 * @uses SORT_NUMERIC
6565 * @param int $sitebytes Set maximum size
6566 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6567 * @param int $modulebytes Current module ->maxbytes (in bytes)
6568 * @param int|array $custombytes custom upload size/s which will be added to list,
6569 * Only value/s smaller then maxsize will be added to list.
6570 * @return array
6572 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6573 global $CFG;
6575 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6576 return array();
6579 if ($sitebytes == 0) {
6580 // Will get the minimum of upload_max_filesize or post_max_size.
6581 $sitebytes = get_max_upload_file_size();
6584 $filesize = array();
6585 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6586 5242880, 10485760, 20971520, 52428800, 104857600,
6587 262144000, 524288000, 786432000, 1073741824,
6588 2147483648, 4294967296, 8589934592);
6590 // If custombytes is given and is valid then add it to the list.
6591 if (is_number($custombytes) and $custombytes > 0) {
6592 $custombytes = (int)$custombytes;
6593 if (!in_array($custombytes, $sizelist)) {
6594 $sizelist[] = $custombytes;
6596 } else if (is_array($custombytes)) {
6597 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6600 // Allow maxbytes to be selected if it falls outside the above boundaries.
6601 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6602 // Note: get_real_size() is used in order to prevent problems with invalid values.
6603 $sizelist[] = get_real_size($CFG->maxbytes);
6606 foreach ($sizelist as $sizebytes) {
6607 if ($sizebytes < $maxsize && $sizebytes > 0) {
6608 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6612 $limitlevel = '';
6613 $displaysize = '';
6614 if ($modulebytes &&
6615 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6616 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6617 $limitlevel = get_string('activity', 'core');
6618 $displaysize = display_size($modulebytes);
6619 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6621 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6622 $limitlevel = get_string('course', 'core');
6623 $displaysize = display_size($coursebytes);
6624 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6626 } else if ($sitebytes) {
6627 $limitlevel = get_string('site', 'core');
6628 $displaysize = display_size($sitebytes);
6629 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6632 krsort($filesize, SORT_NUMERIC);
6633 if ($limitlevel) {
6634 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6635 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6638 return $filesize;
6642 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6644 * If excludefiles is defined, then that file/directory is ignored
6645 * If getdirs is true, then (sub)directories are included in the output
6646 * If getfiles is true, then files are included in the output
6647 * (at least one of these must be true!)
6649 * @todo Finish documenting this function. Add examples of $excludefile usage.
6651 * @param string $rootdir A given root directory to start from
6652 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6653 * @param bool $descend If true then subdirectories are recursed as well
6654 * @param bool $getdirs If true then (sub)directories are included in the output
6655 * @param bool $getfiles If true then files are included in the output
6656 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6658 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6660 $dirs = array();
6662 if (!$getdirs and !$getfiles) { // Nothing to show.
6663 return $dirs;
6666 if (!is_dir($rootdir)) { // Must be a directory.
6667 return $dirs;
6670 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6671 return $dirs;
6674 if (!is_array($excludefiles)) {
6675 $excludefiles = array($excludefiles);
6678 while (false !== ($file = readdir($dir))) {
6679 $firstchar = substr($file, 0, 1);
6680 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6681 continue;
6683 $fullfile = $rootdir .'/'. $file;
6684 if (filetype($fullfile) == 'dir') {
6685 if ($getdirs) {
6686 $dirs[] = $file;
6688 if ($descend) {
6689 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6690 foreach ($subdirs as $subdir) {
6691 $dirs[] = $file .'/'. $subdir;
6694 } else if ($getfiles) {
6695 $dirs[] = $file;
6698 closedir($dir);
6700 asort($dirs);
6702 return $dirs;
6707 * Adds up all the files in a directory and works out the size.
6709 * @param string $rootdir The directory to start from
6710 * @param string $excludefile A file to exclude when summing directory size
6711 * @return int The summed size of all files and subfiles within the root directory
6713 function get_directory_size($rootdir, $excludefile='') {
6714 global $CFG;
6716 // Do it this way if we can, it's much faster.
6717 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6718 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6719 $output = null;
6720 $return = null;
6721 exec($command, $output, $return);
6722 if (is_array($output)) {
6723 // We told it to return k.
6724 return get_real_size(intval($output[0]).'k');
6728 if (!is_dir($rootdir)) {
6729 // Must be a directory.
6730 return 0;
6733 if (!$dir = @opendir($rootdir)) {
6734 // Can't open it for some reason.
6735 return 0;
6738 $size = 0;
6740 while (false !== ($file = readdir($dir))) {
6741 $firstchar = substr($file, 0, 1);
6742 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6743 continue;
6745 $fullfile = $rootdir .'/'. $file;
6746 if (filetype($fullfile) == 'dir') {
6747 $size += get_directory_size($fullfile, $excludefile);
6748 } else {
6749 $size += filesize($fullfile);
6752 closedir($dir);
6754 return $size;
6758 * Converts bytes into display form
6760 * @static string $gb Localized string for size in gigabytes
6761 * @static string $mb Localized string for size in megabytes
6762 * @static string $kb Localized string for size in kilobytes
6763 * @static string $b Localized string for size in bytes
6764 * @param int $size The size to convert to human readable form
6765 * @return string
6767 function display_size($size) {
6769 static $gb, $mb, $kb, $b;
6771 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6772 return get_string('unlimited');
6775 if (empty($gb)) {
6776 $gb = get_string('sizegb');
6777 $mb = get_string('sizemb');
6778 $kb = get_string('sizekb');
6779 $b = get_string('sizeb');
6782 if ($size >= 1073741824) {
6783 $size = round($size / 1073741824 * 10) / 10 . $gb;
6784 } else if ($size >= 1048576) {
6785 $size = round($size / 1048576 * 10) / 10 . $mb;
6786 } else if ($size >= 1024) {
6787 $size = round($size / 1024 * 10) / 10 . $kb;
6788 } else {
6789 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6791 return $size;
6795 * Cleans a given filename by removing suspicious or troublesome characters
6797 * @see clean_param()
6798 * @param string $string file name
6799 * @return string cleaned file name
6801 function clean_filename($string) {
6802 return clean_param($string, PARAM_FILE);
6806 // STRING TRANSLATION.
6809 * Returns the code for the current language
6811 * @category string
6812 * @return string
6814 function current_language() {
6815 global $CFG, $USER, $SESSION, $COURSE;
6817 if (!empty($SESSION->forcelang)) {
6818 // Allows overriding course-forced language (useful for admins to check
6819 // issues in courses whose language they don't understand).
6820 // Also used by some code to temporarily get language-related information in a
6821 // specific language (see force_current_language()).
6822 $return = $SESSION->forcelang;
6824 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6825 // Course language can override all other settings for this page.
6826 $return = $COURSE->lang;
6828 } else if (!empty($SESSION->lang)) {
6829 // Session language can override other settings.
6830 $return = $SESSION->lang;
6832 } else if (!empty($USER->lang)) {
6833 $return = $USER->lang;
6835 } else if (isset($CFG->lang)) {
6836 $return = $CFG->lang;
6838 } else {
6839 $return = 'en';
6842 // Just in case this slipped in from somewhere by accident.
6843 $return = str_replace('_utf8', '', $return);
6845 return $return;
6849 * Returns parent language of current active language if defined
6851 * @category string
6852 * @param string $lang null means current language
6853 * @return string
6855 function get_parent_language($lang=null) {
6857 // Let's hack around the current language.
6858 if (!empty($lang)) {
6859 $oldforcelang = force_current_language($lang);
6862 $parentlang = get_string('parentlanguage', 'langconfig');
6863 if ($parentlang === 'en') {
6864 $parentlang = '';
6867 // Let's hack around the current language.
6868 if (!empty($lang)) {
6869 force_current_language($oldforcelang);
6872 return $parentlang;
6876 * Force the current language to get strings and dates localised in the given language.
6878 * After calling this function, all strings will be provided in the given language
6879 * until this function is called again, or equivalent code is run.
6881 * @param string $language
6882 * @return string previous $SESSION->forcelang value
6884 function force_current_language($language) {
6885 global $SESSION;
6886 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6887 if ($language !== $sessionforcelang) {
6888 // Seting forcelang to null or an empty string disables it's effect.
6889 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6890 $SESSION->forcelang = $language;
6891 moodle_setlocale();
6894 return $sessionforcelang;
6898 * Returns current string_manager instance.
6900 * The param $forcereload is needed for CLI installer only where the string_manager instance
6901 * must be replaced during the install.php script life time.
6903 * @category string
6904 * @param bool $forcereload shall the singleton be released and new instance created instead?
6905 * @return core_string_manager
6907 function get_string_manager($forcereload=false) {
6908 global $CFG;
6910 static $singleton = null;
6912 if ($forcereload) {
6913 $singleton = null;
6915 if ($singleton === null) {
6916 if (empty($CFG->early_install_lang)) {
6918 if (empty($CFG->langlist)) {
6919 $translist = array();
6920 } else {
6921 $translist = explode(',', $CFG->langlist);
6924 if (!empty($CFG->config_php_settings['customstringmanager'])) {
6925 $classname = $CFG->config_php_settings['customstringmanager'];
6927 if (class_exists($classname)) {
6928 $implements = class_implements($classname);
6930 if (isset($implements['core_string_manager'])) {
6931 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist);
6932 return $singleton;
6934 } else {
6935 debugging('Unable to instantiate custom string manager: class '.$classname.
6936 ' does not implement the core_string_manager interface.');
6939 } else {
6940 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
6944 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6946 } else {
6947 $singleton = new core_string_manager_install();
6951 return $singleton;
6955 * Returns a localized string.
6957 * Returns the translated string specified by $identifier as
6958 * for $module. Uses the same format files as STphp.
6959 * $a is an object, string or number that can be used
6960 * within translation strings
6962 * eg 'hello {$a->firstname} {$a->lastname}'
6963 * or 'hello {$a}'
6965 * If you would like to directly echo the localized string use
6966 * the function {@link print_string()}
6968 * Example usage of this function involves finding the string you would
6969 * like a local equivalent of and using its identifier and module information
6970 * to retrieve it.<br/>
6971 * If you open moodle/lang/en/moodle.php and look near line 278
6972 * you will find a string to prompt a user for their word for 'course'
6973 * <code>
6974 * $string['course'] = 'Course';
6975 * </code>
6976 * So if you want to display the string 'Course'
6977 * in any language that supports it on your site
6978 * you just need to use the identifier 'course'
6979 * <code>
6980 * $mystring = '<strong>'. get_string('course') .'</strong>';
6981 * or
6982 * </code>
6983 * If the string you want is in another file you'd take a slightly
6984 * different approach. Looking in moodle/lang/en/calendar.php you find
6985 * around line 75:
6986 * <code>
6987 * $string['typecourse'] = 'Course event';
6988 * </code>
6989 * If you want to display the string "Course event" in any language
6990 * supported you would use the identifier 'typecourse' and the module 'calendar'
6991 * (because it is in the file calendar.php):
6992 * <code>
6993 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6994 * </code>
6996 * As a last resort, should the identifier fail to map to a string
6997 * the returned string will be [[ $identifier ]]
6999 * In Moodle 2.3 there is a new argument to this function $lazyload.
7000 * Setting $lazyload to true causes get_string to return a lang_string object
7001 * rather than the string itself. The fetching of the string is then put off until
7002 * the string object is first used. The object can be used by calling it's out
7003 * method or by casting the object to a string, either directly e.g.
7004 * (string)$stringobject
7005 * or indirectly by using the string within another string or echoing it out e.g.
7006 * echo $stringobject
7007 * return "<p>{$stringobject}</p>";
7008 * It is worth noting that using $lazyload and attempting to use the string as an
7009 * array key will cause a fatal error as objects cannot be used as array keys.
7010 * But you should never do that anyway!
7011 * For more information {@link lang_string}
7013 * @category string
7014 * @param string $identifier The key identifier for the localized string
7015 * @param string $component The module where the key identifier is stored,
7016 * usually expressed as the filename in the language pack without the
7017 * .php on the end but can also be written as mod/forum or grade/export/xls.
7018 * If none is specified then moodle.php is used.
7019 * @param string|object|array $a An object, string or number that can be used
7020 * within translation strings
7021 * @param bool $lazyload If set to true a string object is returned instead of
7022 * the string itself. The string then isn't calculated until it is first used.
7023 * @return string The localized string.
7024 * @throws coding_exception
7026 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7027 global $CFG;
7029 // If the lazy load argument has been supplied return a lang_string object
7030 // instead.
7031 // We need to make sure it is true (and a bool) as you will see below there
7032 // used to be a forth argument at one point.
7033 if ($lazyload === true) {
7034 return new lang_string($identifier, $component, $a);
7037 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7038 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7041 // There is now a forth argument again, this time it is a boolean however so
7042 // we can still check for the old extralocations parameter.
7043 if (!is_bool($lazyload) && !empty($lazyload)) {
7044 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7047 if (strpos($component, '/') !== false) {
7048 debugging('The module name you passed to get_string is the deprecated format ' .
7049 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7050 $componentpath = explode('/', $component);
7052 switch ($componentpath[0]) {
7053 case 'mod':
7054 $component = $componentpath[1];
7055 break;
7056 case 'blocks':
7057 case 'block':
7058 $component = 'block_'.$componentpath[1];
7059 break;
7060 case 'enrol':
7061 $component = 'enrol_'.$componentpath[1];
7062 break;
7063 case 'format':
7064 $component = 'format_'.$componentpath[1];
7065 break;
7066 case 'grade':
7067 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7068 break;
7072 $result = get_string_manager()->get_string($identifier, $component, $a);
7074 // Debugging feature lets you display string identifier and component.
7075 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7076 $result .= ' {' . $identifier . '/' . $component . '}';
7078 return $result;
7082 * Converts an array of strings to their localized value.
7084 * @param array $array An array of strings
7085 * @param string $component The language module that these strings can be found in.
7086 * @return stdClass translated strings.
7088 function get_strings($array, $component = '') {
7089 $string = new stdClass;
7090 foreach ($array as $item) {
7091 $string->$item = get_string($item, $component);
7093 return $string;
7097 * Prints out a translated string.
7099 * Prints out a translated string using the return value from the {@link get_string()} function.
7101 * Example usage of this function when the string is in the moodle.php file:<br/>
7102 * <code>
7103 * echo '<strong>';
7104 * print_string('course');
7105 * echo '</strong>';
7106 * </code>
7108 * Example usage of this function when the string is not in the moodle.php file:<br/>
7109 * <code>
7110 * echo '<h1>';
7111 * print_string('typecourse', 'calendar');
7112 * echo '</h1>';
7113 * </code>
7115 * @category string
7116 * @param string $identifier The key identifier for the localized string
7117 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7118 * @param string|object|array $a An object, string or number that can be used within translation strings
7120 function print_string($identifier, $component = '', $a = null) {
7121 echo get_string($identifier, $component, $a);
7125 * Returns a list of charset codes
7127 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7128 * (checking that such charset is supported by the texlib library!)
7130 * @return array And associative array with contents in the form of charset => charset
7132 function get_list_of_charsets() {
7134 $charsets = array(
7135 'EUC-JP' => 'EUC-JP',
7136 'ISO-2022-JP'=> 'ISO-2022-JP',
7137 'ISO-8859-1' => 'ISO-8859-1',
7138 'SHIFT-JIS' => 'SHIFT-JIS',
7139 'GB2312' => 'GB2312',
7140 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7141 'UTF-8' => 'UTF-8');
7143 asort($charsets);
7145 return $charsets;
7149 * Returns a list of valid and compatible themes
7151 * @return array
7153 function get_list_of_themes() {
7154 global $CFG;
7156 $themes = array();
7158 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7159 $themelist = explode(',', $CFG->themelist);
7160 } else {
7161 $themelist = array_keys(core_component::get_plugin_list("theme"));
7164 foreach ($themelist as $key => $themename) {
7165 $theme = theme_config::load($themename);
7166 $themes[$themename] = $theme;
7169 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7171 return $themes;
7175 * Factory function for emoticon_manager
7177 * @return emoticon_manager singleton
7179 function get_emoticon_manager() {
7180 static $singleton = null;
7182 if (is_null($singleton)) {
7183 $singleton = new emoticon_manager();
7186 return $singleton;
7190 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7192 * Whenever this manager mentiones 'emoticon object', the following data
7193 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7194 * altidentifier and altcomponent
7196 * @see admin_setting_emoticons
7198 * @copyright 2010 David Mudrak
7199 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7201 class emoticon_manager {
7204 * Returns the currently enabled emoticons
7206 * @return array of emoticon objects
7208 public function get_emoticons() {
7209 global $CFG;
7211 if (empty($CFG->emoticons)) {
7212 return array();
7215 $emoticons = $this->decode_stored_config($CFG->emoticons);
7217 if (!is_array($emoticons)) {
7218 // Something is wrong with the format of stored setting.
7219 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7220 return array();
7223 return $emoticons;
7227 * Converts emoticon object into renderable pix_emoticon object
7229 * @param stdClass $emoticon emoticon object
7230 * @param array $attributes explicit HTML attributes to set
7231 * @return pix_emoticon
7233 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7234 $stringmanager = get_string_manager();
7235 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7236 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7237 } else {
7238 $alt = s($emoticon->text);
7240 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7244 * Encodes the array of emoticon objects into a string storable in config table
7246 * @see self::decode_stored_config()
7247 * @param array $emoticons array of emtocion objects
7248 * @return string
7250 public function encode_stored_config(array $emoticons) {
7251 return json_encode($emoticons);
7255 * Decodes the string into an array of emoticon objects
7257 * @see self::encode_stored_config()
7258 * @param string $encoded
7259 * @return string|null
7261 public function decode_stored_config($encoded) {
7262 $decoded = json_decode($encoded);
7263 if (!is_array($decoded)) {
7264 return null;
7266 return $decoded;
7270 * Returns default set of emoticons supported by Moodle
7272 * @return array of sdtClasses
7274 public function default_emoticons() {
7275 return array(
7276 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7277 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7278 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7279 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7280 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7281 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7282 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7283 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7284 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7285 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7286 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7287 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7288 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7289 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7290 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7291 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7292 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7293 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7294 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7295 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7296 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7297 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7298 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7299 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7300 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7301 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7302 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7303 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7304 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7305 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7310 * Helper method preparing the stdClass with the emoticon properties
7312 * @param string|array $text or array of strings
7313 * @param string $imagename to be used by {@link pix_emoticon}
7314 * @param string $altidentifier alternative string identifier, null for no alt
7315 * @param string $altcomponent where the alternative string is defined
7316 * @param string $imagecomponent to be used by {@link pix_emoticon}
7317 * @return stdClass
7319 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7320 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7321 return (object)array(
7322 'text' => $text,
7323 'imagename' => $imagename,
7324 'imagecomponent' => $imagecomponent,
7325 'altidentifier' => $altidentifier,
7326 'altcomponent' => $altcomponent,
7331 // ENCRYPTION.
7334 * rc4encrypt
7336 * @param string $data Data to encrypt.
7337 * @return string The now encrypted data.
7339 function rc4encrypt($data) {
7340 return endecrypt(get_site_identifier(), $data, '');
7344 * rc4decrypt
7346 * @param string $data Data to decrypt.
7347 * @return string The now decrypted data.
7349 function rc4decrypt($data) {
7350 return endecrypt(get_site_identifier(), $data, 'de');
7354 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7356 * @todo Finish documenting this function
7358 * @param string $pwd The password to use when encrypting or decrypting
7359 * @param string $data The data to be decrypted/encrypted
7360 * @param string $case Either 'de' for decrypt or '' for encrypt
7361 * @return string
7363 function endecrypt ($pwd, $data, $case) {
7365 if ($case == 'de') {
7366 $data = urldecode($data);
7369 $key[] = '';
7370 $box[] = '';
7371 $pwdlength = strlen($pwd);
7373 for ($i = 0; $i <= 255; $i++) {
7374 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7375 $box[$i] = $i;
7378 $x = 0;
7380 for ($i = 0; $i <= 255; $i++) {
7381 $x = ($x + $box[$i] + $key[$i]) % 256;
7382 $tempswap = $box[$i];
7383 $box[$i] = $box[$x];
7384 $box[$x] = $tempswap;
7387 $cipher = '';
7389 $a = 0;
7390 $j = 0;
7392 for ($i = 0; $i < strlen($data); $i++) {
7393 $a = ($a + 1) % 256;
7394 $j = ($j + $box[$a]) % 256;
7395 $temp = $box[$a];
7396 $box[$a] = $box[$j];
7397 $box[$j] = $temp;
7398 $k = $box[(($box[$a] + $box[$j]) % 256)];
7399 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7400 $cipher .= chr($cipherby);
7403 if ($case == 'de') {
7404 $cipher = urldecode(urlencode($cipher));
7405 } else {
7406 $cipher = urlencode($cipher);
7409 return $cipher;
7412 // ENVIRONMENT CHECKING.
7415 * This method validates a plug name. It is much faster than calling clean_param.
7417 * @param string $name a string that might be a plugin name.
7418 * @return bool if this string is a valid plugin name.
7420 function is_valid_plugin_name($name) {
7421 // This does not work for 'mod', bad luck, use any other type.
7422 return core_component::is_valid_plugin_name('tool', $name);
7426 * Get a list of all the plugins of a given type that define a certain API function
7427 * in a certain file. The plugin component names and function names are returned.
7429 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7430 * @param string $function the part of the name of the function after the
7431 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7432 * names like report_courselist_hook.
7433 * @param string $file the name of file within the plugin that defines the
7434 * function. Defaults to lib.php.
7435 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7436 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7438 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7439 global $CFG;
7441 // We don't include here as all plugin types files would be included.
7442 $plugins = get_plugins_with_function($function, $file, false);
7444 if (empty($plugins[$plugintype])) {
7445 return array();
7448 $allplugins = core_component::get_plugin_list($plugintype);
7450 // Reformat the array and include the files.
7451 $pluginfunctions = array();
7452 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7454 // Check that it has not been removed and the file is still available.
7455 if (!empty($allplugins[$pluginname])) {
7457 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7458 if (file_exists($filepath)) {
7459 include_once($filepath);
7460 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7465 return $pluginfunctions;
7469 * Get a list of all the plugins that define a certain API function in a certain file.
7471 * @param string $function the part of the name of the function after the
7472 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7473 * names like report_courselist_hook.
7474 * @param string $file the name of file within the plugin that defines the
7475 * function. Defaults to lib.php.
7476 * @param bool $include Whether to include the files that contain the functions or not.
7477 * @return array with [plugintype][plugin] = functionname
7479 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7480 global $CFG;
7482 $cache = \cache::make('core', 'plugin_functions');
7484 // Including both although I doubt that we will find two functions definitions with the same name.
7485 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7486 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7488 if ($pluginfunctions = $cache->get($key)) {
7490 // Checking that the files are still available.
7491 foreach ($pluginfunctions as $plugintype => $plugins) {
7493 $allplugins = \core_component::get_plugin_list($plugintype);
7494 foreach ($plugins as $plugin => $fullpath) {
7496 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7497 if (empty($allplugins[$plugin])) {
7498 unset($pluginfunctions[$plugintype][$plugin]);
7499 continue;
7502 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7503 if ($include && $fileexists) {
7504 // Include the files if it was requested.
7505 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7506 } else if (!$fileexists) {
7507 // If the file is not available any more it should not be returned.
7508 unset($pluginfunctions[$plugintype][$plugin]);
7512 return $pluginfunctions;
7515 $pluginfunctions = array();
7517 // To fill the cached. Also, everything should continue working with cache disabled.
7518 $plugintypes = \core_component::get_plugin_types();
7519 foreach ($plugintypes as $plugintype => $unused) {
7521 // We need to include files here.
7522 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7523 foreach ($pluginswithfile as $plugin => $notused) {
7525 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7527 $pluginfunction = false;
7528 if (function_exists($fullfunction)) {
7529 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7530 $pluginfunction = $fullfunction;
7532 } else if ($plugintype === 'mod') {
7533 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7534 $shortfunction = $plugin . '_' . $function;
7535 if (function_exists($shortfunction)) {
7536 $pluginfunction = $shortfunction;
7540 if ($pluginfunction) {
7541 if (empty($pluginfunctions[$plugintype])) {
7542 $pluginfunctions[$plugintype] = array();
7544 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7549 $cache->set($key, $pluginfunctions);
7551 return $pluginfunctions;
7556 * Lists plugin-like directories within specified directory
7558 * This function was originally used for standard Moodle plugins, please use
7559 * new core_component::get_plugin_list() now.
7561 * This function is used for general directory listing and backwards compatility.
7563 * @param string $directory relative directory from root
7564 * @param string $exclude dir name to exclude from the list (defaults to none)
7565 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7566 * @return array Sorted array of directory names found under the requested parameters
7568 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7569 global $CFG;
7571 $plugins = array();
7573 if (empty($basedir)) {
7574 $basedir = $CFG->dirroot .'/'. $directory;
7576 } else {
7577 $basedir = $basedir .'/'. $directory;
7580 if ($CFG->debugdeveloper and empty($exclude)) {
7581 // Make sure devs do not use this to list normal plugins,
7582 // this is intended for general directories that are not plugins!
7584 $subtypes = core_component::get_plugin_types();
7585 if (in_array($basedir, $subtypes)) {
7586 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7588 unset($subtypes);
7591 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7592 if (!$dirhandle = opendir($basedir)) {
7593 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7594 return array();
7596 while (false !== ($dir = readdir($dirhandle))) {
7597 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7598 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7599 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7600 continue;
7602 if (filetype($basedir .'/'. $dir) != 'dir') {
7603 continue;
7605 $plugins[] = $dir;
7607 closedir($dirhandle);
7609 if ($plugins) {
7610 asort($plugins);
7612 return $plugins;
7616 * Invoke plugin's callback functions
7618 * @param string $type plugin type e.g. 'mod'
7619 * @param string $name plugin name
7620 * @param string $feature feature name
7621 * @param string $action feature's action
7622 * @param array $params parameters of callback function, should be an array
7623 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7624 * @return mixed
7626 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7628 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7629 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7633 * Invoke component's callback functions
7635 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7636 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7637 * @param array $params parameters of callback function
7638 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7639 * @return mixed
7641 function component_callback($component, $function, array $params = array(), $default = null) {
7643 $functionname = component_callback_exists($component, $function);
7645 if ($functionname) {
7646 // Function exists, so just return function result.
7647 $ret = call_user_func_array($functionname, $params);
7648 if (is_null($ret)) {
7649 return $default;
7650 } else {
7651 return $ret;
7654 return $default;
7658 * Determine if a component callback exists and return the function name to call. Note that this
7659 * function will include the required library files so that the functioname returned can be
7660 * called directly.
7662 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7663 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7664 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7665 * @throws coding_exception if invalid component specfied
7667 function component_callback_exists($component, $function) {
7668 global $CFG; // This is needed for the inclusions.
7670 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7671 if (empty($cleancomponent)) {
7672 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7674 $component = $cleancomponent;
7676 list($type, $name) = core_component::normalize_component($component);
7677 $component = $type . '_' . $name;
7679 $oldfunction = $name.'_'.$function;
7680 $function = $component.'_'.$function;
7682 $dir = core_component::get_component_directory($component);
7683 if (empty($dir)) {
7684 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7687 // Load library and look for function.
7688 if (file_exists($dir.'/lib.php')) {
7689 require_once($dir.'/lib.php');
7692 if (!function_exists($function) and function_exists($oldfunction)) {
7693 if ($type !== 'mod' and $type !== 'core') {
7694 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7696 $function = $oldfunction;
7699 if (function_exists($function)) {
7700 return $function;
7702 return false;
7706 * Checks whether a plugin supports a specified feature.
7708 * @param string $type Plugin type e.g. 'mod'
7709 * @param string $name Plugin name e.g. 'forum'
7710 * @param string $feature Feature code (FEATURE_xx constant)
7711 * @param mixed $default default value if feature support unknown
7712 * @return mixed Feature result (false if not supported, null if feature is unknown,
7713 * otherwise usually true but may have other feature-specific value such as array)
7714 * @throws coding_exception
7716 function plugin_supports($type, $name, $feature, $default = null) {
7717 global $CFG;
7719 if ($type === 'mod' and $name === 'NEWMODULE') {
7720 // Somebody forgot to rename the module template.
7721 return false;
7724 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7725 if (empty($component)) {
7726 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7729 $function = null;
7731 if ($type === 'mod') {
7732 // We need this special case because we support subplugins in modules,
7733 // otherwise it would end up in infinite loop.
7734 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7735 include_once("$CFG->dirroot/mod/$name/lib.php");
7736 $function = $component.'_supports';
7737 if (!function_exists($function)) {
7738 // Legacy non-frankenstyle function name.
7739 $function = $name.'_supports';
7743 } else {
7744 if (!$path = core_component::get_plugin_directory($type, $name)) {
7745 // Non existent plugin type.
7746 return false;
7748 if (file_exists("$path/lib.php")) {
7749 include_once("$path/lib.php");
7750 $function = $component.'_supports';
7754 if ($function and function_exists($function)) {
7755 $supports = $function($feature);
7756 if (is_null($supports)) {
7757 // Plugin does not know - use default.
7758 return $default;
7759 } else {
7760 return $supports;
7764 // Plugin does not care, so use default.
7765 return $default;
7769 * Returns true if the current version of PHP is greater that the specified one.
7771 * @todo Check PHP version being required here is it too low?
7773 * @param string $version The version of php being tested.
7774 * @return bool
7776 function check_php_version($version='5.2.4') {
7777 return (version_compare(phpversion(), $version) >= 0);
7781 * Determine if moodle installation requires update.
7783 * Checks version numbers of main code and all plugins to see
7784 * if there are any mismatches.
7786 * @return bool
7788 function moodle_needs_upgrading() {
7789 global $CFG;
7791 if (empty($CFG->version)) {
7792 return true;
7795 // There is no need to purge plugininfo caches here because
7796 // these caches are not used during upgrade and they are purged after
7797 // every upgrade.
7799 if (empty($CFG->allversionshash)) {
7800 return true;
7803 $hash = core_component::get_all_versions_hash();
7805 return ($hash !== $CFG->allversionshash);
7809 * Returns the major version of this site
7811 * Moodle version numbers consist of three numbers separated by a dot, for
7812 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7813 * called major version. This function extracts the major version from either
7814 * $CFG->release (default) or eventually from the $release variable defined in
7815 * the main version.php.
7817 * @param bool $fromdisk should the version if source code files be used
7818 * @return string|false the major version like '2.3', false if could not be determined
7820 function moodle_major_version($fromdisk = false) {
7821 global $CFG;
7823 if ($fromdisk) {
7824 $release = null;
7825 require($CFG->dirroot.'/version.php');
7826 if (empty($release)) {
7827 return false;
7830 } else {
7831 if (empty($CFG->release)) {
7832 return false;
7834 $release = $CFG->release;
7837 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7838 return $matches[0];
7839 } else {
7840 return false;
7844 // MISCELLANEOUS.
7847 * Sets the system locale
7849 * @category string
7850 * @param string $locale Can be used to force a locale
7852 function moodle_setlocale($locale='') {
7853 global $CFG;
7855 static $currentlocale = ''; // Last locale caching.
7857 $oldlocale = $currentlocale;
7859 // Fetch the correct locale based on ostype.
7860 if ($CFG->ostype == 'WINDOWS') {
7861 $stringtofetch = 'localewin';
7862 } else {
7863 $stringtofetch = 'locale';
7866 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7867 if (!empty($locale)) {
7868 $currentlocale = $locale;
7869 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7870 $currentlocale = $CFG->locale;
7871 } else {
7872 $currentlocale = get_string($stringtofetch, 'langconfig');
7875 // Do nothing if locale already set up.
7876 if ($oldlocale == $currentlocale) {
7877 return;
7880 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7881 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7882 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7884 // Get current values.
7885 $monetary= setlocale (LC_MONETARY, 0);
7886 $numeric = setlocale (LC_NUMERIC, 0);
7887 $ctype = setlocale (LC_CTYPE, 0);
7888 if ($CFG->ostype != 'WINDOWS') {
7889 $messages= setlocale (LC_MESSAGES, 0);
7891 // Set locale to all.
7892 $result = setlocale (LC_ALL, $currentlocale);
7893 // If setting of locale fails try the other utf8 or utf-8 variant,
7894 // some operating systems support both (Debian), others just one (OSX).
7895 if ($result === false) {
7896 if (stripos($currentlocale, '.UTF-8') !== false) {
7897 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7898 setlocale (LC_ALL, $newlocale);
7899 } else if (stripos($currentlocale, '.UTF8') !== false) {
7900 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7901 setlocale (LC_ALL, $newlocale);
7904 // Set old values.
7905 setlocale (LC_MONETARY, $monetary);
7906 setlocale (LC_NUMERIC, $numeric);
7907 if ($CFG->ostype != 'WINDOWS') {
7908 setlocale (LC_MESSAGES, $messages);
7910 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7911 // To workaround a well-known PHP problem with Turkish letter Ii.
7912 setlocale (LC_CTYPE, $ctype);
7917 * Count words in a string.
7919 * Words are defined as things between whitespace.
7921 * @category string
7922 * @param string $string The text to be searched for words.
7923 * @return int The count of words in the specified string
7925 function count_words($string) {
7926 $string = strip_tags($string);
7927 // Decode HTML entities.
7928 $string = html_entity_decode($string);
7929 // Replace underscores (which are classed as word characters) with spaces.
7930 $string = preg_replace('/_/u', ' ', $string);
7931 // Remove any characters that shouldn't be treated as word boundaries.
7932 $string = preg_replace('/[\'"’-]/u', '', $string);
7933 // Remove dots and commas from within numbers only.
7934 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7936 return count(preg_split('/\w\b/u', $string)) - 1;
7940 * Count letters in a string.
7942 * Letters are defined as chars not in tags and different from whitespace.
7944 * @category string
7945 * @param string $string The text to be searched for letters.
7946 * @return int The count of letters in the specified text.
7948 function count_letters($string) {
7949 $string = strip_tags($string); // Tags are out now.
7950 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7952 return core_text::strlen($string);
7956 * Generate and return a random string of the specified length.
7958 * @param int $length The length of the string to be created.
7959 * @return string
7961 function random_string($length=15) {
7962 $randombytes = random_bytes_emulate($length);
7963 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7964 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7965 $pool .= '0123456789';
7966 $poollen = strlen($pool);
7967 $string = '';
7968 for ($i = 0; $i < $length; $i++) {
7969 $rand = ord($randombytes[$i]);
7970 $string .= substr($pool, ($rand%($poollen)), 1);
7972 return $string;
7976 * Generate a complex random string (useful for md5 salts)
7978 * This function is based on the above {@link random_string()} however it uses a
7979 * larger pool of characters and generates a string between 24 and 32 characters
7981 * @param int $length Optional if set generates a string to exactly this length
7982 * @return string
7984 function complex_random_string($length=null) {
7985 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7986 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7987 $poollen = strlen($pool);
7988 if ($length===null) {
7989 $length = floor(rand(24, 32));
7991 $randombytes = random_bytes_emulate($length);
7992 $string = '';
7993 for ($i = 0; $i < $length; $i++) {
7994 $rand = ord($randombytes[$i]);
7995 $string .= $pool[($rand%$poollen)];
7997 return $string;
8001 * Try to generates cryptographically secure pseudo-random bytes.
8003 * Note this is achieved by fallbacking between:
8004 * - PHP 7 random_bytes().
8005 * - OpenSSL openssl_random_pseudo_bytes().
8006 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8008 * @param int $length requested length in bytes
8009 * @return string binary data
8011 function random_bytes_emulate($length) {
8012 global $CFG;
8013 if ($length <= 0) {
8014 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8015 return '';
8017 if (function_exists('random_bytes')) {
8018 // Use PHP 7 goodness.
8019 $hash = @random_bytes($length);
8020 if ($hash !== false) {
8021 return $hash;
8024 if (function_exists('openssl_random_pseudo_bytes')) {
8025 // If you have the openssl extension enabled.
8026 $hash = openssl_random_pseudo_bytes($length);
8027 if ($hash !== false) {
8028 return $hash;
8032 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8033 $staticdata = serialize($CFG) . serialize($_SERVER);
8034 $hash = '';
8035 do {
8036 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8037 } while (strlen($hash) < $length);
8039 return substr($hash, 0, $length);
8043 * Given some text (which may contain HTML) and an ideal length,
8044 * this function truncates the text neatly on a word boundary if possible
8046 * @category string
8047 * @param string $text text to be shortened
8048 * @param int $ideal ideal string length
8049 * @param boolean $exact if false, $text will not be cut mid-word
8050 * @param string $ending The string to append if the passed string is truncated
8051 * @return string $truncate shortened string
8053 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8054 // If the plain text is shorter than the maximum length, return the whole text.
8055 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8056 return $text;
8059 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8060 // and only tag in its 'line'.
8061 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8063 $totallength = core_text::strlen($ending);
8064 $truncate = '';
8066 // This array stores information about open and close tags and their position
8067 // in the truncated string. Each item in the array is an object with fields
8068 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8069 // (byte position in truncated text).
8070 $tagdetails = array();
8072 foreach ($lines as $linematchings) {
8073 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8074 if (!empty($linematchings[1])) {
8075 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8076 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8077 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8078 // Record closing tag.
8079 $tagdetails[] = (object) array(
8080 'open' => false,
8081 'tag' => core_text::strtolower($tagmatchings[1]),
8082 'pos' => core_text::strlen($truncate),
8085 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8086 // Record opening tag.
8087 $tagdetails[] = (object) array(
8088 'open' => true,
8089 'tag' => core_text::strtolower($tagmatchings[1]),
8090 'pos' => core_text::strlen($truncate),
8092 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8093 $tagdetails[] = (object) array(
8094 'open' => true,
8095 'tag' => core_text::strtolower('if'),
8096 'pos' => core_text::strlen($truncate),
8098 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8099 $tagdetails[] = (object) array(
8100 'open' => false,
8101 'tag' => core_text::strtolower('if'),
8102 'pos' => core_text::strlen($truncate),
8106 // Add html-tag to $truncate'd text.
8107 $truncate .= $linematchings[1];
8110 // Calculate the length of the plain text part of the line; handle entities as one character.
8111 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8112 if ($totallength + $contentlength > $ideal) {
8113 // The number of characters which are left.
8114 $left = $ideal - $totallength;
8115 $entitieslength = 0;
8116 // Search for html entities.
8117 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)) {
8118 // Calculate the real length of all entities in the legal range.
8119 foreach ($entities[0] as $entity) {
8120 if ($entity[1]+1-$entitieslength <= $left) {
8121 $left--;
8122 $entitieslength += core_text::strlen($entity[0]);
8123 } else {
8124 // No more characters left.
8125 break;
8129 $breakpos = $left + $entitieslength;
8131 // If the words shouldn't be cut in the middle...
8132 if (!$exact) {
8133 // Search the last occurence of a space.
8134 for (; $breakpos > 0; $breakpos--) {
8135 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8136 if ($char === '.' or $char === ' ') {
8137 $breakpos += 1;
8138 break;
8139 } else if (strlen($char) > 2) {
8140 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8141 $breakpos += 1;
8142 break;
8147 if ($breakpos == 0) {
8148 // This deals with the test_shorten_text_no_spaces case.
8149 $breakpos = $left + $entitieslength;
8150 } else if ($breakpos > $left + $entitieslength) {
8151 // This deals with the previous for loop breaking on the first char.
8152 $breakpos = $left + $entitieslength;
8155 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8156 // Maximum length is reached, so get off the loop.
8157 break;
8158 } else {
8159 $truncate .= $linematchings[2];
8160 $totallength += $contentlength;
8163 // If the maximum length is reached, get off the loop.
8164 if ($totallength >= $ideal) {
8165 break;
8169 // Add the defined ending to the text.
8170 $truncate .= $ending;
8172 // Now calculate the list of open html tags based on the truncate position.
8173 $opentags = array();
8174 foreach ($tagdetails as $taginfo) {
8175 if ($taginfo->open) {
8176 // Add tag to the beginning of $opentags list.
8177 array_unshift($opentags, $taginfo->tag);
8178 } else {
8179 // Can have multiple exact same open tags, close the last one.
8180 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8181 if ($pos !== false) {
8182 unset($opentags[$pos]);
8187 // Close all unclosed html-tags.
8188 foreach ($opentags as $tag) {
8189 if ($tag === 'if') {
8190 $truncate .= '<!--<![endif]-->';
8191 } else {
8192 $truncate .= '</' . $tag . '>';
8196 return $truncate;
8201 * Given dates in seconds, how many weeks is the date from startdate
8202 * The first week is 1, the second 2 etc ...
8204 * @param int $startdate Timestamp for the start date
8205 * @param int $thedate Timestamp for the end date
8206 * @return string
8208 function getweek ($startdate, $thedate) {
8209 if ($thedate < $startdate) {
8210 return 0;
8213 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8217 * Returns a randomly generated password of length $maxlen. inspired by
8219 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8220 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8222 * @param int $maxlen The maximum size of the password being generated.
8223 * @return string
8225 function generate_password($maxlen=10) {
8226 global $CFG;
8228 if (empty($CFG->passwordpolicy)) {
8229 $fillers = PASSWORD_DIGITS;
8230 $wordlist = file($CFG->wordlist);
8231 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8232 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8233 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8234 $password = $word1 . $filler1 . $word2;
8235 } else {
8236 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8237 $digits = $CFG->minpassworddigits;
8238 $lower = $CFG->minpasswordlower;
8239 $upper = $CFG->minpasswordupper;
8240 $nonalphanum = $CFG->minpasswordnonalphanum;
8241 $total = $lower + $upper + $digits + $nonalphanum;
8242 // Var minlength should be the greater one of the two ( $minlen and $total ).
8243 $minlen = $minlen < $total ? $total : $minlen;
8244 // Var maxlen can never be smaller than minlen.
8245 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8246 $additional = $maxlen - $total;
8248 // Make sure we have enough characters to fulfill
8249 // complexity requirements.
8250 $passworddigits = PASSWORD_DIGITS;
8251 while ($digits > strlen($passworddigits)) {
8252 $passworddigits .= PASSWORD_DIGITS;
8254 $passwordlower = PASSWORD_LOWER;
8255 while ($lower > strlen($passwordlower)) {
8256 $passwordlower .= PASSWORD_LOWER;
8258 $passwordupper = PASSWORD_UPPER;
8259 while ($upper > strlen($passwordupper)) {
8260 $passwordupper .= PASSWORD_UPPER;
8262 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8263 while ($nonalphanum > strlen($passwordnonalphanum)) {
8264 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8267 // Now mix and shuffle it all.
8268 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8269 substr(str_shuffle ($passwordupper), 0, $upper) .
8270 substr(str_shuffle ($passworddigits), 0, $digits) .
8271 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8272 substr(str_shuffle ($passwordlower .
8273 $passwordupper .
8274 $passworddigits .
8275 $passwordnonalphanum), 0 , $additional));
8278 return substr ($password, 0, $maxlen);
8282 * Given a float, prints it nicely.
8283 * Localized floats must not be used in calculations!
8285 * The stripzeros feature is intended for making numbers look nicer in small
8286 * areas where it is not necessary to indicate the degree of accuracy by showing
8287 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8288 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8290 * @param float $float The float to print
8291 * @param int $decimalpoints The number of decimal places to print.
8292 * @param bool $localized use localized decimal separator
8293 * @param bool $stripzeros If true, removes final zeros after decimal point
8294 * @return string locale float
8296 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8297 if (is_null($float)) {
8298 return '';
8300 if ($localized) {
8301 $separator = get_string('decsep', 'langconfig');
8302 } else {
8303 $separator = '.';
8305 $result = number_format($float, $decimalpoints, $separator, '');
8306 if ($stripzeros) {
8307 // Remove zeros and final dot if not needed.
8308 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8310 return $result;
8314 * Converts locale specific floating point/comma number back to standard PHP float value
8315 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8317 * @param string $localefloat locale aware float representation
8318 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8319 * @return mixed float|bool - false or the parsed float.
8321 function unformat_float($localefloat, $strict = false) {
8322 $localefloat = trim($localefloat);
8324 if ($localefloat == '') {
8325 return null;
8328 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8329 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8331 if ($strict && !is_numeric($localefloat)) {
8332 return false;
8335 return (float)$localefloat;
8339 * Given a simple array, this shuffles it up just like shuffle()
8340 * Unlike PHP's shuffle() this function works on any machine.
8342 * @param array $array The array to be rearranged
8343 * @return array
8345 function swapshuffle($array) {
8347 $last = count($array) - 1;
8348 for ($i = 0; $i <= $last; $i++) {
8349 $from = rand(0, $last);
8350 $curr = $array[$i];
8351 $array[$i] = $array[$from];
8352 $array[$from] = $curr;
8354 return $array;
8358 * Like {@link swapshuffle()}, but works on associative arrays
8360 * @param array $array The associative array to be rearranged
8361 * @return array
8363 function swapshuffle_assoc($array) {
8365 $newarray = array();
8366 $newkeys = swapshuffle(array_keys($array));
8368 foreach ($newkeys as $newkey) {
8369 $newarray[$newkey] = $array[$newkey];
8371 return $newarray;
8375 * Given an arbitrary array, and a number of draws,
8376 * this function returns an array with that amount
8377 * of items. The indexes are retained.
8379 * @todo Finish documenting this function
8381 * @param array $array
8382 * @param int $draws
8383 * @return array
8385 function draw_rand_array($array, $draws) {
8387 $return = array();
8389 $last = count($array);
8391 if ($draws > $last) {
8392 $draws = $last;
8395 while ($draws > 0) {
8396 $last--;
8398 $keys = array_keys($array);
8399 $rand = rand(0, $last);
8401 $return[$keys[$rand]] = $array[$keys[$rand]];
8402 unset($array[$keys[$rand]]);
8404 $draws--;
8407 return $return;
8411 * Calculate the difference between two microtimes
8413 * @param string $a The first Microtime
8414 * @param string $b The second Microtime
8415 * @return string
8417 function microtime_diff($a, $b) {
8418 list($adec, $asec) = explode(' ', $a);
8419 list($bdec, $bsec) = explode(' ', $b);
8420 return $bsec - $asec + $bdec - $adec;
8424 * Given a list (eg a,b,c,d,e) this function returns
8425 * an array of 1->a, 2->b, 3->c etc
8427 * @param string $list The string to explode into array bits
8428 * @param string $separator The separator used within the list string
8429 * @return array The now assembled array
8431 function make_menu_from_list($list, $separator=',') {
8433 $array = array_reverse(explode($separator, $list), true);
8434 foreach ($array as $key => $item) {
8435 $outarray[$key+1] = trim($item);
8437 return $outarray;
8441 * Creates an array that represents all the current grades that
8442 * can be chosen using the given grading type.
8444 * Negative numbers
8445 * are scales, zero is no grade, and positive numbers are maximum
8446 * grades.
8448 * @todo Finish documenting this function or better deprecated this completely!
8450 * @param int $gradingtype
8451 * @return array
8453 function make_grades_menu($gradingtype) {
8454 global $DB;
8456 $grades = array();
8457 if ($gradingtype < 0) {
8458 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8459 return make_menu_from_list($scale->scale);
8461 } else if ($gradingtype > 0) {
8462 for ($i=$gradingtype; $i>=0; $i--) {
8463 $grades[$i] = $i .' / '. $gradingtype;
8465 return $grades;
8467 return $grades;
8471 * make_unique_id_code
8473 * @todo Finish documenting this function
8475 * @uses $_SERVER
8476 * @param string $extra Extra string to append to the end of the code
8477 * @return string
8479 function make_unique_id_code($extra = '') {
8481 $hostname = 'unknownhost';
8482 if (!empty($_SERVER['HTTP_HOST'])) {
8483 $hostname = $_SERVER['HTTP_HOST'];
8484 } else if (!empty($_ENV['HTTP_HOST'])) {
8485 $hostname = $_ENV['HTTP_HOST'];
8486 } else if (!empty($_SERVER['SERVER_NAME'])) {
8487 $hostname = $_SERVER['SERVER_NAME'];
8488 } else if (!empty($_ENV['SERVER_NAME'])) {
8489 $hostname = $_ENV['SERVER_NAME'];
8492 $date = gmdate("ymdHis");
8494 $random = random_string(6);
8496 if ($extra) {
8497 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8498 } else {
8499 return $hostname .'+'. $date .'+'. $random;
8505 * Function to check the passed address is within the passed subnet
8507 * The parameter is a comma separated string of subnet definitions.
8508 * Subnet strings can be in one of three formats:
8509 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8510 * 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)
8511 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8512 * Code for type 1 modified from user posted comments by mediator at
8513 * {@link http://au.php.net/manual/en/function.ip2long.php}
8515 * @param string $addr The address you are checking
8516 * @param string $subnetstr The string of subnet addresses
8517 * @return bool
8519 function address_in_subnet($addr, $subnetstr) {
8521 if ($addr == '0.0.0.0') {
8522 return false;
8524 $subnets = explode(',', $subnetstr);
8525 $found = false;
8526 $addr = trim($addr);
8527 $addr = cleanremoteaddr($addr, false); // Normalise.
8528 if ($addr === null) {
8529 return false;
8531 $addrparts = explode(':', $addr);
8533 $ipv6 = strpos($addr, ':');
8535 foreach ($subnets as $subnet) {
8536 $subnet = trim($subnet);
8537 if ($subnet === '') {
8538 continue;
8541 if (strpos($subnet, '/') !== false) {
8542 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8543 list($ip, $mask) = explode('/', $subnet);
8544 $mask = trim($mask);
8545 if (!is_number($mask)) {
8546 continue; // Incorect mask number, eh?
8548 $ip = cleanremoteaddr($ip, false); // Normalise.
8549 if ($ip === null) {
8550 continue;
8552 if (strpos($ip, ':') !== false) {
8553 // IPv6.
8554 if (!$ipv6) {
8555 continue;
8557 if ($mask > 128 or $mask < 0) {
8558 continue; // Nonsense.
8560 if ($mask == 0) {
8561 return true; // Any address.
8563 if ($mask == 128) {
8564 if ($ip === $addr) {
8565 return true;
8567 continue;
8569 $ipparts = explode(':', $ip);
8570 $modulo = $mask % 16;
8571 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8572 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8573 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8574 if ($modulo == 0) {
8575 return true;
8577 $pos = ($mask-$modulo)/16;
8578 $ipnet = hexdec($ipparts[$pos]);
8579 $addrnet = hexdec($addrparts[$pos]);
8580 $mask = 0xffff << (16 - $modulo);
8581 if (($addrnet & $mask) == ($ipnet & $mask)) {
8582 return true;
8586 } else {
8587 // IPv4.
8588 if ($ipv6) {
8589 continue;
8591 if ($mask > 32 or $mask < 0) {
8592 continue; // Nonsense.
8594 if ($mask == 0) {
8595 return true;
8597 if ($mask == 32) {
8598 if ($ip === $addr) {
8599 return true;
8601 continue;
8603 $mask = 0xffffffff << (32 - $mask);
8604 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8605 return true;
8609 } else if (strpos($subnet, '-') !== false) {
8610 // 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.
8611 $parts = explode('-', $subnet);
8612 if (count($parts) != 2) {
8613 continue;
8616 if (strpos($subnet, ':') !== false) {
8617 // IPv6.
8618 if (!$ipv6) {
8619 continue;
8621 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8622 if ($ipstart === null) {
8623 continue;
8625 $ipparts = explode(':', $ipstart);
8626 $start = hexdec(array_pop($ipparts));
8627 $ipparts[] = trim($parts[1]);
8628 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8629 if ($ipend === null) {
8630 continue;
8632 $ipparts[7] = '';
8633 $ipnet = implode(':', $ipparts);
8634 if (strpos($addr, $ipnet) !== 0) {
8635 continue;
8637 $ipparts = explode(':', $ipend);
8638 $end = hexdec($ipparts[7]);
8640 $addrend = hexdec($addrparts[7]);
8642 if (($addrend >= $start) and ($addrend <= $end)) {
8643 return true;
8646 } else {
8647 // IPv4.
8648 if ($ipv6) {
8649 continue;
8651 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8652 if ($ipstart === null) {
8653 continue;
8655 $ipparts = explode('.', $ipstart);
8656 $ipparts[3] = trim($parts[1]);
8657 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8658 if ($ipend === null) {
8659 continue;
8662 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8663 return true;
8667 } else {
8668 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8669 if (strpos($subnet, ':') !== false) {
8670 // IPv6.
8671 if (!$ipv6) {
8672 continue;
8674 $parts = explode(':', $subnet);
8675 $count = count($parts);
8676 if ($parts[$count-1] === '') {
8677 unset($parts[$count-1]); // Trim trailing :'s.
8678 $count--;
8679 $subnet = implode('.', $parts);
8681 $isip = cleanremoteaddr($subnet, false); // Normalise.
8682 if ($isip !== null) {
8683 if ($isip === $addr) {
8684 return true;
8686 continue;
8687 } else if ($count > 8) {
8688 continue;
8690 $zeros = array_fill(0, 8-$count, '0');
8691 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8692 if (address_in_subnet($addr, $subnet)) {
8693 return true;
8696 } else {
8697 // IPv4.
8698 if ($ipv6) {
8699 continue;
8701 $parts = explode('.', $subnet);
8702 $count = count($parts);
8703 if ($parts[$count-1] === '') {
8704 unset($parts[$count-1]); // Trim trailing .
8705 $count--;
8706 $subnet = implode('.', $parts);
8708 if ($count == 4) {
8709 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8710 if ($subnet === $addr) {
8711 return true;
8713 continue;
8714 } else if ($count > 4) {
8715 continue;
8717 $zeros = array_fill(0, 4-$count, '0');
8718 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8719 if (address_in_subnet($addr, $subnet)) {
8720 return true;
8726 return false;
8730 * For outputting debugging info
8732 * @param string $string The string to write
8733 * @param string $eol The end of line char(s) to use
8734 * @param string $sleep Period to make the application sleep
8735 * This ensures any messages have time to display before redirect
8737 function mtrace($string, $eol="\n", $sleep=0) {
8739 if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
8740 fwrite(STDOUT, $string.$eol);
8741 } else {
8742 echo $string . $eol;
8745 flush();
8747 // Delay to keep message on user's screen in case of subsequent redirect.
8748 if ($sleep) {
8749 sleep($sleep);
8754 * Replace 1 or more slashes or backslashes to 1 slash
8756 * @param string $path The path to strip
8757 * @return string the path with double slashes removed
8759 function cleardoubleslashes ($path) {
8760 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8764 * Is current ip in give list?
8766 * @param string $list
8767 * @return bool
8769 function remoteip_in_list($list) {
8770 $inlist = false;
8771 $clientip = getremoteaddr(null);
8773 if (!$clientip) {
8774 // Ensure access on cli.
8775 return true;
8778 $list = explode("\n", $list);
8779 foreach ($list as $subnet) {
8780 $subnet = trim($subnet);
8781 if (address_in_subnet($clientip, $subnet)) {
8782 $inlist = true;
8783 break;
8786 return $inlist;
8790 * Returns most reliable client address
8792 * @param string $default If an address can't be determined, then return this
8793 * @return string The remote IP address
8795 function getremoteaddr($default='0.0.0.0') {
8796 global $CFG;
8798 if (empty($CFG->getremoteaddrconf)) {
8799 // This will happen, for example, before just after the upgrade, as the
8800 // user is redirected to the admin screen.
8801 $variablestoskip = 0;
8802 } else {
8803 $variablestoskip = $CFG->getremoteaddrconf;
8805 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8806 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8807 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8808 return $address ? $address : $default;
8811 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8812 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8813 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8814 $address = $forwardedaddresses[0];
8816 if (substr_count($address, ":") > 1) {
8817 // Remove port and brackets from IPv6.
8818 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8819 $address = $matches[1];
8821 } else {
8822 // Remove port from IPv4.
8823 if (substr_count($address, ":") == 1) {
8824 $parts = explode(":", $address);
8825 $address = $parts[0];
8829 $address = cleanremoteaddr($address);
8830 return $address ? $address : $default;
8833 if (!empty($_SERVER['REMOTE_ADDR'])) {
8834 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8835 return $address ? $address : $default;
8836 } else {
8837 return $default;
8842 * Cleans an ip address. Internal addresses are now allowed.
8843 * (Originally local addresses were not allowed.)
8845 * @param string $addr IPv4 or IPv6 address
8846 * @param bool $compress use IPv6 address compression
8847 * @return string normalised ip address string, null if error
8849 function cleanremoteaddr($addr, $compress=false) {
8850 $addr = trim($addr);
8852 if (strpos($addr, ':') !== false) {
8853 // Can be only IPv6.
8854 $parts = explode(':', $addr);
8855 $count = count($parts);
8857 if (strpos($parts[$count-1], '.') !== false) {
8858 // Legacy ipv4 notation.
8859 $last = array_pop($parts);
8860 $ipv4 = cleanremoteaddr($last, true);
8861 if ($ipv4 === null) {
8862 return null;
8864 $bits = explode('.', $ipv4);
8865 $parts[] = dechex($bits[0]).dechex($bits[1]);
8866 $parts[] = dechex($bits[2]).dechex($bits[3]);
8867 $count = count($parts);
8868 $addr = implode(':', $parts);
8871 if ($count < 3 or $count > 8) {
8872 return null; // Severly malformed.
8875 if ($count != 8) {
8876 if (strpos($addr, '::') === false) {
8877 return null; // Malformed.
8879 // Uncompress.
8880 $insertat = array_search('', $parts, true);
8881 $missing = array_fill(0, 1 + 8 - $count, '0');
8882 array_splice($parts, $insertat, 1, $missing);
8883 foreach ($parts as $key => $part) {
8884 if ($part === '') {
8885 $parts[$key] = '0';
8890 $adr = implode(':', $parts);
8891 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8892 return null; // Incorrect format - sorry.
8895 // Normalise 0s and case.
8896 $parts = array_map('hexdec', $parts);
8897 $parts = array_map('dechex', $parts);
8899 $result = implode(':', $parts);
8901 if (!$compress) {
8902 return $result;
8905 if ($result === '0:0:0:0:0:0:0:0') {
8906 return '::'; // All addresses.
8909 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8910 if ($compressed !== $result) {
8911 return $compressed;
8914 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8915 if ($compressed !== $result) {
8916 return $compressed;
8919 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8920 if ($compressed !== $result) {
8921 return $compressed;
8924 return $result;
8927 // First get all things that look like IPv4 addresses.
8928 $parts = array();
8929 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8930 return null;
8932 unset($parts[0]);
8934 foreach ($parts as $key => $match) {
8935 if ($match > 255) {
8936 return null;
8938 $parts[$key] = (int)$match; // Normalise 0s.
8941 return implode('.', $parts);
8946 * Is IP address a public address?
8948 * @param string $ip The ip to check
8949 * @return bool true if the ip is public
8951 function ip_is_public($ip) {
8952 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
8956 * This function will make a complete copy of anything it's given,
8957 * regardless of whether it's an object or not.
8959 * @param mixed $thing Something you want cloned
8960 * @return mixed What ever it is you passed it
8962 function fullclone($thing) {
8963 return unserialize(serialize($thing));
8967 * Used to make sure that $min <= $value <= $max
8969 * Make sure that value is between min, and max
8971 * @param int $min The minimum value
8972 * @param int $value The value to check
8973 * @param int $max The maximum value
8974 * @return int
8976 function bounded_number($min, $value, $max) {
8977 if ($value < $min) {
8978 return $min;
8980 if ($value > $max) {
8981 return $max;
8983 return $value;
8987 * Check if there is a nested array within the passed array
8989 * @param array $array
8990 * @return bool true if there is a nested array false otherwise
8992 function array_is_nested($array) {
8993 foreach ($array as $value) {
8994 if (is_array($value)) {
8995 return true;
8998 return false;
9002 * get_performance_info() pairs up with init_performance_info()
9003 * loaded in setup.php. Returns an array with 'html' and 'txt'
9004 * values ready for use, and each of the individual stats provided
9005 * separately as well.
9007 * @return array
9009 function get_performance_info() {
9010 global $CFG, $PERF, $DB, $PAGE;
9012 $info = array();
9013 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9015 $info['html'] = '';
9016 if (!empty($CFG->themedesignermode)) {
9017 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9018 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9020 $info['html'] .= '<ul class="list-unstyled m-l-1 row">'; // Holds userfriendly HTML representation.
9022 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9024 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9025 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9027 if (function_exists('memory_get_usage')) {
9028 $info['memory_total'] = memory_get_usage();
9029 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9030 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9031 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9032 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9035 if (function_exists('memory_get_peak_usage')) {
9036 $info['memory_peak'] = memory_get_peak_usage();
9037 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9038 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9041 $info['html'] .= '</ul><ul class="list-unstyled m-l-1 row">';
9042 $inc = get_included_files();
9043 $info['includecount'] = count($inc);
9044 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9045 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9047 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9048 // We can not track more performance before installation or before PAGE init, sorry.
9049 return $info;
9052 $filtermanager = filter_manager::instance();
9053 if (method_exists($filtermanager, 'get_performance_summary')) {
9054 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9055 $info = array_merge($filterinfo, $info);
9056 foreach ($filterinfo as $key => $value) {
9057 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9058 $info['txt'] .= "$key: $value ";
9062 $stringmanager = get_string_manager();
9063 if (method_exists($stringmanager, 'get_performance_summary')) {
9064 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9065 $info = array_merge($filterinfo, $info);
9066 foreach ($filterinfo as $key => $value) {
9067 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9068 $info['txt'] .= "$key: $value ";
9072 if (!empty($PERF->logwrites)) {
9073 $info['logwrites'] = $PERF->logwrites;
9074 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9075 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9078 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9079 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9080 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9082 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9083 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9084 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9086 if (function_exists('posix_times')) {
9087 $ptimes = posix_times();
9088 if (is_array($ptimes)) {
9089 foreach ($ptimes as $key => $val) {
9090 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9092 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9093 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9094 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9098 // Grab the load average for the last minute.
9099 // /proc will only work under some linux configurations
9100 // while uptime is there under MacOSX/Darwin and other unices.
9101 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9102 list($serverload) = explode(' ', $loadavg[0]);
9103 unset($loadavg);
9104 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9105 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9106 $serverload = $matches[1];
9107 } else {
9108 trigger_error('Could not parse uptime output!');
9111 if (!empty($serverload)) {
9112 $info['serverload'] = $serverload;
9113 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9114 $info['txt'] .= "serverload: {$info['serverload']} ";
9117 // Display size of session if session started.
9118 if ($si = \core\session\manager::get_performance_info()) {
9119 $info['sessionsize'] = $si['size'];
9120 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9121 $info['txt'] .= $si['txt'];
9124 $info['html'] .= '</ul>';
9125 if ($stats = cache_helper::get_stats()) {
9126 $html = '<ul class="cachesused list-unstyled m-l-1 row">';
9127 $html .= '<li class="cache-stats-heading font-weight-bold">Caches used (hits/misses/sets)</li>';
9128 $html .= '</ul><ul class="cachesused list-unstyled m-l-1">';
9129 $text = 'Caches used (hits/misses/sets): ';
9130 $hits = 0;
9131 $misses = 0;
9132 $sets = 0;
9133 foreach ($stats as $definition => $details) {
9134 switch ($details['mode']) {
9135 case cache_store::MODE_APPLICATION:
9136 $modeclass = 'application';
9137 $mode = ' <span title="application cache">[a]</span>';
9138 break;
9139 case cache_store::MODE_SESSION:
9140 $modeclass = 'session';
9141 $mode = ' <span title="session cache">[s]</span>';
9142 break;
9143 case cache_store::MODE_REQUEST:
9144 $modeclass = 'request';
9145 $mode = ' <span title="request cache">[r]</span>';
9146 break;
9148 $html .= '<ul class="cache-definition-stats list-unstyled m-l-1 cache-mode-'.$modeclass.' card d-inline-block">';
9149 $html .= '<li class="cache-definition-stats-heading p-t-1 card-header bg-inverse font-weight-bold">' .
9150 $definition . $mode.'</li>';
9151 $text .= "$definition {";
9152 foreach ($details['stores'] as $store => $data) {
9153 $hits += $data['hits'];
9154 $misses += $data['misses'];
9155 $sets += $data['sets'];
9156 if ($data['hits'] == 0 and $data['misses'] > 0) {
9157 $cachestoreclass = 'nohits text-danger';
9158 } else if ($data['hits'] < $data['misses']) {
9159 $cachestoreclass = 'lowhits text-warning';
9160 } else {
9161 $cachestoreclass = 'hihits text-success';
9163 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9164 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">" .
9165 "$store: $data[hits] / $data[misses] / $data[sets]</li>";
9166 // This makes boxes of same sizes.
9167 if (count($details['stores']) == 1) {
9168 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">&nbsp;</li>";
9171 $html .= '</ul>';
9172 $text .= '} ';
9174 $html .= '</ul> ';
9175 $html .= "<div class='cache-total-stats row'>Total: $hits / $misses / $sets</div>";
9176 $info['cachesused'] = "$hits / $misses / $sets";
9177 $info['html'] .= $html;
9178 $info['txt'] .= $text.'. ';
9179 } else {
9180 $info['cachesused'] = '0 / 0 / 0';
9181 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9182 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9185 $info['html'] = '<div class="performanceinfo siteinfo container-fluid">'.$info['html'].'</div>';
9186 return $info;
9190 * Delete directory or only its content
9192 * @param string $dir directory path
9193 * @param bool $contentonly
9194 * @return bool success, true also if dir does not exist
9196 function remove_dir($dir, $contentonly=false) {
9197 if (!file_exists($dir)) {
9198 // Nothing to do.
9199 return true;
9201 if (!$handle = opendir($dir)) {
9202 return false;
9204 $result = true;
9205 while (false!==($item = readdir($handle))) {
9206 if ($item != '.' && $item != '..') {
9207 if (is_dir($dir.'/'.$item)) {
9208 $result = remove_dir($dir.'/'.$item) && $result;
9209 } else {
9210 $result = unlink($dir.'/'.$item) && $result;
9214 closedir($handle);
9215 if ($contentonly) {
9216 clearstatcache(); // Make sure file stat cache is properly invalidated.
9217 return $result;
9219 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9220 clearstatcache(); // Make sure file stat cache is properly invalidated.
9221 return $result;
9225 * Detect if an object or a class contains a given property
9226 * will take an actual object or the name of a class
9228 * @param mix $obj Name of class or real object to test
9229 * @param string $property name of property to find
9230 * @return bool true if property exists
9232 function object_property_exists( $obj, $property ) {
9233 if (is_string( $obj )) {
9234 $properties = get_class_vars( $obj );
9235 } else {
9236 $properties = get_object_vars( $obj );
9238 return array_key_exists( $property, $properties );
9242 * Converts an object into an associative array
9244 * This function converts an object into an associative array by iterating
9245 * over its public properties. Because this function uses the foreach
9246 * construct, Iterators are respected. It works recursively on arrays of objects.
9247 * Arrays and simple values are returned as is.
9249 * If class has magic properties, it can implement IteratorAggregate
9250 * and return all available properties in getIterator()
9252 * @param mixed $var
9253 * @return array
9255 function convert_to_array($var) {
9256 $result = array();
9258 // Loop over elements/properties.
9259 foreach ($var as $key => $value) {
9260 // Recursively convert objects.
9261 if (is_object($value) || is_array($value)) {
9262 $result[$key] = convert_to_array($value);
9263 } else {
9264 // Simple values are untouched.
9265 $result[$key] = $value;
9268 return $result;
9272 * Detect a custom script replacement in the data directory that will
9273 * replace an existing moodle script
9275 * @return string|bool full path name if a custom script exists, false if no custom script exists
9277 function custom_script_path() {
9278 global $CFG, $SCRIPT;
9280 if ($SCRIPT === null) {
9281 // Probably some weird external script.
9282 return false;
9285 $scriptpath = $CFG->customscripts . $SCRIPT;
9287 // Check the custom script exists.
9288 if (file_exists($scriptpath) and is_file($scriptpath)) {
9289 return $scriptpath;
9290 } else {
9291 return false;
9296 * Returns whether or not the user object is a remote MNET user. This function
9297 * is in moodlelib because it does not rely on loading any of the MNET code.
9299 * @param object $user A valid user object
9300 * @return bool True if the user is from a remote Moodle.
9302 function is_mnet_remote_user($user) {
9303 global $CFG;
9305 if (!isset($CFG->mnet_localhost_id)) {
9306 include_once($CFG->dirroot . '/mnet/lib.php');
9307 $env = new mnet_environment();
9308 $env->init();
9309 unset($env);
9312 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9316 * This function will search for browser prefereed languages, setting Moodle
9317 * to use the best one available if $SESSION->lang is undefined
9319 function setup_lang_from_browser() {
9320 global $CFG, $SESSION, $USER;
9322 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9323 // Lang is defined in session or user profile, nothing to do.
9324 return;
9327 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9328 return;
9331 // Extract and clean langs from headers.
9332 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9333 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9334 $rawlangs = explode(',', $rawlangs); // Convert to array.
9335 $langs = array();
9337 $order = 1.0;
9338 foreach ($rawlangs as $lang) {
9339 if (strpos($lang, ';') === false) {
9340 $langs[(string)$order] = $lang;
9341 $order = $order-0.01;
9342 } else {
9343 $parts = explode(';', $lang);
9344 $pos = strpos($parts[1], '=');
9345 $langs[substr($parts[1], $pos+1)] = $parts[0];
9348 krsort($langs, SORT_NUMERIC);
9350 // Look for such langs under standard locations.
9351 foreach ($langs as $lang) {
9352 // Clean it properly for include.
9353 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9354 if (get_string_manager()->translation_exists($lang, false)) {
9355 // Lang exists, set it in session.
9356 $SESSION->lang = $lang;
9357 // We have finished. Go out.
9358 break;
9361 return;
9365 * Check if $url matches anything in proxybypass list
9367 * Any errors just result in the proxy being used (least bad)
9369 * @param string $url url to check
9370 * @return boolean true if we should bypass the proxy
9372 function is_proxybypass( $url ) {
9373 global $CFG;
9375 // Sanity check.
9376 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9377 return false;
9380 // Get the host part out of the url.
9381 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9382 return false;
9385 // Get the possible bypass hosts into an array.
9386 $matches = explode( ',', $CFG->proxybypass );
9388 // Check for a match.
9389 // (IPs need to match the left hand side and hosts the right of the url,
9390 // but we can recklessly check both as there can't be a false +ve).
9391 foreach ($matches as $match) {
9392 $match = trim($match);
9394 // Try for IP match (Left side).
9395 $lhs = substr($host, 0, strlen($match));
9396 if (strcasecmp($match, $lhs)==0) {
9397 return true;
9400 // Try for host match (Right side).
9401 $rhs = substr($host, -strlen($match));
9402 if (strcasecmp($match, $rhs)==0) {
9403 return true;
9407 // Nothing matched.
9408 return false;
9412 * Check if the passed navigation is of the new style
9414 * @param mixed $navigation
9415 * @return bool true for yes false for no
9417 function is_newnav($navigation) {
9418 if (is_array($navigation) && !empty($navigation['newnav'])) {
9419 return true;
9420 } else {
9421 return false;
9426 * Checks whether the given variable name is defined as a variable within the given object.
9428 * This will NOT work with stdClass objects, which have no class variables.
9430 * @param string $var The variable name
9431 * @param object $object The object to check
9432 * @return boolean
9434 function in_object_vars($var, $object) {
9435 $classvars = get_class_vars(get_class($object));
9436 $classvars = array_keys($classvars);
9437 return in_array($var, $classvars);
9441 * Returns an array without repeated objects.
9442 * This function is similar to array_unique, but for arrays that have objects as values
9444 * @param array $array
9445 * @param bool $keepkeyassoc
9446 * @return array
9448 function object_array_unique($array, $keepkeyassoc = true) {
9449 $duplicatekeys = array();
9450 $tmp = array();
9452 foreach ($array as $key => $val) {
9453 // Convert objects to arrays, in_array() does not support objects.
9454 if (is_object($val)) {
9455 $val = (array)$val;
9458 if (!in_array($val, $tmp)) {
9459 $tmp[] = $val;
9460 } else {
9461 $duplicatekeys[] = $key;
9465 foreach ($duplicatekeys as $key) {
9466 unset($array[$key]);
9469 return $keepkeyassoc ? $array : array_values($array);
9473 * Is a userid the primary administrator?
9475 * @param int $userid int id of user to check
9476 * @return boolean
9478 function is_primary_admin($userid) {
9479 $primaryadmin = get_admin();
9481 if ($userid == $primaryadmin->id) {
9482 return true;
9483 } else {
9484 return false;
9489 * Returns the site identifier
9491 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9493 function get_site_identifier() {
9494 global $CFG;
9495 // Check to see if it is missing. If so, initialise it.
9496 if (empty($CFG->siteidentifier)) {
9497 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9499 // Return it.
9500 return $CFG->siteidentifier;
9504 * Check whether the given password has no more than the specified
9505 * number of consecutive identical characters.
9507 * @param string $password password to be checked against the password policy
9508 * @param integer $maxchars maximum number of consecutive identical characters
9509 * @return bool
9511 function check_consecutive_identical_characters($password, $maxchars) {
9513 if ($maxchars < 1) {
9514 return true; // Zero 0 is to disable this check.
9516 if (strlen($password) <= $maxchars) {
9517 return true; // Too short to fail this test.
9520 $previouschar = '';
9521 $consecutivecount = 1;
9522 foreach (str_split($password) as $char) {
9523 if ($char != $previouschar) {
9524 $consecutivecount = 1;
9525 } else {
9526 $consecutivecount++;
9527 if ($consecutivecount > $maxchars) {
9528 return false; // Check failed already.
9532 $previouschar = $char;
9535 return true;
9539 * Helper function to do partial function binding.
9540 * so we can use it for preg_replace_callback, for example
9541 * this works with php functions, user functions, static methods and class methods
9542 * it returns you a callback that you can pass on like so:
9544 * $callback = partial('somefunction', $arg1, $arg2);
9545 * or
9546 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9547 * or even
9548 * $obj = new someclass();
9549 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9551 * and then the arguments that are passed through at calltime are appended to the argument list.
9553 * @param mixed $function a php callback
9554 * @param mixed $arg1,... $argv arguments to partially bind with
9555 * @return array Array callback
9557 function partial() {
9558 if (!class_exists('partial')) {
9560 * Used to manage function binding.
9561 * @copyright 2009 Penny Leach
9562 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9564 class partial{
9565 /** @var array */
9566 public $values = array();
9567 /** @var string The function to call as a callback. */
9568 public $func;
9570 * Constructor
9571 * @param string $func
9572 * @param array $args
9574 public function __construct($func, $args) {
9575 $this->values = $args;
9576 $this->func = $func;
9579 * Calls the callback function.
9580 * @return mixed
9582 public function method() {
9583 $args = func_get_args();
9584 return call_user_func_array($this->func, array_merge($this->values, $args));
9588 $args = func_get_args();
9589 $func = array_shift($args);
9590 $p = new partial($func, $args);
9591 return array($p, 'method');
9595 * helper function to load up and initialise the mnet environment
9596 * this must be called before you use mnet functions.
9598 * @return mnet_environment the equivalent of old $MNET global
9600 function get_mnet_environment() {
9601 global $CFG;
9602 require_once($CFG->dirroot . '/mnet/lib.php');
9603 static $instance = null;
9604 if (empty($instance)) {
9605 $instance = new mnet_environment();
9606 $instance->init();
9608 return $instance;
9612 * during xmlrpc server code execution, any code wishing to access
9613 * information about the remote peer must use this to get it.
9615 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9617 function get_mnet_remote_client() {
9618 if (!defined('MNET_SERVER')) {
9619 debugging(get_string('notinxmlrpcserver', 'mnet'));
9620 return false;
9622 global $MNET_REMOTE_CLIENT;
9623 if (isset($MNET_REMOTE_CLIENT)) {
9624 return $MNET_REMOTE_CLIENT;
9626 return false;
9630 * during the xmlrpc server code execution, this will be called
9631 * to setup the object returned by {@link get_mnet_remote_client}
9633 * @param mnet_remote_client $client the client to set up
9634 * @throws moodle_exception
9636 function set_mnet_remote_client($client) {
9637 if (!defined('MNET_SERVER')) {
9638 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9640 global $MNET_REMOTE_CLIENT;
9641 $MNET_REMOTE_CLIENT = $client;
9645 * return the jump url for a given remote user
9646 * this is used for rewriting forum post links in emails, etc
9648 * @param stdclass $user the user to get the idp url for
9650 function mnet_get_idp_jump_url($user) {
9651 global $CFG;
9653 static $mnetjumps = array();
9654 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9655 $idp = mnet_get_peer_host($user->mnethostid);
9656 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9657 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9659 return $mnetjumps[$user->mnethostid];
9663 * Gets the homepage to use for the current user
9665 * @return int One of HOMEPAGE_*
9667 function get_home_page() {
9668 global $CFG;
9670 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9671 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9672 return HOMEPAGE_MY;
9673 } else {
9674 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9677 return HOMEPAGE_SITE;
9681 * Gets the name of a course to be displayed when showing a list of courses.
9682 * By default this is just $course->fullname but user can configure it. The
9683 * result of this function should be passed through print_string.
9684 * @param stdClass|course_in_list $course Moodle course object
9685 * @return string Display name of course (either fullname or short + fullname)
9687 function get_course_display_name_for_list($course) {
9688 global $CFG;
9689 if (!empty($CFG->courselistshortnames)) {
9690 if (!($course instanceof stdClass)) {
9691 $course = (object)convert_to_array($course);
9693 return get_string('courseextendednamedisplay', '', $course);
9694 } else {
9695 return $course->fullname;
9700 * The lang_string class
9702 * This special class is used to create an object representation of a string request.
9703 * It is special because processing doesn't occur until the object is first used.
9704 * The class was created especially to aid performance in areas where strings were
9705 * required to be generated but were not necessarily used.
9706 * As an example the admin tree when generated uses over 1500 strings, of which
9707 * normally only 1/3 are ever actually printed at any time.
9708 * The performance advantage is achieved by not actually processing strings that
9709 * arn't being used, as such reducing the processing required for the page.
9711 * How to use the lang_string class?
9712 * There are two methods of using the lang_string class, first through the
9713 * forth argument of the get_string function, and secondly directly.
9714 * The following are examples of both.
9715 * 1. Through get_string calls e.g.
9716 * $string = get_string($identifier, $component, $a, true);
9717 * $string = get_string('yes', 'moodle', null, true);
9718 * 2. Direct instantiation
9719 * $string = new lang_string($identifier, $component, $a, $lang);
9720 * $string = new lang_string('yes');
9722 * How do I use a lang_string object?
9723 * The lang_string object makes use of a magic __toString method so that you
9724 * are able to use the object exactly as you would use a string in most cases.
9725 * This means you are able to collect it into a variable and then directly
9726 * echo it, or concatenate it into another string, or similar.
9727 * The other thing you can do is manually get the string by calling the
9728 * lang_strings out method e.g.
9729 * $string = new lang_string('yes');
9730 * $string->out();
9731 * Also worth noting is that the out method can take one argument, $lang which
9732 * allows the developer to change the language on the fly.
9734 * When should I use a lang_string object?
9735 * The lang_string object is designed to be used in any situation where a
9736 * string may not be needed, but needs to be generated.
9737 * The admin tree is a good example of where lang_string objects should be
9738 * used.
9739 * A more practical example would be any class that requries strings that may
9740 * not be printed (after all classes get renderer by renderers and who knows
9741 * what they will do ;))
9743 * When should I not use a lang_string object?
9744 * Don't use lang_strings when you are going to use a string immediately.
9745 * There is no need as it will be processed immediately and there will be no
9746 * advantage, and in fact perhaps a negative hit as a class has to be
9747 * instantiated for a lang_string object, however get_string won't require
9748 * that.
9750 * Limitations:
9751 * 1. You cannot use a lang_string object as an array offset. Doing so will
9752 * result in PHP throwing an error. (You can use it as an object property!)
9754 * @package core
9755 * @category string
9756 * @copyright 2011 Sam Hemelryk
9757 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9759 class lang_string {
9761 /** @var string The strings identifier */
9762 protected $identifier;
9763 /** @var string The strings component. Default '' */
9764 protected $component = '';
9765 /** @var array|stdClass Any arguments required for the string. Default null */
9766 protected $a = null;
9767 /** @var string The language to use when processing the string. Default null */
9768 protected $lang = null;
9770 /** @var string The processed string (once processed) */
9771 protected $string = null;
9774 * A special boolean. If set to true then the object has been woken up and
9775 * cannot be regenerated. If this is set then $this->string MUST be used.
9776 * @var bool
9778 protected $forcedstring = false;
9781 * Constructs a lang_string object
9783 * This function should do as little processing as possible to ensure the best
9784 * performance for strings that won't be used.
9786 * @param string $identifier The strings identifier
9787 * @param string $component The strings component
9788 * @param stdClass|array $a Any arguments the string requires
9789 * @param string $lang The language to use when processing the string.
9790 * @throws coding_exception
9792 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9793 if (empty($component)) {
9794 $component = 'moodle';
9797 $this->identifier = $identifier;
9798 $this->component = $component;
9799 $this->lang = $lang;
9801 // We MUST duplicate $a to ensure that it if it changes by reference those
9802 // changes are not carried across.
9803 // To do this we always ensure $a or its properties/values are strings
9804 // and that any properties/values that arn't convertable are forgotten.
9805 if (!empty($a)) {
9806 if (is_scalar($a)) {
9807 $this->a = $a;
9808 } else if ($a instanceof lang_string) {
9809 $this->a = $a->out();
9810 } else if (is_object($a) or is_array($a)) {
9811 $a = (array)$a;
9812 $this->a = array();
9813 foreach ($a as $key => $value) {
9814 // Make sure conversion errors don't get displayed (results in '').
9815 if (is_array($value)) {
9816 $this->a[$key] = '';
9817 } else if (is_object($value)) {
9818 if (method_exists($value, '__toString')) {
9819 $this->a[$key] = $value->__toString();
9820 } else {
9821 $this->a[$key] = '';
9823 } else {
9824 $this->a[$key] = (string)$value;
9830 if (debugging(false, DEBUG_DEVELOPER)) {
9831 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9832 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9834 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9835 throw new coding_exception('Invalid string compontent. Please check your string definition');
9837 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9838 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9844 * Processes the string.
9846 * This function actually processes the string, stores it in the string property
9847 * and then returns it.
9848 * You will notice that this function is VERY similar to the get_string method.
9849 * That is because it is pretty much doing the same thing.
9850 * However as this function is an upgrade it isn't as tolerant to backwards
9851 * compatibility.
9853 * @return string
9854 * @throws coding_exception
9856 protected function get_string() {
9857 global $CFG;
9859 // Check if we need to process the string.
9860 if ($this->string === null) {
9861 // Check the quality of the identifier.
9862 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9863 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);
9866 // Process the string.
9867 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9868 // Debugging feature lets you display string identifier and component.
9869 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9870 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9873 // Return the string.
9874 return $this->string;
9878 * Returns the string
9880 * @param string $lang The langauge to use when processing the string
9881 * @return string
9883 public function out($lang = null) {
9884 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9885 if ($this->forcedstring) {
9886 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9887 return $this->get_string();
9889 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9890 return $translatedstring->out();
9892 return $this->get_string();
9896 * Magic __toString method for printing a string
9898 * @return string
9900 public function __toString() {
9901 return $this->get_string();
9905 * Magic __set_state method used for var_export
9907 * @return string
9909 public function __set_state() {
9910 return $this->get_string();
9914 * Prepares the lang_string for sleep and stores only the forcedstring and
9915 * string properties... the string cannot be regenerated so we need to ensure
9916 * it is generated for this.
9918 * @return string
9920 public function __sleep() {
9921 $this->get_string();
9922 $this->forcedstring = true;
9923 return array('forcedstring', 'string', 'lang');