Merge branch 'MDL-61839-master' of git://github.com/mihailges/moodle
[moodle.git] / lib / moodlelib.php
blobe26ef637ae50589163f92933a755f52d7a0f2745
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 receiving
119 * the input (required/optional_param or formslib) and then sanitise 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');
443 * Maximum filename char size
445 define('MAX_FILENAME_SIZE', 100);
447 /** Unspecified module archetype */
448 define('MOD_ARCHETYPE_OTHER', 0);
449 /** Resource-like type module */
450 define('MOD_ARCHETYPE_RESOURCE', 1);
451 /** Assignment module archetype */
452 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
453 /** System (not user-addable) module archetype */
454 define('MOD_ARCHETYPE_SYSTEM', 3);
457 * Security token used for allowing access
458 * from external application such as web services.
459 * Scripts do not use any session, performance is relatively
460 * low because we need to load access info in each request.
461 * Scripts are executed in parallel.
463 define('EXTERNAL_TOKEN_PERMANENT', 0);
466 * Security token used for allowing access
467 * of embedded applications, the code is executed in the
468 * active user session. Token is invalidated after user logs out.
469 * Scripts are executed serially - normal session locking is used.
471 define('EXTERNAL_TOKEN_EMBEDDED', 1);
474 * The home page should be the site home
476 define('HOMEPAGE_SITE', 0);
478 * The home page should be the users my page
480 define('HOMEPAGE_MY', 1);
482 * The home page can be chosen by the user
484 define('HOMEPAGE_USER', 2);
487 * Hub directory url (should be moodle.org)
489 define('HUB_HUBDIRECTORYURL', "https://hubdirectory.moodle.org");
493 * Moodle.net url (should be moodle.net)
495 define('HUB_MOODLEORGHUBURL', "https://moodle.net");
496 define('HUB_OLDMOODLEORGHUBURL', "http://hub.moodle.org");
499 * Moodle mobile app service name
501 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
504 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
506 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
509 * Course display settings: display all sections on one page.
511 define('COURSE_DISPLAY_SINGLEPAGE', 0);
513 * Course display settings: split pages into a page per section.
515 define('COURSE_DISPLAY_MULTIPAGE', 1);
518 * Authentication constant: String used in password field when password is not stored.
520 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
523 * Email from header to never include via information.
525 define('EMAIL_VIA_NEVER', 0);
528 * Email from header to always include via information.
530 define('EMAIL_VIA_ALWAYS', 1);
533 * Email from header to only include via information if the address is no-reply.
535 define('EMAIL_VIA_NO_REPLY_ONLY', 2);
537 // PARAMETER HANDLING.
540 * Returns a particular value for the named variable, taken from
541 * POST or GET. If the parameter doesn't exist then an error is
542 * thrown because we require this variable.
544 * This function should be used to initialise all required values
545 * in a script that are based on parameters. Usually it will be
546 * used like this:
547 * $id = required_param('id', PARAM_INT);
549 * Please note the $type parameter is now required and the value can not be array.
551 * @param string $parname the name of the page parameter we want
552 * @param string $type expected type of parameter
553 * @return mixed
554 * @throws coding_exception
556 function required_param($parname, $type) {
557 if (func_num_args() != 2 or empty($parname) or empty($type)) {
558 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
560 // POST has precedence.
561 if (isset($_POST[$parname])) {
562 $param = $_POST[$parname];
563 } else if (isset($_GET[$parname])) {
564 $param = $_GET[$parname];
565 } else {
566 print_error('missingparam', '', '', $parname);
569 if (is_array($param)) {
570 debugging('Invalid array parameter detected in required_param(): '.$parname);
571 // TODO: switch to fatal error in Moodle 2.3.
572 return required_param_array($parname, $type);
575 return clean_param($param, $type);
579 * Returns a particular array value for the named variable, taken from
580 * POST or GET. If the parameter doesn't exist then an error is
581 * thrown because we require this variable.
583 * This function should be used to initialise all required values
584 * in a script that are based on parameters. Usually it will be
585 * used like this:
586 * $ids = required_param_array('ids', PARAM_INT);
588 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
590 * @param string $parname the name of the page parameter we want
591 * @param string $type expected type of parameter
592 * @return array
593 * @throws coding_exception
595 function required_param_array($parname, $type) {
596 if (func_num_args() != 2 or empty($parname) or empty($type)) {
597 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
599 // POST has precedence.
600 if (isset($_POST[$parname])) {
601 $param = $_POST[$parname];
602 } else if (isset($_GET[$parname])) {
603 $param = $_GET[$parname];
604 } else {
605 print_error('missingparam', '', '', $parname);
607 if (!is_array($param)) {
608 print_error('missingparam', '', '', $parname);
611 $result = array();
612 foreach ($param as $key => $value) {
613 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
614 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
615 continue;
617 $result[$key] = clean_param($value, $type);
620 return $result;
624 * Returns a particular value for the named variable, taken from
625 * POST or GET, otherwise returning a given default.
627 * This function should be used to initialise all optional values
628 * in a script that are based on parameters. Usually it will be
629 * used like this:
630 * $name = optional_param('name', 'Fred', PARAM_TEXT);
632 * Please note the $type parameter is now required and the value can not be array.
634 * @param string $parname the name of the page parameter we want
635 * @param mixed $default the default value to return if nothing is found
636 * @param string $type expected type of parameter
637 * @return mixed
638 * @throws coding_exception
640 function optional_param($parname, $default, $type) {
641 if (func_num_args() != 3 or empty($parname) or empty($type)) {
642 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
645 // POST has precedence.
646 if (isset($_POST[$parname])) {
647 $param = $_POST[$parname];
648 } else if (isset($_GET[$parname])) {
649 $param = $_GET[$parname];
650 } else {
651 return $default;
654 if (is_array($param)) {
655 debugging('Invalid array parameter detected in required_param(): '.$parname);
656 // TODO: switch to $default in Moodle 2.3.
657 return optional_param_array($parname, $default, $type);
660 return clean_param($param, $type);
664 * Returns a particular array value for the named variable, taken from
665 * POST or GET, otherwise returning a given default.
667 * This function should be used to initialise all optional values
668 * in a script that are based on parameters. Usually it will be
669 * used like this:
670 * $ids = optional_param('id', array(), PARAM_INT);
672 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
674 * @param string $parname the name of the page parameter we want
675 * @param mixed $default the default value to return if nothing is found
676 * @param string $type expected type of parameter
677 * @return array
678 * @throws coding_exception
680 function optional_param_array($parname, $default, $type) {
681 if (func_num_args() != 3 or empty($parname) or empty($type)) {
682 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
685 // POST has precedence.
686 if (isset($_POST[$parname])) {
687 $param = $_POST[$parname];
688 } else if (isset($_GET[$parname])) {
689 $param = $_GET[$parname];
690 } else {
691 return $default;
693 if (!is_array($param)) {
694 debugging('optional_param_array() expects array parameters only: '.$parname);
695 return $default;
698 $result = array();
699 foreach ($param as $key => $value) {
700 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
701 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
702 continue;
704 $result[$key] = clean_param($value, $type);
707 return $result;
711 * Strict validation of parameter values, the values are only converted
712 * to requested PHP type. Internally it is using clean_param, the values
713 * before and after cleaning must be equal - otherwise
714 * an invalid_parameter_exception is thrown.
715 * Objects and classes are not accepted.
717 * @param mixed $param
718 * @param string $type PARAM_ constant
719 * @param bool $allownull are nulls valid value?
720 * @param string $debuginfo optional debug information
721 * @return mixed the $param value converted to PHP type
722 * @throws invalid_parameter_exception if $param is not of given type
724 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
725 if (is_null($param)) {
726 if ($allownull == NULL_ALLOWED) {
727 return null;
728 } else {
729 throw new invalid_parameter_exception($debuginfo);
732 if (is_array($param) or is_object($param)) {
733 throw new invalid_parameter_exception($debuginfo);
736 $cleaned = clean_param($param, $type);
738 if ($type == PARAM_FLOAT) {
739 // Do not detect precision loss here.
740 if (is_float($param) or is_int($param)) {
741 // These always fit.
742 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
743 throw new invalid_parameter_exception($debuginfo);
745 } else if ((string)$param !== (string)$cleaned) {
746 // Conversion to string is usually lossless.
747 throw new invalid_parameter_exception($debuginfo);
750 return $cleaned;
754 * Makes sure array contains only the allowed types, this function does not validate array key names!
756 * <code>
757 * $options = clean_param($options, PARAM_INT);
758 * </code>
760 * @param array $param the variable array we are cleaning
761 * @param string $type expected format of param after cleaning.
762 * @param bool $recursive clean recursive arrays
763 * @return array
764 * @throws coding_exception
766 function clean_param_array(array $param = null, $type, $recursive = false) {
767 // Convert null to empty array.
768 $param = (array)$param;
769 foreach ($param as $key => $value) {
770 if (is_array($value)) {
771 if ($recursive) {
772 $param[$key] = clean_param_array($value, $type, true);
773 } else {
774 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
776 } else {
777 $param[$key] = clean_param($value, $type);
780 return $param;
784 * Used by {@link optional_param()} and {@link required_param()} to
785 * clean the variables and/or cast to specific types, based on
786 * an options field.
787 * <code>
788 * $course->format = clean_param($course->format, PARAM_ALPHA);
789 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
790 * </code>
792 * @param mixed $param the variable we are cleaning
793 * @param string $type expected format of param after cleaning.
794 * @return mixed
795 * @throws coding_exception
797 function clean_param($param, $type) {
798 global $CFG;
800 if (is_array($param)) {
801 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
802 } else if (is_object($param)) {
803 if (method_exists($param, '__toString')) {
804 $param = $param->__toString();
805 } else {
806 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
810 switch ($type) {
811 case PARAM_RAW:
812 // No cleaning at all.
813 $param = fix_utf8($param);
814 return $param;
816 case PARAM_RAW_TRIMMED:
817 // No cleaning, but strip leading and trailing whitespace.
818 $param = fix_utf8($param);
819 return trim($param);
821 case PARAM_CLEAN:
822 // General HTML cleaning, try to use more specific type if possible this is deprecated!
823 // Please use more specific type instead.
824 if (is_numeric($param)) {
825 return $param;
827 $param = fix_utf8($param);
828 // Sweep for scripts, etc.
829 return clean_text($param);
831 case PARAM_CLEANHTML:
832 // Clean html fragment.
833 $param = fix_utf8($param);
834 // Sweep for scripts, etc.
835 $param = clean_text($param, FORMAT_HTML);
836 return trim($param);
838 case PARAM_INT:
839 // Convert to integer.
840 return (int)$param;
842 case PARAM_FLOAT:
843 // Convert to float.
844 return (float)$param;
846 case PARAM_ALPHA:
847 // Remove everything not `a-z`.
848 return preg_replace('/[^a-zA-Z]/i', '', $param);
850 case PARAM_ALPHAEXT:
851 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
852 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
854 case PARAM_ALPHANUM:
855 // Remove everything not `a-zA-Z0-9`.
856 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
858 case PARAM_ALPHANUMEXT:
859 // Remove everything not `a-zA-Z0-9_-`.
860 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
862 case PARAM_SEQUENCE:
863 // Remove everything not `0-9,`.
864 return preg_replace('/[^0-9,]/i', '', $param);
866 case PARAM_BOOL:
867 // Convert to 1 or 0.
868 $tempstr = strtolower($param);
869 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
870 $param = 1;
871 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
872 $param = 0;
873 } else {
874 $param = empty($param) ? 0 : 1;
876 return $param;
878 case PARAM_NOTAGS:
879 // Strip all tags.
880 $param = fix_utf8($param);
881 return strip_tags($param);
883 case PARAM_TEXT:
884 // Leave only tags needed for multilang.
885 $param = fix_utf8($param);
886 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
887 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
888 do {
889 if (strpos($param, '</lang>') !== false) {
890 // Old and future mutilang syntax.
891 $param = strip_tags($param, '<lang>');
892 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
893 break;
895 $open = false;
896 foreach ($matches[0] as $match) {
897 if ($match === '</lang>') {
898 if ($open) {
899 $open = false;
900 continue;
901 } else {
902 break 2;
905 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
906 break 2;
907 } else {
908 $open = true;
911 if ($open) {
912 break;
914 return $param;
916 } else if (strpos($param, '</span>') !== false) {
917 // Current problematic multilang syntax.
918 $param = strip_tags($param, '<span>');
919 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
920 break;
922 $open = false;
923 foreach ($matches[0] as $match) {
924 if ($match === '</span>') {
925 if ($open) {
926 $open = false;
927 continue;
928 } else {
929 break 2;
932 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
933 break 2;
934 } else {
935 $open = true;
938 if ($open) {
939 break;
941 return $param;
943 } while (false);
944 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
945 return strip_tags($param);
947 case PARAM_COMPONENT:
948 // We do not want any guessing here, either the name is correct or not
949 // please note only normalised component names are accepted.
950 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
951 return '';
953 if (strpos($param, '__') !== false) {
954 return '';
956 if (strpos($param, 'mod_') === 0) {
957 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
958 if (substr_count($param, '_') != 1) {
959 return '';
962 return $param;
964 case PARAM_PLUGIN:
965 case PARAM_AREA:
966 // We do not want any guessing here, either the name is correct or not.
967 if (!is_valid_plugin_name($param)) {
968 return '';
970 return $param;
972 case PARAM_SAFEDIR:
973 // Remove everything not a-zA-Z0-9_- .
974 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
976 case PARAM_SAFEPATH:
977 // Remove everything not a-zA-Z0-9/_- .
978 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
980 case PARAM_FILE:
981 // Strip all suspicious characters from filename.
982 $param = fix_utf8($param);
983 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
984 if ($param === '.' || $param === '..') {
985 $param = '';
987 return $param;
989 case PARAM_PATH:
990 // Strip all suspicious characters from file path.
991 $param = fix_utf8($param);
992 $param = str_replace('\\', '/', $param);
994 // Explode the path and clean each element using the PARAM_FILE rules.
995 $breadcrumb = explode('/', $param);
996 foreach ($breadcrumb as $key => $crumb) {
997 if ($crumb === '.' && $key === 0) {
998 // Special condition to allow for relative current path such as ./currentdirfile.txt.
999 } else {
1000 $crumb = clean_param($crumb, PARAM_FILE);
1002 $breadcrumb[$key] = $crumb;
1004 $param = implode('/', $breadcrumb);
1006 // Remove multiple current path (./././) and multiple slashes (///).
1007 $param = preg_replace('~//+~', '/', $param);
1008 $param = preg_replace('~/(\./)+~', '/', $param);
1009 return $param;
1011 case PARAM_HOST:
1012 // Allow FQDN or IPv4 dotted quad.
1013 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1014 // Match ipv4 dotted quad.
1015 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1016 // Confirm values are ok.
1017 if ( $match[0] > 255
1018 || $match[1] > 255
1019 || $match[3] > 255
1020 || $match[4] > 255 ) {
1021 // Hmmm, what kind of dotted quad is this?
1022 $param = '';
1024 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1025 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1026 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1028 // All is ok - $param is respected.
1029 } else {
1030 // All is not ok...
1031 $param='';
1033 return $param;
1035 case PARAM_URL:
1036 // Allow safe 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 if ($param === $CFG->wwwroot) {
1053 // Exact match;
1054 } else if (preg_match(':^/:', $param)) {
1055 // Root-relative, ok!
1056 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1057 // Absolute, and matches our wwwroot.
1058 } else {
1059 // Relative - let's make sure there are no tricks.
1060 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1061 // Looks ok.
1062 } else {
1063 $param = '';
1067 return $param;
1069 case PARAM_PEM:
1070 $param = trim($param);
1071 // PEM formatted strings may contain letters/numbers and the symbols:
1072 // forward slash: /
1073 // plus sign: +
1074 // equal sign: =
1075 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1076 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1077 list($wholething, $body) = $matches;
1078 unset($wholething, $matches);
1079 $b64 = clean_param($body, PARAM_BASE64);
1080 if (!empty($b64)) {
1081 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1082 } else {
1083 return '';
1086 return '';
1088 case PARAM_BASE64:
1089 if (!empty($param)) {
1090 // PEM formatted strings may contain letters/numbers and the symbols
1091 // forward slash: /
1092 // plus sign: +
1093 // equal sign: =.
1094 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1095 return '';
1097 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1098 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1099 // than (or equal to) 64 characters long.
1100 for ($i=0, $j=count($lines); $i < $j; $i++) {
1101 if ($i + 1 == $j) {
1102 if (64 < strlen($lines[$i])) {
1103 return '';
1105 continue;
1108 if (64 != strlen($lines[$i])) {
1109 return '';
1112 return implode("\n", $lines);
1113 } else {
1114 return '';
1117 case PARAM_TAG:
1118 $param = fix_utf8($param);
1119 // Please note it is not safe to use the tag name directly anywhere,
1120 // it must be processed with s(), urlencode() before embedding anywhere.
1121 // Remove some nasties.
1122 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1123 // Convert many whitespace chars into one.
1124 $param = preg_replace('/\s+/u', ' ', $param);
1125 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1126 return $param;
1128 case PARAM_TAGLIST:
1129 $param = fix_utf8($param);
1130 $tags = explode(',', $param);
1131 $result = array();
1132 foreach ($tags as $tag) {
1133 $res = clean_param($tag, PARAM_TAG);
1134 if ($res !== '') {
1135 $result[] = $res;
1138 if ($result) {
1139 return implode(',', $result);
1140 } else {
1141 return '';
1144 case PARAM_CAPABILITY:
1145 if (get_capability_info($param)) {
1146 return $param;
1147 } else {
1148 return '';
1151 case PARAM_PERMISSION:
1152 $param = (int)$param;
1153 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1154 return $param;
1155 } else {
1156 return CAP_INHERIT;
1159 case PARAM_AUTH:
1160 $param = clean_param($param, PARAM_PLUGIN);
1161 if (empty($param)) {
1162 return '';
1163 } else if (exists_auth_plugin($param)) {
1164 return $param;
1165 } else {
1166 return '';
1169 case PARAM_LANG:
1170 $param = clean_param($param, PARAM_SAFEDIR);
1171 if (get_string_manager()->translation_exists($param)) {
1172 return $param;
1173 } else {
1174 // Specified language is not installed or param malformed.
1175 return '';
1178 case PARAM_THEME:
1179 $param = clean_param($param, PARAM_PLUGIN);
1180 if (empty($param)) {
1181 return '';
1182 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1183 return $param;
1184 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1185 return $param;
1186 } else {
1187 // Specified theme is not installed.
1188 return '';
1191 case PARAM_USERNAME:
1192 $param = fix_utf8($param);
1193 $param = trim($param);
1194 // Convert uppercase to lowercase MDL-16919.
1195 $param = core_text::strtolower($param);
1196 if (empty($CFG->extendedusernamechars)) {
1197 $param = str_replace(" " , "", $param);
1198 // Regular expression, eliminate all chars EXCEPT:
1199 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1200 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1202 return $param;
1204 case PARAM_EMAIL:
1205 $param = fix_utf8($param);
1206 if (validate_email($param)) {
1207 return $param;
1208 } else {
1209 return '';
1212 case PARAM_STRINGID:
1213 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1214 return $param;
1215 } else {
1216 return '';
1219 case PARAM_TIMEZONE:
1220 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1221 $param = fix_utf8($param);
1222 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1223 if (preg_match($timezonepattern, $param)) {
1224 return $param;
1225 } else {
1226 return '';
1229 default:
1230 // Doh! throw error, switched parameters in optional_param or another serious problem.
1231 print_error("unknownparamtype", '', '', $type);
1236 * Whether the PARAM_* type is compatible in RTL.
1238 * Being compatible with RTL means that the data they contain can flow
1239 * from right-to-left or left-to-right without compromising the user experience.
1241 * Take URLs for example, they are not RTL compatible as they should always
1242 * flow from the left to the right. This also applies to numbers, email addresses,
1243 * configuration snippets, base64 strings, etc...
1245 * This function tries to best guess which parameters can contain localised strings.
1247 * @param string $paramtype Constant PARAM_*.
1248 * @return bool
1250 function is_rtl_compatible($paramtype) {
1251 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1255 * Makes sure the data is using valid utf8, invalid characters are discarded.
1257 * Note: this function is not intended for full objects with methods and private properties.
1259 * @param mixed $value
1260 * @return mixed with proper utf-8 encoding
1262 function fix_utf8($value) {
1263 if (is_null($value) or $value === '') {
1264 return $value;
1266 } else if (is_string($value)) {
1267 if ((string)(int)$value === $value) {
1268 // Shortcut.
1269 return $value;
1271 // No null bytes expected in our data, so let's remove it.
1272 $value = str_replace("\0", '', $value);
1274 // Note: this duplicates min_fix_utf8() intentionally.
1275 static $buggyiconv = null;
1276 if ($buggyiconv === null) {
1277 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1280 if ($buggyiconv) {
1281 if (function_exists('mb_convert_encoding')) {
1282 $subst = mb_substitute_character();
1283 mb_substitute_character('');
1284 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1285 mb_substitute_character($subst);
1287 } else {
1288 // Warn admins on admin/index.php page.
1289 $result = $value;
1292 } else {
1293 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1296 return $result;
1298 } else if (is_array($value)) {
1299 foreach ($value as $k => $v) {
1300 $value[$k] = fix_utf8($v);
1302 return $value;
1304 } else if (is_object($value)) {
1305 // Do not modify original.
1306 $value = clone($value);
1307 foreach ($value as $k => $v) {
1308 $value->$k = fix_utf8($v);
1310 return $value;
1312 } else {
1313 // This is some other type, no utf-8 here.
1314 return $value;
1319 * Return true if given value is integer or string with integer value
1321 * @param mixed $value String or Int
1322 * @return bool true if number, false if not
1324 function is_number($value) {
1325 if (is_int($value)) {
1326 return true;
1327 } else if (is_string($value)) {
1328 return ((string)(int)$value) === $value;
1329 } else {
1330 return false;
1335 * Returns host part from url.
1337 * @param string $url full url
1338 * @return string host, null if not found
1340 function get_host_from_url($url) {
1341 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1342 if ($matches) {
1343 return $matches[1];
1345 return null;
1349 * Tests whether anything was returned by text editor
1351 * This function is useful for testing whether something you got back from
1352 * the HTML editor actually contains anything. Sometimes the HTML editor
1353 * appear to be empty, but actually you get back a <br> tag or something.
1355 * @param string $string a string containing HTML.
1356 * @return boolean does the string contain any actual content - that is text,
1357 * images, objects, etc.
1359 function html_is_blank($string) {
1360 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1364 * Set a key in global configuration
1366 * Set a key/value pair in both this session's {@link $CFG} global variable
1367 * and in the 'config' database table for future sessions.
1369 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1370 * In that case it doesn't affect $CFG.
1372 * A NULL value will delete the entry.
1374 * NOTE: this function is called from lib/db/upgrade.php
1376 * @param string $name the key to set
1377 * @param string $value the value to set (without magic quotes)
1378 * @param string $plugin (optional) the plugin scope, default null
1379 * @return bool true or exception
1381 function set_config($name, $value, $plugin=null) {
1382 global $CFG, $DB;
1384 if (empty($plugin)) {
1385 if (!array_key_exists($name, $CFG->config_php_settings)) {
1386 // So it's defined for this invocation at least.
1387 if (is_null($value)) {
1388 unset($CFG->$name);
1389 } else {
1390 // Settings from db are always strings.
1391 $CFG->$name = (string)$value;
1395 if ($DB->get_field('config', 'name', array('name' => $name))) {
1396 if ($value === null) {
1397 $DB->delete_records('config', array('name' => $name));
1398 } else {
1399 $DB->set_field('config', 'value', $value, array('name' => $name));
1401 } else {
1402 if ($value !== null) {
1403 $config = new stdClass();
1404 $config->name = $name;
1405 $config->value = $value;
1406 $DB->insert_record('config', $config, false);
1409 if ($name === 'siteidentifier') {
1410 cache_helper::update_site_identifier($value);
1412 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1413 } else {
1414 // Plugin scope.
1415 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1416 if ($value===null) {
1417 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1418 } else {
1419 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1421 } else {
1422 if ($value !== null) {
1423 $config = new stdClass();
1424 $config->plugin = $plugin;
1425 $config->name = $name;
1426 $config->value = $value;
1427 $DB->insert_record('config_plugins', $config, false);
1430 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1433 return true;
1437 * Get configuration values from the global config table
1438 * or the config_plugins table.
1440 * If called with one parameter, it will load all the config
1441 * variables for one plugin, and return them as an object.
1443 * If called with 2 parameters it will return a string single
1444 * value or false if the value is not found.
1446 * NOTE: this function is called from lib/db/upgrade.php
1448 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1449 * that we need only fetch it once per request.
1450 * @param string $plugin full component name
1451 * @param string $name default null
1452 * @return mixed hash-like object or single value, return false no config found
1453 * @throws dml_exception
1455 function get_config($plugin, $name = null) {
1456 global $CFG, $DB;
1458 static $siteidentifier = null;
1460 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1461 $forced =& $CFG->config_php_settings;
1462 $iscore = true;
1463 $plugin = 'core';
1464 } else {
1465 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1466 $forced =& $CFG->forced_plugin_settings[$plugin];
1467 } else {
1468 $forced = array();
1470 $iscore = false;
1473 if ($siteidentifier === null) {
1474 try {
1475 // This may fail during installation.
1476 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1477 // install the database.
1478 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1479 } catch (dml_exception $ex) {
1480 // Set siteidentifier to false. We don't want to trip this continually.
1481 $siteidentifier = false;
1482 throw $ex;
1486 if (!empty($name)) {
1487 if (array_key_exists($name, $forced)) {
1488 return (string)$forced[$name];
1489 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1490 return $siteidentifier;
1494 $cache = cache::make('core', 'config');
1495 $result = $cache->get($plugin);
1496 if ($result === false) {
1497 // The user is after a recordset.
1498 if (!$iscore) {
1499 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1500 } else {
1501 // This part is not really used any more, but anyway...
1502 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1504 $cache->set($plugin, $result);
1507 if (!empty($name)) {
1508 if (array_key_exists($name, $result)) {
1509 return $result[$name];
1511 return false;
1514 if ($plugin === 'core') {
1515 $result['siteidentifier'] = $siteidentifier;
1518 foreach ($forced as $key => $value) {
1519 if (is_null($value) or is_array($value) or is_object($value)) {
1520 // We do not want any extra mess here, just real settings that could be saved in db.
1521 unset($result[$key]);
1522 } else {
1523 // Convert to string as if it went through the DB.
1524 $result[$key] = (string)$value;
1528 return (object)$result;
1532 * Removes a key from global configuration.
1534 * NOTE: this function is called from lib/db/upgrade.php
1536 * @param string $name the key to set
1537 * @param string $plugin (optional) the plugin scope
1538 * @return boolean whether the operation succeeded.
1540 function unset_config($name, $plugin=null) {
1541 global $CFG, $DB;
1543 if (empty($plugin)) {
1544 unset($CFG->$name);
1545 $DB->delete_records('config', array('name' => $name));
1546 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1547 } else {
1548 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1549 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1552 return true;
1556 * Remove all the config variables for a given plugin.
1558 * NOTE: this function is called from lib/db/upgrade.php
1560 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1561 * @return boolean whether the operation succeeded.
1563 function unset_all_config_for_plugin($plugin) {
1564 global $DB;
1565 // Delete from the obvious config_plugins first.
1566 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1567 // Next delete any suspect settings from config.
1568 $like = $DB->sql_like('name', '?', true, true, false, '|');
1569 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1570 $DB->delete_records_select('config', $like, $params);
1571 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1572 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1574 return true;
1578 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1580 * All users are verified if they still have the necessary capability.
1582 * @param string $value the value of the config setting.
1583 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1584 * @param bool $includeadmins include administrators.
1585 * @return array of user objects.
1587 function get_users_from_config($value, $capability, $includeadmins = true) {
1588 if (empty($value) or $value === '$@NONE@$') {
1589 return array();
1592 // We have to make sure that users still have the necessary capability,
1593 // it should be faster to fetch them all first and then test if they are present
1594 // instead of validating them one-by-one.
1595 $users = get_users_by_capability(context_system::instance(), $capability);
1596 if ($includeadmins) {
1597 $admins = get_admins();
1598 foreach ($admins as $admin) {
1599 $users[$admin->id] = $admin;
1603 if ($value === '$@ALL@$') {
1604 return $users;
1607 $result = array(); // Result in correct order.
1608 $allowed = explode(',', $value);
1609 foreach ($allowed as $uid) {
1610 if (isset($users[$uid])) {
1611 $user = $users[$uid];
1612 $result[$user->id] = $user;
1616 return $result;
1621 * Invalidates browser caches and cached data in temp.
1623 * @return void
1625 function purge_all_caches() {
1626 purge_caches();
1630 * Selectively invalidate different types of cache.
1632 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1633 * areas alone or in combination.
1635 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1636 * 'muc' Purge MUC caches?
1637 * 'theme' Purge theme cache?
1638 * 'lang' Purge language string cache?
1639 * 'js' Purge javascript cache?
1640 * 'filter' Purge text filter cache?
1641 * 'other' Purge all other caches?
1643 function purge_caches($options = []) {
1644 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'filter', 'other'], false);
1645 if (empty(array_filter($options))) {
1646 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1647 } else {
1648 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1650 if ($options['muc']) {
1651 cache_helper::purge_all();
1653 if ($options['theme']) {
1654 theme_reset_all_caches();
1656 if ($options['lang']) {
1657 get_string_manager()->reset_caches();
1659 if ($options['js']) {
1660 js_reset_all_caches();
1662 if ($options['filter']) {
1663 reset_text_filters_cache();
1665 if ($options['other']) {
1666 purge_other_caches();
1671 * Purge all non-MUC caches not otherwise purged in purge_caches.
1673 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1674 * {@link phpunit_util::reset_dataroot()}
1676 function purge_other_caches() {
1677 global $DB, $CFG;
1678 core_text::reset_caches();
1679 if (class_exists('core_plugin_manager')) {
1680 core_plugin_manager::reset_caches();
1683 // Bump up cacherev field for all courses.
1684 try {
1685 increment_revision_number('course', 'cacherev', '');
1686 } catch (moodle_exception $e) {
1687 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1690 $DB->reset_caches();
1692 // Purge all other caches: rss, simplepie, etc.
1693 clearstatcache();
1694 remove_dir($CFG->cachedir.'', true);
1696 // Make sure cache dir is writable, throws exception if not.
1697 make_cache_directory('');
1699 // This is the only place where we purge local caches, we are only adding files there.
1700 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1701 remove_dir($CFG->localcachedir, true);
1702 set_config('localcachedirpurged', time());
1703 make_localcache_directory('', true);
1704 \core\task\manager::clear_static_caches();
1708 * Get volatile flags
1710 * @param string $type
1711 * @param int $changedsince default null
1712 * @return array records array
1714 function get_cache_flags($type, $changedsince = null) {
1715 global $DB;
1717 $params = array('type' => $type, 'expiry' => time());
1718 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1719 if ($changedsince !== null) {
1720 $params['changedsince'] = $changedsince;
1721 $sqlwhere .= " AND timemodified > :changedsince";
1723 $cf = array();
1724 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1725 foreach ($flags as $flag) {
1726 $cf[$flag->name] = $flag->value;
1729 return $cf;
1733 * Get volatile flags
1735 * @param string $type
1736 * @param string $name
1737 * @param int $changedsince default null
1738 * @return string|false The cache flag value or false
1740 function get_cache_flag($type, $name, $changedsince=null) {
1741 global $DB;
1743 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1745 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1746 if ($changedsince !== null) {
1747 $params['changedsince'] = $changedsince;
1748 $sqlwhere .= " AND timemodified > :changedsince";
1751 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1755 * Set a volatile flag
1757 * @param string $type the "type" namespace for the key
1758 * @param string $name the key to set
1759 * @param string $value the value to set (without magic quotes) - null will remove the flag
1760 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1761 * @return bool Always returns true
1763 function set_cache_flag($type, $name, $value, $expiry = null) {
1764 global $DB;
1766 $timemodified = time();
1767 if ($expiry === null || $expiry < $timemodified) {
1768 $expiry = $timemodified + 24 * 60 * 60;
1769 } else {
1770 $expiry = (int)$expiry;
1773 if ($value === null) {
1774 unset_cache_flag($type, $name);
1775 return true;
1778 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1779 // This is a potential problem in DEBUG_DEVELOPER.
1780 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1781 return true; // No need to update.
1783 $f->value = $value;
1784 $f->expiry = $expiry;
1785 $f->timemodified = $timemodified;
1786 $DB->update_record('cache_flags', $f);
1787 } else {
1788 $f = new stdClass();
1789 $f->flagtype = $type;
1790 $f->name = $name;
1791 $f->value = $value;
1792 $f->expiry = $expiry;
1793 $f->timemodified = $timemodified;
1794 $DB->insert_record('cache_flags', $f);
1796 return true;
1800 * Removes a single volatile flag
1802 * @param string $type the "type" namespace for the key
1803 * @param string $name the key to set
1804 * @return bool
1806 function unset_cache_flag($type, $name) {
1807 global $DB;
1808 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1809 return true;
1813 * Garbage-collect volatile flags
1815 * @return bool Always returns true
1817 function gc_cache_flags() {
1818 global $DB;
1819 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1820 return true;
1823 // USER PREFERENCE API.
1826 * Refresh user preference cache. This is used most often for $USER
1827 * object that is stored in session, but it also helps with performance in cron script.
1829 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1831 * @package core
1832 * @category preference
1833 * @access public
1834 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1835 * @param int $cachelifetime Cache life time on the current page (in seconds)
1836 * @throws coding_exception
1837 * @return null
1839 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1840 global $DB;
1841 // Static cache, we need to check on each page load, not only every 2 minutes.
1842 static $loadedusers = array();
1844 if (!isset($user->id)) {
1845 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1848 if (empty($user->id) or isguestuser($user->id)) {
1849 // No permanent storage for not-logged-in users and guest.
1850 if (!isset($user->preference)) {
1851 $user->preference = array();
1853 return;
1856 $timenow = time();
1858 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1859 // Already loaded at least once on this page. Are we up to date?
1860 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1861 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1862 return;
1864 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1865 // No change since the lastcheck on this page.
1866 $user->preference['_lastloaded'] = $timenow;
1867 return;
1871 // OK, so we have to reload all preferences.
1872 $loadedusers[$user->id] = true;
1873 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1874 $user->preference['_lastloaded'] = $timenow;
1878 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1880 * NOTE: internal function, do not call from other code.
1882 * @package core
1883 * @access private
1884 * @param integer $userid the user whose prefs were changed.
1886 function mark_user_preferences_changed($userid) {
1887 global $CFG;
1889 if (empty($userid) or isguestuser($userid)) {
1890 // No cache flags for guest and not-logged-in users.
1891 return;
1894 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1898 * Sets a preference for the specified user.
1900 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1902 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1904 * @package core
1905 * @category preference
1906 * @access public
1907 * @param string $name The key to set as preference for the specified user
1908 * @param string $value The value to set for the $name key in the specified user's
1909 * record, null means delete current value.
1910 * @param stdClass|int|null $user A moodle user object or id, null means current user
1911 * @throws coding_exception
1912 * @return bool Always true or exception
1914 function set_user_preference($name, $value, $user = null) {
1915 global $USER, $DB;
1917 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1918 throw new coding_exception('Invalid preference name in set_user_preference() call');
1921 if (is_null($value)) {
1922 // Null means delete current.
1923 return unset_user_preference($name, $user);
1924 } else if (is_object($value)) {
1925 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1926 } else if (is_array($value)) {
1927 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1929 // Value column maximum length is 1333 characters.
1930 $value = (string)$value;
1931 if (core_text::strlen($value) > 1333) {
1932 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1935 if (is_null($user)) {
1936 $user = $USER;
1937 } else if (isset($user->id)) {
1938 // It is a valid object.
1939 } else if (is_numeric($user)) {
1940 $user = (object)array('id' => (int)$user);
1941 } else {
1942 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1945 check_user_preferences_loaded($user);
1947 if (empty($user->id) or isguestuser($user->id)) {
1948 // No permanent storage for not-logged-in users and guest.
1949 $user->preference[$name] = $value;
1950 return true;
1953 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1954 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1955 // Preference already set to this value.
1956 return true;
1958 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1960 } else {
1961 $preference = new stdClass();
1962 $preference->userid = $user->id;
1963 $preference->name = $name;
1964 $preference->value = $value;
1965 $DB->insert_record('user_preferences', $preference);
1968 // Update value in cache.
1969 $user->preference[$name] = $value;
1970 // Update the $USER in case where we've not a direct reference to $USER.
1971 if ($user !== $USER && $user->id == $USER->id) {
1972 $USER->preference[$name] = $value;
1975 // Set reload flag for other sessions.
1976 mark_user_preferences_changed($user->id);
1978 return true;
1982 * Sets a whole array of preferences for the current user
1984 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1986 * @package core
1987 * @category preference
1988 * @access public
1989 * @param array $prefarray An array of key/value pairs to be set
1990 * @param stdClass|int|null $user A moodle user object or id, null means current user
1991 * @return bool Always true or exception
1993 function set_user_preferences(array $prefarray, $user = null) {
1994 foreach ($prefarray as $name => $value) {
1995 set_user_preference($name, $value, $user);
1997 return true;
2001 * Unsets a preference completely by deleting it from the database
2003 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2005 * @package core
2006 * @category preference
2007 * @access public
2008 * @param string $name The key to unset as preference for the specified user
2009 * @param stdClass|int|null $user A moodle user object or id, null means current user
2010 * @throws coding_exception
2011 * @return bool Always true or exception
2013 function unset_user_preference($name, $user = null) {
2014 global $USER, $DB;
2016 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2017 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2020 if (is_null($user)) {
2021 $user = $USER;
2022 } else if (isset($user->id)) {
2023 // It is a valid object.
2024 } else if (is_numeric($user)) {
2025 $user = (object)array('id' => (int)$user);
2026 } else {
2027 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2030 check_user_preferences_loaded($user);
2032 if (empty($user->id) or isguestuser($user->id)) {
2033 // No permanent storage for not-logged-in user and guest.
2034 unset($user->preference[$name]);
2035 return true;
2038 // Delete from DB.
2039 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2041 // Delete the preference from cache.
2042 unset($user->preference[$name]);
2043 // Update the $USER in case where we've not a direct reference to $USER.
2044 if ($user !== $USER && $user->id == $USER->id) {
2045 unset($USER->preference[$name]);
2048 // Set reload flag for other sessions.
2049 mark_user_preferences_changed($user->id);
2051 return true;
2055 * Used to fetch user preference(s)
2057 * If no arguments are supplied this function will return
2058 * all of the current user preferences as an array.
2060 * If a name is specified then this function
2061 * attempts to return that particular preference value. If
2062 * none is found, then the optional value $default is returned,
2063 * otherwise null.
2065 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2067 * @package core
2068 * @category preference
2069 * @access public
2070 * @param string $name Name of the key to use in finding a preference value
2071 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2072 * @param stdClass|int|null $user A moodle user object or id, null means current user
2073 * @throws coding_exception
2074 * @return string|mixed|null A string containing the value of a single preference. An
2075 * array with all of the preferences or null
2077 function get_user_preferences($name = null, $default = null, $user = null) {
2078 global $USER;
2080 if (is_null($name)) {
2081 // All prefs.
2082 } else if (is_numeric($name) or $name === '_lastloaded') {
2083 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2086 if (is_null($user)) {
2087 $user = $USER;
2088 } else if (isset($user->id)) {
2089 // Is a valid object.
2090 } else if (is_numeric($user)) {
2091 $user = (object)array('id' => (int)$user);
2092 } else {
2093 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2096 check_user_preferences_loaded($user);
2098 if (empty($name)) {
2099 // All values.
2100 return $user->preference;
2101 } else if (isset($user->preference[$name])) {
2102 // The single string value.
2103 return $user->preference[$name];
2104 } else {
2105 // Default value (null if not specified).
2106 return $default;
2110 // FUNCTIONS FOR HANDLING TIME.
2113 * Given Gregorian date parts in user time produce a GMT timestamp.
2115 * @package core
2116 * @category time
2117 * @param int $year The year part to create timestamp of
2118 * @param int $month The month part to create timestamp of
2119 * @param int $day The day part to create timestamp of
2120 * @param int $hour The hour part to create timestamp of
2121 * @param int $minute The minute part to create timestamp of
2122 * @param int $second The second part to create timestamp of
2123 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2124 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2125 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2126 * applied only if timezone is 99 or string.
2127 * @return int GMT timestamp
2129 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2130 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2131 $date->setDate((int)$year, (int)$month, (int)$day);
2132 $date->setTime((int)$hour, (int)$minute, (int)$second);
2134 $time = $date->getTimestamp();
2136 if ($time === false) {
2137 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2138 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2141 // Moodle BC DST stuff.
2142 if (!$applydst) {
2143 $time += dst_offset_on($time, $timezone);
2146 return $time;
2151 * Format a date/time (seconds) as weeks, days, hours etc as needed
2153 * Given an amount of time in seconds, returns string
2154 * formatted nicely as years, days, hours etc as needed
2156 * @package core
2157 * @category time
2158 * @uses MINSECS
2159 * @uses HOURSECS
2160 * @uses DAYSECS
2161 * @uses YEARSECS
2162 * @param int $totalsecs Time in seconds
2163 * @param stdClass $str Should be a time object
2164 * @return string A nicely formatted date/time string
2166 function format_time($totalsecs, $str = null) {
2168 $totalsecs = abs($totalsecs);
2170 if (!$str) {
2171 // Create the str structure the slow way.
2172 $str = new stdClass();
2173 $str->day = get_string('day');
2174 $str->days = get_string('days');
2175 $str->hour = get_string('hour');
2176 $str->hours = get_string('hours');
2177 $str->min = get_string('min');
2178 $str->mins = get_string('mins');
2179 $str->sec = get_string('sec');
2180 $str->secs = get_string('secs');
2181 $str->year = get_string('year');
2182 $str->years = get_string('years');
2185 $years = floor($totalsecs/YEARSECS);
2186 $remainder = $totalsecs - ($years*YEARSECS);
2187 $days = floor($remainder/DAYSECS);
2188 $remainder = $totalsecs - ($days*DAYSECS);
2189 $hours = floor($remainder/HOURSECS);
2190 $remainder = $remainder - ($hours*HOURSECS);
2191 $mins = floor($remainder/MINSECS);
2192 $secs = $remainder - ($mins*MINSECS);
2194 $ss = ($secs == 1) ? $str->sec : $str->secs;
2195 $sm = ($mins == 1) ? $str->min : $str->mins;
2196 $sh = ($hours == 1) ? $str->hour : $str->hours;
2197 $sd = ($days == 1) ? $str->day : $str->days;
2198 $sy = ($years == 1) ? $str->year : $str->years;
2200 $oyears = '';
2201 $odays = '';
2202 $ohours = '';
2203 $omins = '';
2204 $osecs = '';
2206 if ($years) {
2207 $oyears = $years .' '. $sy;
2209 if ($days) {
2210 $odays = $days .' '. $sd;
2212 if ($hours) {
2213 $ohours = $hours .' '. $sh;
2215 if ($mins) {
2216 $omins = $mins .' '. $sm;
2218 if ($secs) {
2219 $osecs = $secs .' '. $ss;
2222 if ($years) {
2223 return trim($oyears .' '. $odays);
2225 if ($days) {
2226 return trim($odays .' '. $ohours);
2228 if ($hours) {
2229 return trim($ohours .' '. $omins);
2231 if ($mins) {
2232 return trim($omins .' '. $osecs);
2234 if ($secs) {
2235 return $osecs;
2237 return get_string('now');
2241 * Returns a formatted string that represents a date in user time.
2243 * @package core
2244 * @category time
2245 * @param int $date the timestamp in UTC, as obtained from the database.
2246 * @param string $format strftime format. You should probably get this using
2247 * get_string('strftime...', 'langconfig');
2248 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2249 * not 99 then daylight saving will not be added.
2250 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2251 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2252 * If false then the leading zero is maintained.
2253 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2254 * @return string the formatted date/time.
2256 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2257 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2258 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2262 * Returns a formatted date ensuring it is UTF-8.
2264 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2265 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2267 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2268 * @param string $format strftime format.
2269 * @param int|float|string $tz the user timezone
2270 * @return string the formatted date/time.
2271 * @since Moodle 2.3.3
2273 function date_format_string($date, $format, $tz = 99) {
2274 global $CFG;
2276 $localewincharset = null;
2277 // Get the calendar type user is using.
2278 if ($CFG->ostype == 'WINDOWS') {
2279 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2280 $localewincharset = $calendartype->locale_win_charset();
2283 if ($localewincharset) {
2284 $format = core_text::convert($format, 'utf-8', $localewincharset);
2287 date_default_timezone_set(core_date::get_user_timezone($tz));
2288 $datestring = strftime($format, $date);
2289 core_date::set_default_server_timezone();
2291 if ($localewincharset) {
2292 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2295 return $datestring;
2299 * Given a $time timestamp in GMT (seconds since epoch),
2300 * returns an array that represents the Gregorian date in user time
2302 * @package core
2303 * @category time
2304 * @param int $time Timestamp in GMT
2305 * @param float|int|string $timezone user timezone
2306 * @return array An array that represents the date in user time
2308 function usergetdate($time, $timezone=99) {
2309 date_default_timezone_set(core_date::get_user_timezone($timezone));
2310 $result = getdate($time);
2311 core_date::set_default_server_timezone();
2313 return $result;
2317 * Given a GMT timestamp (seconds since epoch), offsets it by
2318 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2320 * NOTE: this function does not include DST properly,
2321 * you should use the PHP date stuff instead!
2323 * @package core
2324 * @category time
2325 * @param int $date Timestamp in GMT
2326 * @param float|int|string $timezone user timezone
2327 * @return int
2329 function usertime($date, $timezone=99) {
2330 $userdate = new DateTime('@' . $date);
2331 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2332 $dst = dst_offset_on($date, $timezone);
2334 return $date - $userdate->getOffset() + $dst;
2338 * Given a time, return the GMT timestamp of the most recent midnight
2339 * for the current user.
2341 * @package core
2342 * @category time
2343 * @param int $date Timestamp in GMT
2344 * @param float|int|string $timezone user timezone
2345 * @return int Returns a GMT timestamp
2347 function usergetmidnight($date, $timezone=99) {
2349 $userdate = usergetdate($date, $timezone);
2351 // Time of midnight of this user's day, in GMT.
2352 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2357 * Returns a string that prints the user's timezone
2359 * @package core
2360 * @category time
2361 * @param float|int|string $timezone user timezone
2362 * @return string
2364 function usertimezone($timezone=99) {
2365 $tz = core_date::get_user_timezone($timezone);
2366 return core_date::get_localised_timezone($tz);
2370 * Returns a float or a string which denotes the user's timezone
2371 * 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)
2372 * means that for this timezone there are also DST rules to be taken into account
2373 * Checks various settings and picks the most dominant of those which have a value
2375 * @package core
2376 * @category time
2377 * @param float|int|string $tz timezone to calculate GMT time offset before
2378 * calculating user timezone, 99 is default user timezone
2379 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2380 * @return float|string
2382 function get_user_timezone($tz = 99) {
2383 global $USER, $CFG;
2385 $timezones = array(
2386 $tz,
2387 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2388 isset($USER->timezone) ? $USER->timezone : 99,
2389 isset($CFG->timezone) ? $CFG->timezone : 99,
2392 $tz = 99;
2394 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2395 foreach ($timezones as $nextvalue) {
2396 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2397 $tz = $nextvalue;
2400 return is_numeric($tz) ? (float) $tz : $tz;
2404 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2405 * - Note: Daylight saving only works for string timezones and not for float.
2407 * @package core
2408 * @category time
2409 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2410 * @param int|float|string $strtimezone user timezone
2411 * @return int
2413 function dst_offset_on($time, $strtimezone = null) {
2414 $tz = core_date::get_user_timezone($strtimezone);
2415 $date = new DateTime('@' . $time);
2416 $date->setTimezone(new DateTimeZone($tz));
2417 if ($date->format('I') == '1') {
2418 if ($tz === 'Australia/Lord_Howe') {
2419 return 1800;
2421 return 3600;
2423 return 0;
2427 * Calculates when the day appears in specific month
2429 * @package core
2430 * @category time
2431 * @param int $startday starting day of the month
2432 * @param int $weekday The day when week starts (normally taken from user preferences)
2433 * @param int $month The month whose day is sought
2434 * @param int $year The year of the month whose day is sought
2435 * @return int
2437 function find_day_in_month($startday, $weekday, $month, $year) {
2438 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2440 $daysinmonth = days_in_month($month, $year);
2441 $daysinweek = count($calendartype->get_weekdays());
2443 if ($weekday == -1) {
2444 // Don't care about weekday, so return:
2445 // abs($startday) if $startday != -1
2446 // $daysinmonth otherwise.
2447 return ($startday == -1) ? $daysinmonth : abs($startday);
2450 // From now on we 're looking for a specific weekday.
2451 // Give "end of month" its actual value, since we know it.
2452 if ($startday == -1) {
2453 $startday = -1 * $daysinmonth;
2456 // Starting from day $startday, the sign is the direction.
2457 if ($startday < 1) {
2458 $startday = abs($startday);
2459 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2461 // This is the last such weekday of the month.
2462 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2463 if ($lastinmonth > $daysinmonth) {
2464 $lastinmonth -= $daysinweek;
2467 // Find the first such weekday <= $startday.
2468 while ($lastinmonth > $startday) {
2469 $lastinmonth -= $daysinweek;
2472 return $lastinmonth;
2473 } else {
2474 $indexweekday = dayofweek($startday, $month, $year);
2476 $diff = $weekday - $indexweekday;
2477 if ($diff < 0) {
2478 $diff += $daysinweek;
2481 // This is the first such weekday of the month equal to or after $startday.
2482 $firstfromindex = $startday + $diff;
2484 return $firstfromindex;
2489 * Calculate the number of days in a given month
2491 * @package core
2492 * @category time
2493 * @param int $month The month whose day count is sought
2494 * @param int $year The year of the month whose day count is sought
2495 * @return int
2497 function days_in_month($month, $year) {
2498 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2499 return $calendartype->get_num_days_in_month($year, $month);
2503 * Calculate the position in the week of a specific calendar day
2505 * @package core
2506 * @category time
2507 * @param int $day The day of the date whose position in the week is sought
2508 * @param int $month The month of the date whose position in the week is sought
2509 * @param int $year The year of the date whose position in the week is sought
2510 * @return int
2512 function dayofweek($day, $month, $year) {
2513 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2514 return $calendartype->get_weekday($year, $month, $day);
2517 // USER AUTHENTICATION AND LOGIN.
2520 * Returns full login url.
2522 * @return string login url
2524 function get_login_url() {
2525 global $CFG;
2527 return "$CFG->wwwroot/login/index.php";
2531 * This function checks that the current user is logged in and has the
2532 * required privileges
2534 * This function checks that the current user is logged in, and optionally
2535 * whether they are allowed to be in a particular course and view a particular
2536 * course module.
2537 * If they are not logged in, then it redirects them to the site login unless
2538 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2539 * case they are automatically logged in as guests.
2540 * If $courseid is given and the user is not enrolled in that course then the
2541 * user is redirected to the course enrolment page.
2542 * If $cm is given and the course module is hidden and the user is not a teacher
2543 * in the course then the user is redirected to the course home page.
2545 * When $cm parameter specified, this function sets page layout to 'module'.
2546 * You need to change it manually later if some other layout needed.
2548 * @package core_access
2549 * @category access
2551 * @param mixed $courseorid id of the course or course object
2552 * @param bool $autologinguest default true
2553 * @param object $cm course module object
2554 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2555 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2556 * in order to keep redirects working properly. MDL-14495
2557 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2558 * @return mixed Void, exit, and die depending on path
2559 * @throws coding_exception
2560 * @throws require_login_exception
2561 * @throws moodle_exception
2563 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2564 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2566 // Must not redirect when byteserving already started.
2567 if (!empty($_SERVER['HTTP_RANGE'])) {
2568 $preventredirect = true;
2571 if (AJAX_SCRIPT) {
2572 // We cannot redirect for AJAX scripts either.
2573 $preventredirect = true;
2576 // Setup global $COURSE, themes, language and locale.
2577 if (!empty($courseorid)) {
2578 if (is_object($courseorid)) {
2579 $course = $courseorid;
2580 } else if ($courseorid == SITEID) {
2581 $course = clone($SITE);
2582 } else {
2583 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2585 if ($cm) {
2586 if ($cm->course != $course->id) {
2587 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2589 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2590 if (!($cm instanceof cm_info)) {
2591 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2592 // db queries so this is not really a performance concern, however it is obviously
2593 // better if you use get_fast_modinfo to get the cm before calling this.
2594 $modinfo = get_fast_modinfo($course);
2595 $cm = $modinfo->get_cm($cm->id);
2598 } else {
2599 // Do not touch global $COURSE via $PAGE->set_course(),
2600 // the reasons is we need to be able to call require_login() at any time!!
2601 $course = $SITE;
2602 if ($cm) {
2603 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2607 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2608 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2609 // risk leading the user back to the AJAX request URL.
2610 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2611 $setwantsurltome = false;
2614 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2615 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2616 if ($preventredirect) {
2617 throw new require_login_session_timeout_exception();
2618 } else {
2619 if ($setwantsurltome) {
2620 $SESSION->wantsurl = qualified_me();
2622 redirect(get_login_url());
2626 // If the user is not even logged in yet then make sure they are.
2627 if (!isloggedin()) {
2628 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2629 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2630 // Misconfigured site guest, just redirect to login page.
2631 redirect(get_login_url());
2632 exit; // Never reached.
2634 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2635 complete_user_login($guest);
2636 $USER->autologinguest = true;
2637 $SESSION->lang = $lang;
2638 } else {
2639 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2640 if ($preventredirect) {
2641 throw new require_login_exception('You are not logged in');
2644 if ($setwantsurltome) {
2645 $SESSION->wantsurl = qualified_me();
2648 $referer = get_local_referer(false);
2649 if (!empty($referer)) {
2650 $SESSION->fromurl = $referer;
2653 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2654 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2655 foreach($authsequence as $authname) {
2656 $authplugin = get_auth_plugin($authname);
2657 $authplugin->pre_loginpage_hook();
2658 if (isloggedin()) {
2659 break;
2663 // If we're still not logged in then go to the login page
2664 if (!isloggedin()) {
2665 redirect(get_login_url());
2666 exit; // Never reached.
2671 // Loginas as redirection if needed.
2672 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2673 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2674 if ($USER->loginascontext->instanceid != $course->id) {
2675 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2680 // Check whether the user should be changing password (but only if it is REALLY them).
2681 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2682 $userauth = get_auth_plugin($USER->auth);
2683 if ($userauth->can_change_password() and !$preventredirect) {
2684 if ($setwantsurltome) {
2685 $SESSION->wantsurl = qualified_me();
2687 if ($changeurl = $userauth->change_password_url()) {
2688 // Use plugin custom url.
2689 redirect($changeurl);
2690 } else {
2691 // Use moodle internal method.
2692 redirect($CFG->wwwroot .'/login/change_password.php');
2694 } else if ($userauth->can_change_password()) {
2695 throw new moodle_exception('forcepasswordchangenotice');
2696 } else {
2697 throw new moodle_exception('nopasswordchangeforced', 'auth');
2701 // Check that the user account is properly set up. If we can't redirect to
2702 // edit their profile and this is not a WS request, perform just the lax check.
2703 // It will allow them to use filepicker on the profile edit page.
2705 if ($preventredirect && !WS_SERVER) {
2706 $usernotfullysetup = user_not_fully_set_up($USER, false);
2707 } else {
2708 $usernotfullysetup = user_not_fully_set_up($USER, true);
2711 if ($usernotfullysetup) {
2712 if ($preventredirect) {
2713 throw new moodle_exception('usernotfullysetup');
2715 if ($setwantsurltome) {
2716 $SESSION->wantsurl = qualified_me();
2718 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2721 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2722 sesskey();
2724 // Do not bother admins with any formalities, except for activities pending deletion.
2725 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2726 // Set the global $COURSE.
2727 if ($cm) {
2728 $PAGE->set_cm($cm, $course);
2729 $PAGE->set_pagelayout('incourse');
2730 } else if (!empty($courseorid)) {
2731 $PAGE->set_course($course);
2733 // Set accesstime or the user will appear offline which messes up messaging.
2734 user_accesstime_log($course->id);
2735 return;
2738 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2739 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2740 if (!defined('NO_SITEPOLICY_CHECK')) {
2741 define('NO_SITEPOLICY_CHECK', false);
2744 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2745 // Do not test if the script explicitly asked for skipping the site policies check.
2746 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2747 $manager = new \core_privacy\local\sitepolicy\manager();
2748 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2749 if ($preventredirect) {
2750 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2752 if ($setwantsurltome) {
2753 $SESSION->wantsurl = qualified_me();
2755 redirect($policyurl);
2759 // Fetch the system context, the course context, and prefetch its child contexts.
2760 $sysctx = context_system::instance();
2761 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2762 if ($cm) {
2763 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2764 } else {
2765 $cmcontext = null;
2768 // If the site is currently under maintenance, then print a message.
2769 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2770 if ($preventredirect) {
2771 throw new require_login_exception('Maintenance in progress');
2773 $PAGE->set_context(null);
2774 print_maintenance_message();
2777 // Make sure the course itself is not hidden.
2778 if ($course->id == SITEID) {
2779 // Frontpage can not be hidden.
2780 } else {
2781 if (is_role_switched($course->id)) {
2782 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2783 } else {
2784 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2785 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2786 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2787 if ($preventredirect) {
2788 throw new require_login_exception('Course is hidden');
2790 $PAGE->set_context(null);
2791 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2792 // the navigation will mess up when trying to find it.
2793 navigation_node::override_active_url(new moodle_url('/'));
2794 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2799 // Is the user enrolled?
2800 if ($course->id == SITEID) {
2801 // Everybody is enrolled on the frontpage.
2802 } else {
2803 if (\core\session\manager::is_loggedinas()) {
2804 // Make sure the REAL person can access this course first.
2805 $realuser = \core\session\manager::get_realuser();
2806 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2807 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2808 if ($preventredirect) {
2809 throw new require_login_exception('Invalid course login-as access');
2811 $PAGE->set_context(null);
2812 echo $OUTPUT->header();
2813 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2817 $access = false;
2819 if (is_role_switched($course->id)) {
2820 // Ok, user had to be inside this course before the switch.
2821 $access = true;
2823 } else if (is_viewing($coursecontext, $USER)) {
2824 // Ok, no need to mess with enrol.
2825 $access = true;
2827 } else {
2828 if (isset($USER->enrol['enrolled'][$course->id])) {
2829 if ($USER->enrol['enrolled'][$course->id] > time()) {
2830 $access = true;
2831 if (isset($USER->enrol['tempguest'][$course->id])) {
2832 unset($USER->enrol['tempguest'][$course->id]);
2833 remove_temp_course_roles($coursecontext);
2835 } else {
2836 // Expired.
2837 unset($USER->enrol['enrolled'][$course->id]);
2840 if (isset($USER->enrol['tempguest'][$course->id])) {
2841 if ($USER->enrol['tempguest'][$course->id] == 0) {
2842 $access = true;
2843 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2844 $access = true;
2845 } else {
2846 // Expired.
2847 unset($USER->enrol['tempguest'][$course->id]);
2848 remove_temp_course_roles($coursecontext);
2852 if (!$access) {
2853 // Cache not ok.
2854 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2855 if ($until !== false) {
2856 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2857 if ($until == 0) {
2858 $until = ENROL_MAX_TIMESTAMP;
2860 $USER->enrol['enrolled'][$course->id] = $until;
2861 $access = true;
2863 } else {
2864 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2865 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2866 $enrols = enrol_get_plugins(true);
2867 // First ask all enabled enrol instances in course if they want to auto enrol user.
2868 foreach ($instances as $instance) {
2869 if (!isset($enrols[$instance->enrol])) {
2870 continue;
2872 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2873 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2874 if ($until !== false) {
2875 if ($until == 0) {
2876 $until = ENROL_MAX_TIMESTAMP;
2878 $USER->enrol['enrolled'][$course->id] = $until;
2879 $access = true;
2880 break;
2883 // If not enrolled yet try to gain temporary guest access.
2884 if (!$access) {
2885 foreach ($instances as $instance) {
2886 if (!isset($enrols[$instance->enrol])) {
2887 continue;
2889 // Get a duration for the guest access, a timestamp in the future or false.
2890 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2891 if ($until !== false and $until > time()) {
2892 $USER->enrol['tempguest'][$course->id] = $until;
2893 $access = true;
2894 break;
2902 if (!$access) {
2903 if ($preventredirect) {
2904 throw new require_login_exception('Not enrolled');
2906 if ($setwantsurltome) {
2907 $SESSION->wantsurl = qualified_me();
2909 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2913 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
2914 if ($cm && $cm->deletioninprogress) {
2915 if ($preventredirect) {
2916 throw new moodle_exception('activityisscheduledfordeletion');
2918 require_once($CFG->dirroot . '/course/lib.php');
2919 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
2922 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2923 if ($cm && !$cm->uservisible) {
2924 if ($preventredirect) {
2925 throw new require_login_exception('Activity is hidden');
2927 // Get the error message that activity is not available and why (if explanation can be shown to the user).
2928 $PAGE->set_course($course);
2929 $renderer = $PAGE->get_renderer('course');
2930 $message = $renderer->course_section_cm_unavailable_error_message($cm);
2931 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
2934 // Set the global $COURSE.
2935 if ($cm) {
2936 $PAGE->set_cm($cm, $course);
2937 $PAGE->set_pagelayout('incourse');
2938 } else if (!empty($courseorid)) {
2939 $PAGE->set_course($course);
2942 // Finally access granted, update lastaccess times.
2943 user_accesstime_log($course->id);
2948 * This function just makes sure a user is logged out.
2950 * @package core_access
2951 * @category access
2953 function require_logout() {
2954 global $USER, $DB;
2956 if (!isloggedin()) {
2957 // This should not happen often, no need for hooks or events here.
2958 \core\session\manager::terminate_current();
2959 return;
2962 // Execute hooks before action.
2963 $authplugins = array();
2964 $authsequence = get_enabled_auth_plugins();
2965 foreach ($authsequence as $authname) {
2966 $authplugins[$authname] = get_auth_plugin($authname);
2967 $authplugins[$authname]->prelogout_hook();
2970 // Store info that gets removed during logout.
2971 $sid = session_id();
2972 $event = \core\event\user_loggedout::create(
2973 array(
2974 'userid' => $USER->id,
2975 'objectid' => $USER->id,
2976 'other' => array('sessionid' => $sid),
2979 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2980 $event->add_record_snapshot('sessions', $session);
2983 // Clone of $USER object to be used by auth plugins.
2984 $user = fullclone($USER);
2986 // Delete session record and drop $_SESSION content.
2987 \core\session\manager::terminate_current();
2989 // Trigger event AFTER action.
2990 $event->trigger();
2992 // Hook to execute auth plugins redirection after event trigger.
2993 foreach ($authplugins as $authplugin) {
2994 $authplugin->postlogout_hook($user);
2999 * Weaker version of require_login()
3001 * This is a weaker version of {@link require_login()} which only requires login
3002 * when called from within a course rather than the site page, unless
3003 * the forcelogin option is turned on.
3004 * @see require_login()
3006 * @package core_access
3007 * @category access
3009 * @param mixed $courseorid The course object or id in question
3010 * @param bool $autologinguest Allow autologin guests if that is wanted
3011 * @param object $cm Course activity module if known
3012 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3013 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3014 * in order to keep redirects working properly. MDL-14495
3015 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3016 * @return void
3017 * @throws coding_exception
3019 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3020 global $CFG, $PAGE, $SITE;
3021 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3022 or (!is_object($courseorid) and $courseorid == SITEID));
3023 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3024 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3025 // db queries so this is not really a performance concern, however it is obviously
3026 // better if you use get_fast_modinfo to get the cm before calling this.
3027 if (is_object($courseorid)) {
3028 $course = $courseorid;
3029 } else {
3030 $course = clone($SITE);
3032 $modinfo = get_fast_modinfo($course);
3033 $cm = $modinfo->get_cm($cm->id);
3035 if (!empty($CFG->forcelogin)) {
3036 // Login required for both SITE and courses.
3037 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3039 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3040 // Always login for hidden activities.
3041 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3043 } else if (isloggedin() && !isguestuser()) {
3044 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3045 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3047 } else if ($issite) {
3048 // Login for SITE not required.
3049 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3050 if (!empty($courseorid)) {
3051 if (is_object($courseorid)) {
3052 $course = $courseorid;
3053 } else {
3054 $course = clone $SITE;
3056 if ($cm) {
3057 if ($cm->course != $course->id) {
3058 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3060 $PAGE->set_cm($cm, $course);
3061 $PAGE->set_pagelayout('incourse');
3062 } else {
3063 $PAGE->set_course($course);
3065 } else {
3066 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3067 $PAGE->set_course($PAGE->course);
3069 user_accesstime_log(SITEID);
3070 return;
3072 } else {
3073 // Course login always required.
3074 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3079 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3081 * @param string $keyvalue the key value
3082 * @param string $script unique script identifier
3083 * @param int $instance instance id
3084 * @return stdClass the key entry in the user_private_key table
3085 * @since Moodle 3.2
3086 * @throws moodle_exception
3088 function validate_user_key($keyvalue, $script, $instance) {
3089 global $DB;
3091 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3092 print_error('invalidkey');
3095 if (!empty($key->validuntil) and $key->validuntil < time()) {
3096 print_error('expiredkey');
3099 if ($key->iprestriction) {
3100 $remoteaddr = getremoteaddr(null);
3101 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3102 print_error('ipmismatch');
3105 return $key;
3109 * Require key login. Function terminates with error if key not found or incorrect.
3111 * @uses NO_MOODLE_COOKIES
3112 * @uses PARAM_ALPHANUM
3113 * @param string $script unique script identifier
3114 * @param int $instance optional instance id
3115 * @return int Instance ID
3117 function require_user_key_login($script, $instance=null) {
3118 global $DB;
3120 if (!NO_MOODLE_COOKIES) {
3121 print_error('sessioncookiesdisable');
3124 // Extra safety.
3125 \core\session\manager::write_close();
3127 $keyvalue = required_param('key', PARAM_ALPHANUM);
3129 $key = validate_user_key($keyvalue, $script, $instance);
3131 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3132 print_error('invaliduserid');
3135 // Emulate normal session.
3136 enrol_check_plugins($user);
3137 \core\session\manager::set_user($user);
3139 // Note we are not using normal login.
3140 if (!defined('USER_KEY_LOGIN')) {
3141 define('USER_KEY_LOGIN', true);
3144 // Return instance id - it might be empty.
3145 return $key->instance;
3149 * Creates a new private user access key.
3151 * @param string $script unique target identifier
3152 * @param int $userid
3153 * @param int $instance optional instance id
3154 * @param string $iprestriction optional ip restricted access
3155 * @param int $validuntil key valid only until given data
3156 * @return string access key value
3158 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3159 global $DB;
3161 $key = new stdClass();
3162 $key->script = $script;
3163 $key->userid = $userid;
3164 $key->instance = $instance;
3165 $key->iprestriction = $iprestriction;
3166 $key->validuntil = $validuntil;
3167 $key->timecreated = time();
3169 // Something long and unique.
3170 $key->value = md5($userid.'_'.time().random_string(40));
3171 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3172 // Must be unique.
3173 $key->value = md5($userid.'_'.time().random_string(40));
3175 $DB->insert_record('user_private_key', $key);
3176 return $key->value;
3180 * Delete the user's new private user access keys for a particular script.
3182 * @param string $script unique target identifier
3183 * @param int $userid
3184 * @return void
3186 function delete_user_key($script, $userid) {
3187 global $DB;
3188 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3192 * Gets a private user access key (and creates one if one doesn't exist).
3194 * @param string $script unique target identifier
3195 * @param int $userid
3196 * @param int $instance optional instance id
3197 * @param string $iprestriction optional ip restricted access
3198 * @param int $validuntil key valid only until given date
3199 * @return string access key value
3201 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3202 global $DB;
3204 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3205 'instance' => $instance, 'iprestriction' => $iprestriction,
3206 'validuntil' => $validuntil))) {
3207 return $key->value;
3208 } else {
3209 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3215 * Modify the user table by setting the currently logged in user's last login to now.
3217 * @return bool Always returns true
3219 function update_user_login_times() {
3220 global $USER, $DB;
3222 if (isguestuser()) {
3223 // Do not update guest access times/ips for performance.
3224 return true;
3227 $now = time();
3229 $user = new stdClass();
3230 $user->id = $USER->id;
3232 // Make sure all users that logged in have some firstaccess.
3233 if ($USER->firstaccess == 0) {
3234 $USER->firstaccess = $user->firstaccess = $now;
3237 // Store the previous current as lastlogin.
3238 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3240 $USER->currentlogin = $user->currentlogin = $now;
3242 // Function user_accesstime_log() may not update immediately, better do it here.
3243 $USER->lastaccess = $user->lastaccess = $now;
3244 $USER->lastip = $user->lastip = getremoteaddr();
3246 // Note: do not call user_update_user() here because this is part of the login process,
3247 // the login event means that these fields were updated.
3248 $DB->update_record('user', $user);
3249 return true;
3253 * Determines if a user has completed setting up their account.
3255 * The lax mode (with $strict = false) has been introduced for special cases
3256 * only where we want to skip certain checks intentionally. This is valid in
3257 * certain mnet or ajax scenarios when the user cannot / should not be
3258 * redirected to edit their profile. In most cases, you should perform the
3259 * strict check.
3261 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3262 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3263 * @return bool
3265 function user_not_fully_set_up($user, $strict = true) {
3266 global $CFG;
3267 require_once($CFG->dirroot.'/user/profile/lib.php');
3269 if (isguestuser($user)) {
3270 return false;
3273 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3274 return true;
3277 if ($strict) {
3278 if (empty($user->id)) {
3279 // Strict mode can be used with existing accounts only.
3280 return true;
3282 if (!profile_has_required_custom_fields_set($user->id)) {
3283 return true;
3287 return false;
3291 * Check whether the user has exceeded the bounce threshold
3293 * @param stdClass $user A {@link $USER} object
3294 * @return bool true => User has exceeded bounce threshold
3296 function over_bounce_threshold($user) {
3297 global $CFG, $DB;
3299 if (empty($CFG->handlebounces)) {
3300 return false;
3303 if (empty($user->id)) {
3304 // No real (DB) user, nothing to do here.
3305 return false;
3308 // Set sensible defaults.
3309 if (empty($CFG->minbounces)) {
3310 $CFG->minbounces = 10;
3312 if (empty($CFG->bounceratio)) {
3313 $CFG->bounceratio = .20;
3315 $bouncecount = 0;
3316 $sendcount = 0;
3317 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3318 $bouncecount = $bounce->value;
3320 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3321 $sendcount = $send->value;
3323 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3327 * Used to increment or reset email sent count
3329 * @param stdClass $user object containing an id
3330 * @param bool $reset will reset the count to 0
3331 * @return void
3333 function set_send_count($user, $reset=false) {
3334 global $DB;
3336 if (empty($user->id)) {
3337 // No real (DB) user, nothing to do here.
3338 return;
3341 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3342 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3343 $DB->update_record('user_preferences', $pref);
3344 } else if (!empty($reset)) {
3345 // If it's not there and we're resetting, don't bother. Make a new one.
3346 $pref = new stdClass();
3347 $pref->name = 'email_send_count';
3348 $pref->value = 1;
3349 $pref->userid = $user->id;
3350 $DB->insert_record('user_preferences', $pref, false);
3355 * Increment or reset user's email bounce count
3357 * @param stdClass $user object containing an id
3358 * @param bool $reset will reset the count to 0
3360 function set_bounce_count($user, $reset=false) {
3361 global $DB;
3363 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3364 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3365 $DB->update_record('user_preferences', $pref);
3366 } else if (!empty($reset)) {
3367 // If it's not there and we're resetting, don't bother. Make a new one.
3368 $pref = new stdClass();
3369 $pref->name = 'email_bounce_count';
3370 $pref->value = 1;
3371 $pref->userid = $user->id;
3372 $DB->insert_record('user_preferences', $pref, false);
3377 * Determines if the logged in user is currently moving an activity
3379 * @param int $courseid The id of the course being tested
3380 * @return bool
3382 function ismoving($courseid) {
3383 global $USER;
3385 if (!empty($USER->activitycopy)) {
3386 return ($USER->activitycopycourse == $courseid);
3388 return false;
3392 * Returns a persons full name
3394 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3395 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3396 * specify one.
3398 * @param stdClass $user A {@link $USER} object to get full name of.
3399 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3400 * @return string
3402 function fullname($user, $override=false) {
3403 global $CFG, $SESSION;
3405 if (!isset($user->firstname) and !isset($user->lastname)) {
3406 return '';
3409 // Get all of the name fields.
3410 $allnames = get_all_user_name_fields();
3411 if ($CFG->debugdeveloper) {
3412 foreach ($allnames as $allname) {
3413 if (!property_exists($user, $allname)) {
3414 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3415 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3416 // Message has been sent, no point in sending the message multiple times.
3417 break;
3422 if (!$override) {
3423 if (!empty($CFG->forcefirstname)) {
3424 $user->firstname = $CFG->forcefirstname;
3426 if (!empty($CFG->forcelastname)) {
3427 $user->lastname = $CFG->forcelastname;
3431 if (!empty($SESSION->fullnamedisplay)) {
3432 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3435 $template = null;
3436 // If the fullnamedisplay setting is available, set the template to that.
3437 if (isset($CFG->fullnamedisplay)) {
3438 $template = $CFG->fullnamedisplay;
3440 // If the template is empty, or set to language, return the language string.
3441 if ((empty($template) || $template == 'language') && !$override) {
3442 return get_string('fullnamedisplay', null, $user);
3445 // Check to see if we are displaying according to the alternative full name format.
3446 if ($override) {
3447 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3448 // Default to show just the user names according to the fullnamedisplay string.
3449 return get_string('fullnamedisplay', null, $user);
3450 } else {
3451 // If the override is true, then change the template to use the complete name.
3452 $template = $CFG->alternativefullnameformat;
3456 $requirednames = array();
3457 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3458 foreach ($allnames as $allname) {
3459 if (strpos($template, $allname) !== false) {
3460 $requirednames[] = $allname;
3464 $displayname = $template;
3465 // Switch in the actual data into the template.
3466 foreach ($requirednames as $altname) {
3467 if (isset($user->$altname)) {
3468 // Using empty() on the below if statement causes breakages.
3469 if ((string)$user->$altname == '') {
3470 $displayname = str_replace($altname, 'EMPTY', $displayname);
3471 } else {
3472 $displayname = str_replace($altname, $user->$altname, $displayname);
3474 } else {
3475 $displayname = str_replace($altname, 'EMPTY', $displayname);
3478 // Tidy up any misc. characters (Not perfect, but gets most characters).
3479 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3480 // katakana and parenthesis.
3481 $patterns = array();
3482 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3483 // filled in by a user.
3484 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3485 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3486 // This regular expression is to remove any double spaces in the display name.
3487 $patterns[] = '/\s{2,}/u';
3488 foreach ($patterns as $pattern) {
3489 $displayname = preg_replace($pattern, ' ', $displayname);
3492 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3493 $displayname = trim($displayname);
3494 if (empty($displayname)) {
3495 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3496 // people in general feel is a good setting to fall back on.
3497 $displayname = $user->firstname;
3499 return $displayname;
3503 * A centralised location for the all name fields. Returns an array / sql string snippet.
3505 * @param bool $returnsql True for an sql select field snippet.
3506 * @param string $tableprefix table query prefix to use in front of each field.
3507 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3508 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3509 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3510 * @return array|string All name fields.
3512 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3513 // This array is provided in this order because when called by fullname() (above) if firstname is before
3514 // firstnamephonetic str_replace() will change the wrong placeholder.
3515 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3516 'lastnamephonetic' => 'lastnamephonetic',
3517 'middlename' => 'middlename',
3518 'alternatename' => 'alternatename',
3519 'firstname' => 'firstname',
3520 'lastname' => 'lastname');
3522 // Let's add a prefix to the array of user name fields if provided.
3523 if ($prefix) {
3524 foreach ($alternatenames as $key => $altname) {
3525 $alternatenames[$key] = $prefix . $altname;
3529 // If we want the end result to have firstname and lastname at the front / top of the result.
3530 if ($order) {
3531 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3532 for ($i = 0; $i < 2; $i++) {
3533 // Get the last element.
3534 $lastelement = end($alternatenames);
3535 // Remove it from the array.
3536 unset($alternatenames[$lastelement]);
3537 // Put the element back on the top of the array.
3538 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3542 // Create an sql field snippet if requested.
3543 if ($returnsql) {
3544 if ($tableprefix) {
3545 if ($fieldprefix) {
3546 foreach ($alternatenames as $key => $altname) {
3547 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3549 } else {
3550 foreach ($alternatenames as $key => $altname) {
3551 $alternatenames[$key] = $tableprefix . '.' . $altname;
3555 $alternatenames = implode(',', $alternatenames);
3557 return $alternatenames;
3561 * Reduces lines of duplicated code for getting user name fields.
3563 * See also {@link user_picture::unalias()}
3565 * @param object $addtoobject Object to add user name fields to.
3566 * @param object $secondobject Object that contains user name field information.
3567 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3568 * @param array $additionalfields Additional fields to be matched with data in the second object.
3569 * The key can be set to the user table field name.
3570 * @return object User name fields.
3572 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3573 $fields = get_all_user_name_fields(false, null, $prefix);
3574 if ($additionalfields) {
3575 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3576 // the key is a number and then sets the key to the array value.
3577 foreach ($additionalfields as $key => $value) {
3578 if (is_numeric($key)) {
3579 $additionalfields[$value] = $prefix . $value;
3580 unset($additionalfields[$key]);
3581 } else {
3582 $additionalfields[$key] = $prefix . $value;
3585 $fields = array_merge($fields, $additionalfields);
3587 foreach ($fields as $key => $field) {
3588 // Important that we have all of the user name fields present in the object that we are sending back.
3589 $addtoobject->$key = '';
3590 if (isset($secondobject->$field)) {
3591 $addtoobject->$key = $secondobject->$field;
3594 return $addtoobject;
3598 * Returns an array of values in order of occurance in a provided string.
3599 * The key in the result is the character postion in the string.
3601 * @param array $values Values to be found in the string format
3602 * @param string $stringformat The string which may contain values being searched for.
3603 * @return array An array of values in order according to placement in the string format.
3605 function order_in_string($values, $stringformat) {
3606 $valuearray = array();
3607 foreach ($values as $value) {
3608 $pattern = "/$value\b/";
3609 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3610 if (preg_match($pattern, $stringformat)) {
3611 $replacement = "thing";
3612 // Replace the value with something more unique to ensure we get the right position when using strpos().
3613 $newformat = preg_replace($pattern, $replacement, $stringformat);
3614 $position = strpos($newformat, $replacement);
3615 $valuearray[$position] = $value;
3618 ksort($valuearray);
3619 return $valuearray;
3623 * Checks if current user is shown any extra fields when listing users.
3625 * @param object $context Context
3626 * @param array $already Array of fields that we're going to show anyway
3627 * so don't bother listing them
3628 * @return array Array of field names from user table, not including anything
3629 * listed in $already
3631 function get_extra_user_fields($context, $already = array()) {
3632 global $CFG;
3634 // Only users with permission get the extra fields.
3635 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3636 return array();
3639 // Split showuseridentity on comma (filter needed in case the showuseridentity is empty).
3640 $extra = array_filter(explode(',', $CFG->showuseridentity));
3642 foreach ($extra as $key => $field) {
3643 if (in_array($field, $already)) {
3644 unset($extra[$key]);
3648 // If the identity fields are also among hidden fields, make sure the user can see them.
3649 $hiddenfields = array_filter(explode(',', $CFG->hiddenuserfields));
3650 $hiddenidentifiers = array_intersect($extra, $hiddenfields);
3652 if ($hiddenidentifiers) {
3653 if ($context->get_course_context(false)) {
3654 // We are somewhere inside a course.
3655 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3657 } else {
3658 // We are not inside a course.
3659 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
3662 if (!$canviewhiddenuserfields) {
3663 // Remove hidden identifiers from the list.
3664 $extra = array_diff($extra, $hiddenidentifiers);
3668 // Re-index the entries.
3669 $extra = array_values($extra);
3671 return $extra;
3675 * If the current user is to be shown extra user fields when listing or
3676 * selecting users, returns a string suitable for including in an SQL select
3677 * clause to retrieve those fields.
3679 * @param context $context Context
3680 * @param string $alias Alias of user table, e.g. 'u' (default none)
3681 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3682 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3683 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3685 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3686 $fields = get_extra_user_fields($context, $already);
3687 $result = '';
3688 // Add punctuation for alias.
3689 if ($alias !== '') {
3690 $alias .= '.';
3692 foreach ($fields as $field) {
3693 $result .= ', ' . $alias . $field;
3694 if ($prefix) {
3695 $result .= ' AS ' . $prefix . $field;
3698 return $result;
3702 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3703 * @param string $field Field name, e.g. 'phone1'
3704 * @return string Text description taken from language file, e.g. 'Phone number'
3706 function get_user_field_name($field) {
3707 // Some fields have language strings which are not the same as field name.
3708 switch ($field) {
3709 case 'url' : {
3710 return get_string('webpage');
3712 case 'icq' : {
3713 return get_string('icqnumber');
3715 case 'skype' : {
3716 return get_string('skypeid');
3718 case 'aim' : {
3719 return get_string('aimid');
3721 case 'yahoo' : {
3722 return get_string('yahooid');
3724 case 'msn' : {
3725 return get_string('msnid');
3727 case 'picture' : {
3728 return get_string('pictureofuser');
3731 // Otherwise just use the same lang string.
3732 return get_string($field);
3736 * Returns whether a given authentication plugin exists.
3738 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3739 * @return boolean Whether the plugin is available.
3741 function exists_auth_plugin($auth) {
3742 global $CFG;
3744 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3745 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3747 return false;
3751 * Checks if a given plugin is in the list of enabled authentication plugins.
3753 * @param string $auth Authentication plugin.
3754 * @return boolean Whether the plugin is enabled.
3756 function is_enabled_auth($auth) {
3757 if (empty($auth)) {
3758 return false;
3761 $enabled = get_enabled_auth_plugins();
3763 return in_array($auth, $enabled);
3767 * Returns an authentication plugin instance.
3769 * @param string $auth name of authentication plugin
3770 * @return auth_plugin_base An instance of the required authentication plugin.
3772 function get_auth_plugin($auth) {
3773 global $CFG;
3775 // Check the plugin exists first.
3776 if (! exists_auth_plugin($auth)) {
3777 print_error('authpluginnotfound', 'debug', '', $auth);
3780 // Return auth plugin instance.
3781 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3782 $class = "auth_plugin_$auth";
3783 return new $class;
3787 * Returns array of active auth plugins.
3789 * @param bool $fix fix $CFG->auth if needed
3790 * @return array
3792 function get_enabled_auth_plugins($fix=false) {
3793 global $CFG;
3795 $default = array('manual', 'nologin');
3797 if (empty($CFG->auth)) {
3798 $auths = array();
3799 } else {
3800 $auths = explode(',', $CFG->auth);
3803 if ($fix) {
3804 $auths = array_unique($auths);
3805 foreach ($auths as $k => $authname) {
3806 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3807 unset($auths[$k]);
3810 $newconfig = implode(',', $auths);
3811 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3812 set_config('auth', $newconfig);
3816 return (array_merge($default, $auths));
3820 * Returns true if an internal authentication method is being used.
3821 * if method not specified then, global default is assumed
3823 * @param string $auth Form of authentication required
3824 * @return bool
3826 function is_internal_auth($auth) {
3827 // Throws error if bad $auth.
3828 $authplugin = get_auth_plugin($auth);
3829 return $authplugin->is_internal();
3833 * Returns true if the user is a 'restored' one.
3835 * Used in the login process to inform the user and allow him/her to reset the password
3837 * @param string $username username to be checked
3838 * @return bool
3840 function is_restored_user($username) {
3841 global $CFG, $DB;
3843 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3847 * Returns an array of user fields
3849 * @return array User field/column names
3851 function get_user_fieldnames() {
3852 global $DB;
3854 $fieldarray = $DB->get_columns('user');
3855 unset($fieldarray['id']);
3856 $fieldarray = array_keys($fieldarray);
3858 return $fieldarray;
3862 * Creates a bare-bones user record
3864 * @todo Outline auth types and provide code example
3866 * @param string $username New user's username to add to record
3867 * @param string $password New user's password to add to record
3868 * @param string $auth Form of authentication required
3869 * @return stdClass A complete user object
3871 function create_user_record($username, $password, $auth = 'manual') {
3872 global $CFG, $DB;
3873 require_once($CFG->dirroot.'/user/profile/lib.php');
3874 require_once($CFG->dirroot.'/user/lib.php');
3876 // Just in case check text case.
3877 $username = trim(core_text::strtolower($username));
3879 $authplugin = get_auth_plugin($auth);
3880 $customfields = $authplugin->get_custom_user_profile_fields();
3881 $newuser = new stdClass();
3882 if ($newinfo = $authplugin->get_userinfo($username)) {
3883 $newinfo = truncate_userinfo($newinfo);
3884 foreach ($newinfo as $key => $value) {
3885 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3886 $newuser->$key = $value;
3891 if (!empty($newuser->email)) {
3892 if (email_is_not_allowed($newuser->email)) {
3893 unset($newuser->email);
3897 if (!isset($newuser->city)) {
3898 $newuser->city = '';
3901 $newuser->auth = $auth;
3902 $newuser->username = $username;
3904 // Fix for MDL-8480
3905 // user CFG lang for user if $newuser->lang is empty
3906 // or $user->lang is not an installed language.
3907 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3908 $newuser->lang = $CFG->lang;
3910 $newuser->confirmed = 1;
3911 $newuser->lastip = getremoteaddr();
3912 $newuser->timecreated = time();
3913 $newuser->timemodified = $newuser->timecreated;
3914 $newuser->mnethostid = $CFG->mnet_localhost_id;
3916 $newuser->id = user_create_user($newuser, false, false);
3918 // Save user profile data.
3919 profile_save_data($newuser);
3921 $user = get_complete_user_data('id', $newuser->id);
3922 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3923 set_user_preference('auth_forcepasswordchange', 1, $user);
3925 // Set the password.
3926 update_internal_user_password($user, $password);
3928 // Trigger event.
3929 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3931 return $user;
3935 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3937 * @param string $username user's username to update the record
3938 * @return stdClass A complete user object
3940 function update_user_record($username) {
3941 global $DB, $CFG;
3942 // Just in case check text case.
3943 $username = trim(core_text::strtolower($username));
3945 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3946 return update_user_record_by_id($oldinfo->id);
3950 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3952 * @param int $id user id
3953 * @return stdClass A complete user object
3955 function update_user_record_by_id($id) {
3956 global $DB, $CFG;
3957 require_once($CFG->dirroot."/user/profile/lib.php");
3958 require_once($CFG->dirroot.'/user/lib.php');
3960 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3961 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3963 $newuser = array();
3964 $userauth = get_auth_plugin($oldinfo->auth);
3966 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3967 $newinfo = truncate_userinfo($newinfo);
3968 $customfields = $userauth->get_custom_user_profile_fields();
3970 foreach ($newinfo as $key => $value) {
3971 $iscustom = in_array($key, $customfields);
3972 if (!$iscustom) {
3973 $key = strtolower($key);
3975 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3976 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3977 // Unknown or must not be changed.
3978 continue;
3980 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
3981 continue;
3983 $confval = $userauth->config->{'field_updatelocal_' . $key};
3984 $lockval = $userauth->config->{'field_lock_' . $key};
3985 if ($confval === 'onlogin') {
3986 // MDL-4207 Don't overwrite modified user profile values with
3987 // empty LDAP values when 'unlocked if empty' is set. The purpose
3988 // of the setting 'unlocked if empty' is to allow the user to fill
3989 // in a value for the selected field _if LDAP is giving
3990 // nothing_ for this field. Thus it makes sense to let this value
3991 // stand in until LDAP is giving a value for this field.
3992 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3993 if ($iscustom || (in_array($key, $userauth->userfields) &&
3994 ((string)$oldinfo->$key !== (string)$value))) {
3995 $newuser[$key] = (string)$value;
4000 if ($newuser) {
4001 $newuser['id'] = $oldinfo->id;
4002 $newuser['timemodified'] = time();
4003 user_update_user((object) $newuser, false, false);
4005 // Save user profile data.
4006 profile_save_data((object) $newuser);
4008 // Trigger event.
4009 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4013 return get_complete_user_data('id', $oldinfo->id);
4017 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4019 * @param array $info Array of user properties to truncate if needed
4020 * @return array The now truncated information that was passed in
4022 function truncate_userinfo(array $info) {
4023 // Define the limits.
4024 $limit = array(
4025 'username' => 100,
4026 'idnumber' => 255,
4027 'firstname' => 100,
4028 'lastname' => 100,
4029 'email' => 100,
4030 'icq' => 15,
4031 'phone1' => 20,
4032 'phone2' => 20,
4033 'institution' => 255,
4034 'department' => 255,
4035 'address' => 255,
4036 'city' => 120,
4037 'country' => 2,
4038 'url' => 255,
4041 // Apply where needed.
4042 foreach (array_keys($info) as $key) {
4043 if (!empty($limit[$key])) {
4044 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4048 return $info;
4052 * Marks user deleted in internal user database and notifies the auth plugin.
4053 * Also unenrols user from all roles and does other cleanup.
4055 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4057 * @param stdClass $user full user object before delete
4058 * @return boolean success
4059 * @throws coding_exception if invalid $user parameter detected
4061 function delete_user(stdClass $user) {
4062 global $CFG, $DB;
4063 require_once($CFG->libdir.'/grouplib.php');
4064 require_once($CFG->libdir.'/gradelib.php');
4065 require_once($CFG->dirroot.'/message/lib.php');
4066 require_once($CFG->dirroot.'/user/lib.php');
4068 // Make sure nobody sends bogus record type as parameter.
4069 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4070 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4073 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4074 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4075 debugging('Attempt to delete unknown user account.');
4076 return false;
4079 // There must be always exactly one guest record, originally the guest account was identified by username only,
4080 // now we use $CFG->siteguest for performance reasons.
4081 if ($user->username === 'guest' or isguestuser($user)) {
4082 debugging('Guest user account can not be deleted.');
4083 return false;
4086 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4087 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4088 if ($user->auth === 'manual' and is_siteadmin($user)) {
4089 debugging('Local administrator accounts can not be deleted.');
4090 return false;
4093 // Allow plugins to use this user object before we completely delete it.
4094 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4095 foreach ($pluginsfunction as $plugintype => $plugins) {
4096 foreach ($plugins as $pluginfunction) {
4097 $pluginfunction($user);
4102 // Keep user record before updating it, as we have to pass this to user_deleted event.
4103 $olduser = clone $user;
4105 // Keep a copy of user context, we need it for event.
4106 $usercontext = context_user::instance($user->id);
4108 // Delete all grades - backup is kept in grade_grades_history table.
4109 grade_user_delete($user->id);
4111 // TODO: remove from cohorts using standard API here.
4113 // Remove user tags.
4114 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4116 // Unconditionally unenrol from all courses.
4117 enrol_user_delete($user);
4119 // Unenrol from all roles in all contexts.
4120 // This might be slow but it is really needed - modules might do some extra cleanup!
4121 role_unassign_all(array('userid' => $user->id));
4123 // Now do a brute force cleanup.
4125 // Remove from all cohorts.
4126 $DB->delete_records('cohort_members', array('userid' => $user->id));
4128 // Remove from all groups.
4129 $DB->delete_records('groups_members', array('userid' => $user->id));
4131 // Brute force unenrol from all courses.
4132 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4134 // Purge user preferences.
4135 $DB->delete_records('user_preferences', array('userid' => $user->id));
4137 // Purge user extra profile info.
4138 $DB->delete_records('user_info_data', array('userid' => $user->id));
4140 // Purge log of previous password hashes.
4141 $DB->delete_records('user_password_history', array('userid' => $user->id));
4143 // Last course access not necessary either.
4144 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4145 // Remove all user tokens.
4146 $DB->delete_records('external_tokens', array('userid' => $user->id));
4148 // Unauthorise the user for all services.
4149 $DB->delete_records('external_services_users', array('userid' => $user->id));
4151 // Remove users private keys.
4152 $DB->delete_records('user_private_key', array('userid' => $user->id));
4154 // Remove users customised pages.
4155 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4157 // Force logout - may fail if file based sessions used, sorry.
4158 \core\session\manager::kill_user_sessions($user->id);
4160 // Generate username from email address, or a fake email.
4161 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4162 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
4164 // Workaround for bulk deletes of users with the same email address.
4165 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4166 $delname++;
4169 // Mark internal user record as "deleted".
4170 $updateuser = new stdClass();
4171 $updateuser->id = $user->id;
4172 $updateuser->deleted = 1;
4173 $updateuser->username = $delname; // Remember it just in case.
4174 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4175 $updateuser->idnumber = ''; // Clear this field to free it up.
4176 $updateuser->picture = 0;
4177 $updateuser->timemodified = time();
4179 // Don't trigger update event, as user is being deleted.
4180 user_update_user($updateuser, false, false);
4182 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4183 context_helper::delete_instance(CONTEXT_USER, $user->id);
4185 // Any plugin that needs to cleanup should register this event.
4186 // Trigger event.
4187 $event = \core\event\user_deleted::create(
4188 array(
4189 'objectid' => $user->id,
4190 'relateduserid' => $user->id,
4191 'context' => $usercontext,
4192 'other' => array(
4193 'username' => $user->username,
4194 'email' => $user->email,
4195 'idnumber' => $user->idnumber,
4196 'picture' => $user->picture,
4197 'mnethostid' => $user->mnethostid
4201 $event->add_record_snapshot('user', $olduser);
4202 $event->trigger();
4204 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4205 // should know about this updated property persisted to the user's table.
4206 $user->timemodified = $updateuser->timemodified;
4208 // Notify auth plugin - do not block the delete even when plugin fails.
4209 $authplugin = get_auth_plugin($user->auth);
4210 $authplugin->user_delete($user);
4212 return true;
4216 * Retrieve the guest user object.
4218 * @return stdClass A {@link $USER} object
4220 function guest_user() {
4221 global $CFG, $DB;
4223 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4224 $newuser->confirmed = 1;
4225 $newuser->lang = $CFG->lang;
4226 $newuser->lastip = getremoteaddr();
4229 return $newuser;
4233 * Authenticates a user against the chosen authentication mechanism
4235 * Given a username and password, this function looks them
4236 * up using the currently selected authentication mechanism,
4237 * and if the authentication is successful, it returns a
4238 * valid $user object from the 'user' table.
4240 * Uses auth_ functions from the currently active auth module
4242 * After authenticate_user_login() returns success, you will need to
4243 * log that the user has logged in, and call complete_user_login() to set
4244 * the session up.
4246 * Note: this function works only with non-mnet accounts!
4248 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4249 * @param string $password User's password
4250 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4251 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4252 * @return stdClass|false A {@link $USER} object or false if error
4254 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4255 global $CFG, $DB;
4256 require_once("$CFG->libdir/authlib.php");
4258 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4259 // we have found the user
4261 } else if (!empty($CFG->authloginviaemail)) {
4262 if ($email = clean_param($username, PARAM_EMAIL)) {
4263 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4264 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4265 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4266 if (count($users) === 1) {
4267 // Use email for login only if unique.
4268 $user = reset($users);
4269 $user = get_complete_user_data('id', $user->id);
4270 $username = $user->username;
4272 unset($users);
4276 $authsenabled = get_enabled_auth_plugins();
4278 if ($user) {
4279 // Use manual if auth not set.
4280 $auth = empty($user->auth) ? 'manual' : $user->auth;
4282 if (in_array($user->auth, $authsenabled)) {
4283 $authplugin = get_auth_plugin($user->auth);
4284 $authplugin->pre_user_login_hook($user);
4287 if (!empty($user->suspended)) {
4288 $failurereason = AUTH_LOGIN_SUSPENDED;
4290 // Trigger login failed event.
4291 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4292 'other' => array('username' => $username, 'reason' => $failurereason)));
4293 $event->trigger();
4294 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4295 return false;
4297 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4298 // Legacy way to suspend user.
4299 $failurereason = AUTH_LOGIN_SUSPENDED;
4301 // Trigger login failed event.
4302 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4303 'other' => array('username' => $username, 'reason' => $failurereason)));
4304 $event->trigger();
4305 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4306 return false;
4308 $auths = array($auth);
4310 } else {
4311 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4312 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4313 $failurereason = AUTH_LOGIN_NOUSER;
4315 // Trigger login failed event.
4316 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4317 'reason' => $failurereason)));
4318 $event->trigger();
4319 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4320 return false;
4323 // User does not exist.
4324 $auths = $authsenabled;
4325 $user = new stdClass();
4326 $user->id = 0;
4329 if ($ignorelockout) {
4330 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4331 // or this function is called from a SSO script.
4332 } else if ($user->id) {
4333 // Verify login lockout after other ways that may prevent user login.
4334 if (login_is_lockedout($user)) {
4335 $failurereason = AUTH_LOGIN_LOCKOUT;
4337 // Trigger login failed event.
4338 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4339 'other' => array('username' => $username, 'reason' => $failurereason)));
4340 $event->trigger();
4342 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4343 return false;
4345 } else {
4346 // We can not lockout non-existing accounts.
4349 foreach ($auths as $auth) {
4350 $authplugin = get_auth_plugin($auth);
4352 // On auth fail fall through to the next plugin.
4353 if (!$authplugin->user_login($username, $password)) {
4354 continue;
4357 // Successful authentication.
4358 if ($user->id) {
4359 // User already exists in database.
4360 if (empty($user->auth)) {
4361 // For some reason auth isn't set yet.
4362 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4363 $user->auth = $auth;
4366 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4367 // the current hash algorithm while we have access to the user's password.
4368 update_internal_user_password($user, $password);
4370 if ($authplugin->is_synchronised_with_external()) {
4371 // Update user record from external DB.
4372 $user = update_user_record_by_id($user->id);
4374 } else {
4375 // The user is authenticated but user creation may be disabled.
4376 if (!empty($CFG->authpreventaccountcreation)) {
4377 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4379 // Trigger login failed event.
4380 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4381 'reason' => $failurereason)));
4382 $event->trigger();
4384 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4385 $_SERVER['HTTP_USER_AGENT']);
4386 return false;
4387 } else {
4388 $user = create_user_record($username, $password, $auth);
4392 $authplugin->sync_roles($user);
4394 foreach ($authsenabled as $hau) {
4395 $hauth = get_auth_plugin($hau);
4396 $hauth->user_authenticated_hook($user, $username, $password);
4399 if (empty($user->id)) {
4400 $failurereason = AUTH_LOGIN_NOUSER;
4401 // Trigger login failed event.
4402 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4403 'reason' => $failurereason)));
4404 $event->trigger();
4405 return false;
4408 if (!empty($user->suspended)) {
4409 // Just in case some auth plugin suspended account.
4410 $failurereason = AUTH_LOGIN_SUSPENDED;
4411 // Trigger login failed event.
4412 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4413 'other' => array('username' => $username, 'reason' => $failurereason)));
4414 $event->trigger();
4415 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4416 return false;
4419 login_attempt_valid($user);
4420 $failurereason = AUTH_LOGIN_OK;
4421 return $user;
4424 // Failed if all the plugins have failed.
4425 if (debugging('', DEBUG_ALL)) {
4426 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4429 if ($user->id) {
4430 login_attempt_failed($user);
4431 $failurereason = AUTH_LOGIN_FAILED;
4432 // Trigger login failed event.
4433 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4434 'other' => array('username' => $username, 'reason' => $failurereason)));
4435 $event->trigger();
4436 } else {
4437 $failurereason = AUTH_LOGIN_NOUSER;
4438 // Trigger login failed event.
4439 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4440 'reason' => $failurereason)));
4441 $event->trigger();
4444 return false;
4448 * Call to complete the user login process after authenticate_user_login()
4449 * has succeeded. It will setup the $USER variable and other required bits
4450 * and pieces.
4452 * NOTE:
4453 * - It will NOT log anything -- up to the caller to decide what to log.
4454 * - this function does not set any cookies any more!
4456 * @param stdClass $user
4457 * @return stdClass A {@link $USER} object - BC only, do not use
4459 function complete_user_login($user) {
4460 global $CFG, $DB, $USER, $SESSION;
4462 \core\session\manager::login_user($user);
4464 // Reload preferences from DB.
4465 unset($USER->preference);
4466 check_user_preferences_loaded($USER);
4468 // Update login times.
4469 update_user_login_times();
4471 // Extra session prefs init.
4472 set_login_session_preferences();
4474 // Trigger login event.
4475 $event = \core\event\user_loggedin::create(
4476 array(
4477 'userid' => $USER->id,
4478 'objectid' => $USER->id,
4479 'other' => array('username' => $USER->username),
4482 $event->trigger();
4484 // Queue migrating the messaging data, if we need to.
4485 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4486 // Check if there are any legacy messages to migrate.
4487 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4488 \core_message\task\migrate_message_data::queue_task($USER->id);
4489 } else {
4490 set_user_preference('core_message_migrate_data', true, $USER->id);
4494 if (isguestuser()) {
4495 // No need to continue when user is THE guest.
4496 return $USER;
4499 if (CLI_SCRIPT) {
4500 // We can redirect to password change URL only in browser.
4501 return $USER;
4504 // Select password change url.
4505 $userauth = get_auth_plugin($USER->auth);
4507 // Check whether the user should be changing password.
4508 if (get_user_preferences('auth_forcepasswordchange', false)) {
4509 if ($userauth->can_change_password()) {
4510 if ($changeurl = $userauth->change_password_url()) {
4511 redirect($changeurl);
4512 } else {
4513 require_once($CFG->dirroot . '/login/lib.php');
4514 $SESSION->wantsurl = core_login_get_return_url();
4515 redirect($CFG->wwwroot.'/login/change_password.php');
4517 } else {
4518 print_error('nopasswordchangeforced', 'auth');
4521 return $USER;
4525 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4527 * @param string $password String to check.
4528 * @return boolean True if the $password matches the format of an md5 sum.
4530 function password_is_legacy_hash($password) {
4531 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4535 * Compare password against hash stored in user object to determine if it is valid.
4537 * If necessary it also updates the stored hash to the current format.
4539 * @param stdClass $user (Password property may be updated).
4540 * @param string $password Plain text password.
4541 * @return bool True if password is valid.
4543 function validate_internal_user_password($user, $password) {
4544 global $CFG;
4546 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4547 // Internal password is not used at all, it can not validate.
4548 return false;
4551 // If hash isn't a legacy (md5) hash, validate using the library function.
4552 if (!password_is_legacy_hash($user->password)) {
4553 return password_verify($password, $user->password);
4556 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4557 // is valid we can then update it to the new algorithm.
4559 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4560 $validated = false;
4562 if ($user->password === md5($password.$sitesalt)
4563 or $user->password === md5($password)
4564 or $user->password === md5(addslashes($password).$sitesalt)
4565 or $user->password === md5(addslashes($password))) {
4566 // Note: we are intentionally using the addslashes() here because we
4567 // need to accept old password hashes of passwords with magic quotes.
4568 $validated = true;
4570 } else {
4571 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4572 $alt = 'passwordsaltalt'.$i;
4573 if (!empty($CFG->$alt)) {
4574 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4575 $validated = true;
4576 break;
4582 if ($validated) {
4583 // If the password matches the existing md5 hash, update to the
4584 // current hash algorithm while we have access to the user's password.
4585 update_internal_user_password($user, $password);
4588 return $validated;
4592 * Calculate hash for a plain text password.
4594 * @param string $password Plain text password to be hashed.
4595 * @param bool $fasthash If true, use a low cost factor when generating the hash
4596 * This is much faster to generate but makes the hash
4597 * less secure. It is used when lots of hashes need to
4598 * be generated quickly.
4599 * @return string The hashed password.
4601 * @throws moodle_exception If a problem occurs while generating the hash.
4603 function hash_internal_user_password($password, $fasthash = false) {
4604 global $CFG;
4606 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4607 $options = ($fasthash) ? array('cost' => 4) : array();
4609 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4611 if ($generatedhash === false || $generatedhash === null) {
4612 throw new moodle_exception('Failed to generate password hash.');
4615 return $generatedhash;
4619 * Update password hash in user object (if necessary).
4621 * The password is updated if:
4622 * 1. The password has changed (the hash of $user->password is different
4623 * to the hash of $password).
4624 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4625 * md5 algorithm).
4627 * Updating the password will modify the $user object and the database
4628 * record to use the current hashing algorithm.
4629 * It will remove Web Services user tokens too.
4631 * @param stdClass $user User object (password property may be updated).
4632 * @param string $password Plain text password.
4633 * @param bool $fasthash If true, use a low cost factor when generating the hash
4634 * This is much faster to generate but makes the hash
4635 * less secure. It is used when lots of hashes need to
4636 * be generated quickly.
4637 * @return bool Always returns true.
4639 function update_internal_user_password($user, $password, $fasthash = false) {
4640 global $CFG, $DB;
4642 // Figure out what the hashed password should be.
4643 if (!isset($user->auth)) {
4644 debugging('User record in update_internal_user_password() must include field auth',
4645 DEBUG_DEVELOPER);
4646 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4648 $authplugin = get_auth_plugin($user->auth);
4649 if ($authplugin->prevent_local_passwords()) {
4650 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4651 } else {
4652 $hashedpassword = hash_internal_user_password($password, $fasthash);
4655 $algorithmchanged = false;
4657 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4658 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4659 $passwordchanged = ($user->password !== $hashedpassword);
4661 } else if (isset($user->password)) {
4662 // If verification fails then it means the password has changed.
4663 $passwordchanged = !password_verify($password, $user->password);
4664 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4665 } else {
4666 // While creating new user, password in unset in $user object, to avoid
4667 // saving it with user_create()
4668 $passwordchanged = true;
4671 if ($passwordchanged || $algorithmchanged) {
4672 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4673 $user->password = $hashedpassword;
4675 // Trigger event.
4676 $user = $DB->get_record('user', array('id' => $user->id));
4677 \core\event\user_password_updated::create_from_user($user)->trigger();
4679 // Remove WS user tokens.
4680 if (!empty($CFG->passwordchangetokendeletion)) {
4681 require_once($CFG->dirroot.'/webservice/lib.php');
4682 webservice::delete_user_ws_tokens($user->id);
4686 return true;
4690 * Get a complete user record, which includes all the info in the user record.
4692 * Intended for setting as $USER session variable
4694 * @param string $field The user field to be checked for a given value.
4695 * @param string $value The value to match for $field.
4696 * @param int $mnethostid
4697 * @return mixed False, or A {@link $USER} object.
4699 function get_complete_user_data($field, $value, $mnethostid = null) {
4700 global $CFG, $DB;
4702 if (!$field || !$value) {
4703 return false;
4706 // Build the WHERE clause for an SQL query.
4707 $params = array('fieldval' => $value);
4708 $constraints = "$field = :fieldval AND deleted <> 1";
4710 // If we are loading user data based on anything other than id,
4711 // we must also restrict our search based on mnet host.
4712 if ($field != 'id') {
4713 if (empty($mnethostid)) {
4714 // If empty, we restrict to local users.
4715 $mnethostid = $CFG->mnet_localhost_id;
4718 if (!empty($mnethostid)) {
4719 $params['mnethostid'] = $mnethostid;
4720 $constraints .= " AND mnethostid = :mnethostid";
4723 // Get all the basic user data.
4724 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4725 return false;
4728 // Get various settings and preferences.
4730 // Preload preference cache.
4731 check_user_preferences_loaded($user);
4733 // Load course enrolment related stuff.
4734 $user->lastcourseaccess = array(); // During last session.
4735 $user->currentcourseaccess = array(); // During current session.
4736 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4737 foreach ($lastaccesses as $lastaccess) {
4738 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4742 $sql = "SELECT g.id, g.courseid
4743 FROM {groups} g, {groups_members} gm
4744 WHERE gm.groupid=g.id AND gm.userid=?";
4746 // This is a special hack to speedup calendar display.
4747 $user->groupmember = array();
4748 if (!isguestuser($user)) {
4749 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4750 foreach ($groups as $group) {
4751 if (!array_key_exists($group->courseid, $user->groupmember)) {
4752 $user->groupmember[$group->courseid] = array();
4754 $user->groupmember[$group->courseid][$group->id] = $group->id;
4759 // Add cohort theme.
4760 if (!empty($CFG->allowcohortthemes)) {
4761 require_once($CFG->dirroot . '/cohort/lib.php');
4762 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4763 $user->cohorttheme = $cohorttheme;
4767 // Add the custom profile fields to the user record.
4768 $user->profile = array();
4769 if (!isguestuser($user)) {
4770 require_once($CFG->dirroot.'/user/profile/lib.php');
4771 profile_load_custom_fields($user);
4774 // Rewrite some variables if necessary.
4775 if (!empty($user->description)) {
4776 // No need to cart all of it around.
4777 $user->description = true;
4779 if (isguestuser($user)) {
4780 // Guest language always same as site.
4781 $user->lang = $CFG->lang;
4782 // Name always in current language.
4783 $user->firstname = get_string('guestuser');
4784 $user->lastname = ' ';
4787 return $user;
4791 * Validate a password against the configured password policy
4793 * @param string $password the password to be checked against the password policy
4794 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4795 * @return bool true if the password is valid according to the policy. false otherwise.
4797 function check_password_policy($password, &$errmsg) {
4798 global $CFG;
4800 if (!empty($CFG->passwordpolicy)) {
4801 $errmsg = '';
4802 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4803 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4805 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4806 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4808 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4809 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4811 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4812 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4814 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4815 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4817 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4818 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4822 // Fire any additional password policy functions from plugins.
4823 // Plugin functions should output an error message string or empty string for success.
4824 $pluginsfunction = get_plugins_with_function('check_password_policy');
4825 foreach ($pluginsfunction as $plugintype => $plugins) {
4826 foreach ($plugins as $pluginfunction) {
4827 $pluginerr = $pluginfunction($password);
4828 if ($pluginerr) {
4829 $errmsg .= '<div>'. $pluginerr .'</div>';
4834 if ($errmsg == '') {
4835 return true;
4836 } else {
4837 return false;
4843 * When logging in, this function is run to set certain preferences for the current SESSION.
4845 function set_login_session_preferences() {
4846 global $SESSION;
4848 $SESSION->justloggedin = true;
4850 unset($SESSION->lang);
4851 unset($SESSION->forcelang);
4852 unset($SESSION->load_navigation_admin);
4857 * Delete a course, including all related data from the database, and any associated files.
4859 * @param mixed $courseorid The id of the course or course object to delete.
4860 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4861 * @return bool true if all the removals succeeded. false if there were any failures. If this
4862 * method returns false, some of the removals will probably have succeeded, and others
4863 * failed, but you have no way of knowing which.
4865 function delete_course($courseorid, $showfeedback = true) {
4866 global $DB;
4868 if (is_object($courseorid)) {
4869 $courseid = $courseorid->id;
4870 $course = $courseorid;
4871 } else {
4872 $courseid = $courseorid;
4873 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4874 return false;
4877 $context = context_course::instance($courseid);
4879 // Frontpage course can not be deleted!!
4880 if ($courseid == SITEID) {
4881 return false;
4884 // Allow plugins to use this course before we completely delete it.
4885 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
4886 foreach ($pluginsfunction as $plugintype => $plugins) {
4887 foreach ($plugins as $pluginfunction) {
4888 $pluginfunction($course);
4893 // Make the course completely empty.
4894 remove_course_contents($courseid, $showfeedback);
4896 // Delete the course and related context instance.
4897 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4899 $DB->delete_records("course", array("id" => $courseid));
4900 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4902 // Reset all course related caches here.
4903 if (class_exists('format_base', false)) {
4904 format_base::reset_course_cache($courseid);
4907 // Trigger a course deleted event.
4908 $event = \core\event\course_deleted::create(array(
4909 'objectid' => $course->id,
4910 'context' => $context,
4911 'other' => array(
4912 'shortname' => $course->shortname,
4913 'fullname' => $course->fullname,
4914 'idnumber' => $course->idnumber
4917 $event->add_record_snapshot('course', $course);
4918 $event->trigger();
4920 return true;
4924 * Clear a course out completely, deleting all content but don't delete the course itself.
4926 * This function does not verify any permissions.
4928 * Please note this function also deletes all user enrolments,
4929 * enrolment instances and role assignments by default.
4931 * $options:
4932 * - 'keep_roles_and_enrolments' - false by default
4933 * - 'keep_groups_and_groupings' - false by default
4935 * @param int $courseid The id of the course that is being deleted
4936 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4937 * @param array $options extra options
4938 * @return bool true if all the removals succeeded. false if there were any failures. If this
4939 * method returns false, some of the removals will probably have succeeded, and others
4940 * failed, but you have no way of knowing which.
4942 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4943 global $CFG, $DB, $OUTPUT;
4945 require_once($CFG->libdir.'/badgeslib.php');
4946 require_once($CFG->libdir.'/completionlib.php');
4947 require_once($CFG->libdir.'/questionlib.php');
4948 require_once($CFG->libdir.'/gradelib.php');
4949 require_once($CFG->dirroot.'/group/lib.php');
4950 require_once($CFG->dirroot.'/comment/lib.php');
4951 require_once($CFG->dirroot.'/rating/lib.php');
4952 require_once($CFG->dirroot.'/notes/lib.php');
4954 // Handle course badges.
4955 badges_handle_course_deletion($courseid);
4957 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4958 $strdeleted = get_string('deleted').' - ';
4960 // Some crazy wishlist of stuff we should skip during purging of course content.
4961 $options = (array)$options;
4963 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
4964 $coursecontext = context_course::instance($courseid);
4965 $fs = get_file_storage();
4967 // Delete course completion information, this has to be done before grades and enrols.
4968 $cc = new completion_info($course);
4969 $cc->clear_criteria();
4970 if ($showfeedback) {
4971 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4974 // Remove all data from gradebook - this needs to be done before course modules
4975 // because while deleting this information, the system may need to reference
4976 // the course modules that own the grades.
4977 remove_course_grades($courseid, $showfeedback);
4978 remove_grade_letters($coursecontext, $showfeedback);
4980 // Delete course blocks in any all child contexts,
4981 // they may depend on modules so delete them first.
4982 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4983 foreach ($childcontexts as $childcontext) {
4984 blocks_delete_all_for_context($childcontext->id);
4986 unset($childcontexts);
4987 blocks_delete_all_for_context($coursecontext->id);
4988 if ($showfeedback) {
4989 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4992 // Get the list of all modules that are properly installed.
4993 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
4995 // Delete every instance of every module,
4996 // this has to be done before deleting of course level stuff.
4997 $locations = core_component::get_plugin_list('mod');
4998 foreach ($locations as $modname => $moddir) {
4999 if ($modname === 'NEWMODULE') {
5000 continue;
5002 if (array_key_exists($modname, $allmodules)) {
5003 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5004 FROM {".$modname."} m
5005 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5006 WHERE m.course = :courseid";
5007 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5008 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5010 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5011 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5013 if ($instances) {
5014 foreach ($instances as $cm) {
5015 if ($cm->id) {
5016 // Delete activity context questions and question categories.
5017 question_delete_activity($cm, $showfeedback);
5018 // Notify the competency subsystem.
5019 \core_competency\api::hook_course_module_deleted($cm);
5021 if (function_exists($moddelete)) {
5022 // This purges all module data in related tables, extra user prefs, settings, etc.
5023 $moddelete($cm->modinstance);
5024 } else {
5025 // NOTE: we should not allow installation of modules with missing delete support!
5026 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5027 $DB->delete_records($modname, array('id' => $cm->modinstance));
5030 if ($cm->id) {
5031 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5032 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5033 $DB->delete_records('course_modules', array('id' => $cm->id));
5037 if ($instances and $showfeedback) {
5038 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5040 } else {
5041 // Ooops, this module is not properly installed, force-delete it in the next block.
5045 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5047 // Delete completion defaults.
5048 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5050 // Remove all data from availability and completion tables that is associated
5051 // with course-modules belonging to this course. Note this is done even if the
5052 // features are not enabled now, in case they were enabled previously.
5053 $DB->delete_records_select('course_modules_completion',
5054 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5055 array($courseid));
5057 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5058 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5059 $allmodulesbyid = array_flip($allmodules);
5060 foreach ($cms as $cm) {
5061 if (array_key_exists($cm->module, $allmodulesbyid)) {
5062 try {
5063 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5064 } catch (Exception $e) {
5065 // Ignore weird or missing table problems.
5068 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5069 $DB->delete_records('course_modules', array('id' => $cm->id));
5072 if ($showfeedback) {
5073 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5076 // Delete questions and question categories.
5077 question_delete_course($course, $showfeedback);
5078 if ($showfeedback) {
5079 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5082 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5083 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5084 foreach ($childcontexts as $childcontext) {
5085 $childcontext->delete();
5087 unset($childcontexts);
5089 // Remove all roles and enrolments by default.
5090 if (empty($options['keep_roles_and_enrolments'])) {
5091 // This hack is used in restore when deleting contents of existing course.
5092 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5093 enrol_course_delete($course);
5094 if ($showfeedback) {
5095 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5099 // Delete any groups, removing members and grouping/course links first.
5100 if (empty($options['keep_groups_and_groupings'])) {
5101 groups_delete_groupings($course->id, $showfeedback);
5102 groups_delete_groups($course->id, $showfeedback);
5105 // Filters be gone!
5106 filter_delete_all_for_context($coursecontext->id);
5108 // Notes, you shall not pass!
5109 note_delete_all($course->id);
5111 // Die comments!
5112 comment::delete_comments($coursecontext->id);
5114 // Ratings are history too.
5115 $delopt = new stdclass();
5116 $delopt->contextid = $coursecontext->id;
5117 $rm = new rating_manager();
5118 $rm->delete_ratings($delopt);
5120 // Delete course tags.
5121 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5123 // Notify the competency subsystem.
5124 \core_competency\api::hook_course_deleted($course);
5126 // Delete calendar events.
5127 $DB->delete_records('event', array('courseid' => $course->id));
5128 $fs->delete_area_files($coursecontext->id, 'calendar');
5130 // Delete all related records in other core tables that may have a courseid
5131 // This array stores the tables that need to be cleared, as
5132 // table_name => column_name that contains the course id.
5133 $tablestoclear = array(
5134 'backup_courses' => 'courseid', // Scheduled backup stuff.
5135 'user_lastaccess' => 'courseid', // User access info.
5137 foreach ($tablestoclear as $table => $col) {
5138 $DB->delete_records($table, array($col => $course->id));
5141 // Delete all course backup files.
5142 $fs->delete_area_files($coursecontext->id, 'backup');
5144 // Cleanup course record - remove links to deleted stuff.
5145 $oldcourse = new stdClass();
5146 $oldcourse->id = $course->id;
5147 $oldcourse->summary = '';
5148 $oldcourse->cacherev = 0;
5149 $oldcourse->legacyfiles = 0;
5150 if (!empty($options['keep_groups_and_groupings'])) {
5151 $oldcourse->defaultgroupingid = 0;
5153 $DB->update_record('course', $oldcourse);
5155 // Delete course sections.
5156 $DB->delete_records('course_sections', array('course' => $course->id));
5158 // Delete legacy, section and any other course files.
5159 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5161 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5162 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5163 // Easy, do not delete the context itself...
5164 $coursecontext->delete_content();
5165 } else {
5166 // Hack alert!!!!
5167 // We can not drop all context stuff because it would bork enrolments and roles,
5168 // there might be also files used by enrol plugins...
5171 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5172 // also some non-standard unsupported plugins may try to store something there.
5173 fulldelete($CFG->dataroot.'/'.$course->id);
5175 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5176 $cachemodinfo = cache::make('core', 'coursemodinfo');
5177 $cachemodinfo->delete($courseid);
5179 // Trigger a course content deleted event.
5180 $event = \core\event\course_content_deleted::create(array(
5181 'objectid' => $course->id,
5182 'context' => $coursecontext,
5183 'other' => array('shortname' => $course->shortname,
5184 'fullname' => $course->fullname,
5185 'options' => $options) // Passing this for legacy reasons.
5187 $event->add_record_snapshot('course', $course);
5188 $event->trigger();
5190 return true;
5194 * Change dates in module - used from course reset.
5196 * @param string $modname forum, assignment, etc
5197 * @param array $fields array of date fields from mod table
5198 * @param int $timeshift time difference
5199 * @param int $courseid
5200 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5201 * @return bool success
5203 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5204 global $CFG, $DB;
5205 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5207 $return = true;
5208 $params = array($timeshift, $courseid);
5209 foreach ($fields as $field) {
5210 $updatesql = "UPDATE {".$modname."}
5211 SET $field = $field + ?
5212 WHERE course=? AND $field<>0";
5213 if ($modid) {
5214 $updatesql .= ' AND id=?';
5215 $params[] = $modid;
5217 $return = $DB->execute($updatesql, $params) && $return;
5220 return $return;
5224 * This function will empty a course of user data.
5225 * It will retain the activities and the structure of the course.
5227 * @param object $data an object containing all the settings including courseid (without magic quotes)
5228 * @return array status array of array component, item, error
5230 function reset_course_userdata($data) {
5231 global $CFG, $DB;
5232 require_once($CFG->libdir.'/gradelib.php');
5233 require_once($CFG->libdir.'/completionlib.php');
5234 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5235 require_once($CFG->dirroot.'/group/lib.php');
5237 $data->courseid = $data->id;
5238 $context = context_course::instance($data->courseid);
5240 $eventparams = array(
5241 'context' => $context,
5242 'courseid' => $data->id,
5243 'other' => array(
5244 'reset_options' => (array) $data
5247 $event = \core\event\course_reset_started::create($eventparams);
5248 $event->trigger();
5250 // Calculate the time shift of dates.
5251 if (!empty($data->reset_start_date)) {
5252 // Time part of course startdate should be zero.
5253 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5254 } else {
5255 $data->timeshift = 0;
5258 // Result array: component, item, error.
5259 $status = array();
5261 // Start the resetting.
5262 $componentstr = get_string('general');
5264 // Move the course start time.
5265 if (!empty($data->reset_start_date) and $data->timeshift) {
5266 // Change course start data.
5267 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5268 // Update all course and group events - do not move activity events.
5269 $updatesql = "UPDATE {event}
5270 SET timestart = timestart + ?
5271 WHERE courseid=? AND instance=0";
5272 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5274 // Update any date activity restrictions.
5275 if ($CFG->enableavailability) {
5276 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5279 // Update completion expected dates.
5280 if ($CFG->enablecompletion) {
5281 $modinfo = get_fast_modinfo($data->courseid);
5282 $changed = false;
5283 foreach ($modinfo->get_cms() as $cm) {
5284 if ($cm->completion && !empty($cm->completionexpected)) {
5285 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5286 array('id' => $cm->id));
5287 $changed = true;
5291 // Clear course cache if changes made.
5292 if ($changed) {
5293 rebuild_course_cache($data->courseid, true);
5296 // Update course date completion criteria.
5297 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5300 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5303 if (!empty($data->reset_end_date)) {
5304 // If the user set a end date value respect it.
5305 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5306 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5307 // If there is a time shift apply it to the end date as well.
5308 $enddate = $data->reset_end_date_old + $data->timeshift;
5309 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5312 if (!empty($data->reset_events)) {
5313 $DB->delete_records('event', array('courseid' => $data->courseid));
5314 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5317 if (!empty($data->reset_notes)) {
5318 require_once($CFG->dirroot.'/notes/lib.php');
5319 note_delete_all($data->courseid);
5320 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5323 if (!empty($data->delete_blog_associations)) {
5324 require_once($CFG->dirroot.'/blog/lib.php');
5325 blog_remove_associations_for_course($data->courseid);
5326 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5329 if (!empty($data->reset_completion)) {
5330 // Delete course and activity completion information.
5331 $course = $DB->get_record('course', array('id' => $data->courseid));
5332 $cc = new completion_info($course);
5333 $cc->delete_all_completion_data();
5334 $status[] = array('component' => $componentstr,
5335 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5338 if (!empty($data->reset_competency_ratings)) {
5339 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5340 $status[] = array('component' => $componentstr,
5341 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5344 $componentstr = get_string('roles');
5346 if (!empty($data->reset_roles_overrides)) {
5347 $children = $context->get_child_contexts();
5348 foreach ($children as $child) {
5349 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5351 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5352 // Force refresh for logged in users.
5353 $context->mark_dirty();
5354 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5357 if (!empty($data->reset_roles_local)) {
5358 $children = $context->get_child_contexts();
5359 foreach ($children as $child) {
5360 role_unassign_all(array('contextid' => $child->id));
5362 // Force refresh for logged in users.
5363 $context->mark_dirty();
5364 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5367 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5368 $data->unenrolled = array();
5369 if (!empty($data->unenrol_users)) {
5370 $plugins = enrol_get_plugins(true);
5371 $instances = enrol_get_instances($data->courseid, true);
5372 foreach ($instances as $key => $instance) {
5373 if (!isset($plugins[$instance->enrol])) {
5374 unset($instances[$key]);
5375 continue;
5379 foreach ($data->unenrol_users as $withroleid) {
5380 if ($withroleid) {
5381 $sql = "SELECT ue.*
5382 FROM {user_enrolments} ue
5383 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5384 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5385 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5386 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5388 } else {
5389 // Without any role assigned at course context.
5390 $sql = "SELECT ue.*
5391 FROM {user_enrolments} ue
5392 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5393 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5394 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5395 WHERE ra.id IS null";
5396 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5399 $rs = $DB->get_recordset_sql($sql, $params);
5400 foreach ($rs as $ue) {
5401 if (!isset($instances[$ue->enrolid])) {
5402 continue;
5404 $instance = $instances[$ue->enrolid];
5405 $plugin = $plugins[$instance->enrol];
5406 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5407 continue;
5410 $plugin->unenrol_user($instance, $ue->userid);
5411 $data->unenrolled[$ue->userid] = $ue->userid;
5413 $rs->close();
5416 if (!empty($data->unenrolled)) {
5417 $status[] = array(
5418 'component' => $componentstr,
5419 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5420 'error' => false
5424 $componentstr = get_string('groups');
5426 // Remove all group members.
5427 if (!empty($data->reset_groups_members)) {
5428 groups_delete_group_members($data->courseid);
5429 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5432 // Remove all groups.
5433 if (!empty($data->reset_groups_remove)) {
5434 groups_delete_groups($data->courseid, false);
5435 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5438 // Remove all grouping members.
5439 if (!empty($data->reset_groupings_members)) {
5440 groups_delete_groupings_groups($data->courseid, false);
5441 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5444 // Remove all groupings.
5445 if (!empty($data->reset_groupings_remove)) {
5446 groups_delete_groupings($data->courseid, false);
5447 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5450 // Look in every instance of every module for data to delete.
5451 $unsupportedmods = array();
5452 if ($allmods = $DB->get_records('modules') ) {
5453 foreach ($allmods as $mod) {
5454 $modname = $mod->name;
5455 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5456 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5457 if (file_exists($modfile)) {
5458 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5459 continue; // Skip mods with no instances.
5461 include_once($modfile);
5462 if (function_exists($moddeleteuserdata)) {
5463 $modstatus = $moddeleteuserdata($data);
5464 if (is_array($modstatus)) {
5465 $status = array_merge($status, $modstatus);
5466 } else {
5467 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5469 } else {
5470 $unsupportedmods[] = $mod;
5472 } else {
5473 debugging('Missing lib.php in '.$modname.' module!');
5475 // Update calendar events for all modules.
5476 course_module_bulk_update_calendar_events($modname, $data->courseid);
5480 // Mention unsupported mods.
5481 if (!empty($unsupportedmods)) {
5482 foreach ($unsupportedmods as $mod) {
5483 $status[] = array(
5484 'component' => get_string('modulenameplural', $mod->name),
5485 'item' => '',
5486 'error' => get_string('resetnotimplemented')
5491 $componentstr = get_string('gradebook', 'grades');
5492 // Reset gradebook,.
5493 if (!empty($data->reset_gradebook_items)) {
5494 remove_course_grades($data->courseid, false);
5495 grade_grab_course_grades($data->courseid);
5496 grade_regrade_final_grades($data->courseid);
5497 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5499 } else if (!empty($data->reset_gradebook_grades)) {
5500 grade_course_reset($data->courseid);
5501 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5503 // Reset comments.
5504 if (!empty($data->reset_comments)) {
5505 require_once($CFG->dirroot.'/comment/lib.php');
5506 comment::reset_course_page_comments($context);
5509 $event = \core\event\course_reset_ended::create($eventparams);
5510 $event->trigger();
5512 return $status;
5516 * Generate an email processing address.
5518 * @param int $modid
5519 * @param string $modargs
5520 * @return string Returns email processing address
5522 function generate_email_processing_address($modid, $modargs) {
5523 global $CFG;
5525 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5526 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5532 * @todo Finish documenting this function
5534 * @param string $modargs
5535 * @param string $body Currently unused
5537 function moodle_process_email($modargs, $body) {
5538 global $DB;
5540 // The first char should be an unencoded letter. We'll take this as an action.
5541 switch ($modargs{0}) {
5542 case 'B': { // Bounce.
5543 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5544 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5545 // Check the half md5 of their email.
5546 $md5check = substr(md5($user->email), 0, 16);
5547 if ($md5check == substr($modargs, -16)) {
5548 set_bounce_count($user);
5550 // Else maybe they've already changed it?
5553 break;
5554 // Maybe more later?
5558 // CORRESPONDENCE.
5561 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5563 * @param string $action 'get', 'buffer', 'close' or 'flush'
5564 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5566 function get_mailer($action='get') {
5567 global $CFG;
5569 /** @var moodle_phpmailer $mailer */
5570 static $mailer = null;
5571 static $counter = 0;
5573 if (!isset($CFG->smtpmaxbulk)) {
5574 $CFG->smtpmaxbulk = 1;
5577 if ($action == 'get') {
5578 $prevkeepalive = false;
5580 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5581 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5582 $counter++;
5583 // Reset the mailer.
5584 $mailer->Priority = 3;
5585 $mailer->CharSet = 'UTF-8'; // Our default.
5586 $mailer->ContentType = "text/plain";
5587 $mailer->Encoding = "8bit";
5588 $mailer->From = "root@localhost";
5589 $mailer->FromName = "Root User";
5590 $mailer->Sender = "";
5591 $mailer->Subject = "";
5592 $mailer->Body = "";
5593 $mailer->AltBody = "";
5594 $mailer->ConfirmReadingTo = "";
5596 $mailer->clearAllRecipients();
5597 $mailer->clearReplyTos();
5598 $mailer->clearAttachments();
5599 $mailer->clearCustomHeaders();
5600 return $mailer;
5603 $prevkeepalive = $mailer->SMTPKeepAlive;
5604 get_mailer('flush');
5607 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5608 $mailer = new moodle_phpmailer();
5610 $counter = 1;
5612 if ($CFG->smtphosts == 'qmail') {
5613 // Use Qmail system.
5614 $mailer->isQmail();
5616 } else if (empty($CFG->smtphosts)) {
5617 // Use PHP mail() = sendmail.
5618 $mailer->isMail();
5620 } else {
5621 // Use SMTP directly.
5622 $mailer->isSMTP();
5623 if (!empty($CFG->debugsmtp)) {
5624 $mailer->SMTPDebug = 3;
5626 // Specify main and backup servers.
5627 $mailer->Host = $CFG->smtphosts;
5628 // Specify secure connection protocol.
5629 $mailer->SMTPSecure = $CFG->smtpsecure;
5630 // Use previous keepalive.
5631 $mailer->SMTPKeepAlive = $prevkeepalive;
5633 if ($CFG->smtpuser) {
5634 // Use SMTP authentication.
5635 $mailer->SMTPAuth = true;
5636 $mailer->Username = $CFG->smtpuser;
5637 $mailer->Password = $CFG->smtppass;
5641 return $mailer;
5644 $nothing = null;
5646 // Keep smtp session open after sending.
5647 if ($action == 'buffer') {
5648 if (!empty($CFG->smtpmaxbulk)) {
5649 get_mailer('flush');
5650 $m = get_mailer();
5651 if ($m->Mailer == 'smtp') {
5652 $m->SMTPKeepAlive = true;
5655 return $nothing;
5658 // Close smtp session, but continue buffering.
5659 if ($action == 'flush') {
5660 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5661 if (!empty($mailer->SMTPDebug)) {
5662 echo '<pre>'."\n";
5664 $mailer->SmtpClose();
5665 if (!empty($mailer->SMTPDebug)) {
5666 echo '</pre>';
5669 return $nothing;
5672 // Close smtp session, do not buffer anymore.
5673 if ($action == 'close') {
5674 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5675 get_mailer('flush');
5676 $mailer->SMTPKeepAlive = false;
5678 $mailer = null; // Better force new instance.
5679 return $nothing;
5684 * A helper function to test for email diversion
5686 * @param string $email
5687 * @return bool Returns true if the email should be diverted
5689 function email_should_be_diverted($email) {
5690 global $CFG;
5692 if (empty($CFG->divertallemailsto)) {
5693 return false;
5696 if (empty($CFG->divertallemailsexcept)) {
5697 return true;
5700 $patterns = array_map('trim', explode(',', $CFG->divertallemailsexcept));
5701 foreach ($patterns as $pattern) {
5702 if (preg_match("/$pattern/", $email)) {
5703 return false;
5707 return true;
5711 * Generate a unique email Message-ID using the moodle domain and install path
5713 * @param string $localpart An optional unique message id prefix.
5714 * @return string The formatted ID ready for appending to the email headers.
5716 function generate_email_messageid($localpart = null) {
5717 global $CFG;
5719 $urlinfo = parse_url($CFG->wwwroot);
5720 $base = '@' . $urlinfo['host'];
5722 // If multiple moodles are on the same domain we want to tell them
5723 // apart so we add the install path to the local part. This means
5724 // that the id local part should never contain a / character so
5725 // we can correctly parse the id to reassemble the wwwroot.
5726 if (isset($urlinfo['path'])) {
5727 $base = $urlinfo['path'] . $base;
5730 if (empty($localpart)) {
5731 $localpart = uniqid('', true);
5734 // Because we may have an option /installpath suffix to the local part
5735 // of the id we need to escape any / chars which are in the $localpart.
5736 $localpart = str_replace('/', '%2F', $localpart);
5738 return '<' . $localpart . $base . '>';
5742 * Send an email to a specified user
5744 * @param stdClass $user A {@link $USER} object
5745 * @param stdClass $from A {@link $USER} object
5746 * @param string $subject plain text subject line of the email
5747 * @param string $messagetext plain text version of the message
5748 * @param string $messagehtml complete html version of the message (optional)
5749 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5750 * @param string $attachname the name of the file (extension indicates MIME)
5751 * @param bool $usetrueaddress determines whether $from email address should
5752 * be sent out. Will be overruled by user profile setting for maildisplay
5753 * @param string $replyto Email address to reply to
5754 * @param string $replytoname Name of reply to recipient
5755 * @param int $wordwrapwidth custom word wrap width, default 79
5756 * @return bool Returns true if mail was sent OK and false if there was an error.
5758 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5759 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5761 global $CFG, $PAGE, $SITE;
5763 if (empty($user) or empty($user->id)) {
5764 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5765 return false;
5768 if (empty($user->email)) {
5769 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5770 return false;
5773 if (!empty($user->deleted)) {
5774 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5775 return false;
5778 if (defined('BEHAT_SITE_RUNNING')) {
5779 // Fake email sending in behat.
5780 return true;
5783 if (!empty($CFG->noemailever)) {
5784 // Hidden setting for development sites, set in config.php if needed.
5785 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5786 return true;
5789 if (email_should_be_diverted($user->email)) {
5790 $subject = "[DIVERTED {$user->email}] $subject";
5791 $user = clone($user);
5792 $user->email = $CFG->divertallemailsto;
5795 // Skip mail to suspended users.
5796 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5797 return true;
5800 if (!validate_email($user->email)) {
5801 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5802 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5803 return false;
5806 if (over_bounce_threshold($user)) {
5807 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5808 return false;
5811 // TLD .invalid is specifically reserved for invalid domain names.
5812 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5813 if (substr($user->email, -8) == '.invalid') {
5814 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5815 return true; // This is not an error.
5818 // If the user is a remote mnet user, parse the email text for URL to the
5819 // wwwroot and modify the url to direct the user's browser to login at their
5820 // home site (identity provider - idp) before hitting the link itself.
5821 if (is_mnet_remote_user($user)) {
5822 require_once($CFG->dirroot.'/mnet/lib.php');
5824 $jumpurl = mnet_get_idp_jump_url($user);
5825 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5827 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5828 $callback,
5829 $messagetext);
5830 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5831 $callback,
5832 $messagehtml);
5834 $mail = get_mailer();
5836 if (!empty($mail->SMTPDebug)) {
5837 echo '<pre>' . "\n";
5840 $temprecipients = array();
5841 $tempreplyto = array();
5843 // Make sure that we fall back onto some reasonable no-reply address.
5844 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
5845 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
5847 if (!validate_email($noreplyaddress)) {
5848 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
5849 $noreplyaddress = $noreplyaddressdefault;
5852 // Make up an email address for handling bounces.
5853 if (!empty($CFG->handlebounces)) {
5854 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5855 $mail->Sender = generate_email_processing_address(0, $modargs);
5856 } else {
5857 $mail->Sender = $noreplyaddress;
5860 // Make sure that the explicit replyto is valid, fall back to the implicit one.
5861 if (!empty($replyto) && !validate_email($replyto)) {
5862 debugging('email_to_user: Invalid replyto-email '.s($replyto));
5863 $replyto = $noreplyaddress;
5866 if (is_string($from)) { // So we can pass whatever we want if there is need.
5867 $mail->From = $noreplyaddress;
5868 $mail->FromName = $from;
5869 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
5870 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
5871 // in a course with the sender.
5872 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
5873 if (!validate_email($from->email)) {
5874 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
5875 // Better not to use $noreplyaddress in this case.
5876 return false;
5878 $mail->From = $from->email;
5879 $fromdetails = new stdClass();
5880 $fromdetails->name = fullname($from);
5881 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5882 $fromdetails->siteshortname = format_string($SITE->shortname);
5883 $fromstring = $fromdetails->name;
5884 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
5885 $fromstring = get_string('emailvia', 'core', $fromdetails);
5887 $mail->FromName = $fromstring;
5888 if (empty($replyto)) {
5889 $tempreplyto[] = array($from->email, fullname($from));
5891 } else {
5892 $mail->From = $noreplyaddress;
5893 $fromdetails = new stdClass();
5894 $fromdetails->name = fullname($from);
5895 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5896 $fromdetails->siteshortname = format_string($SITE->shortname);
5897 $fromstring = $fromdetails->name;
5898 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
5899 $fromstring = get_string('emailvia', 'core', $fromdetails);
5901 $mail->FromName = $fromstring;
5902 if (empty($replyto)) {
5903 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
5907 if (!empty($replyto)) {
5908 $tempreplyto[] = array($replyto, $replytoname);
5911 $temprecipients[] = array($user->email, fullname($user));
5913 // Set word wrap.
5914 $mail->WordWrap = $wordwrapwidth;
5916 if (!empty($from->customheaders)) {
5917 // Add custom headers.
5918 if (is_array($from->customheaders)) {
5919 foreach ($from->customheaders as $customheader) {
5920 $mail->addCustomHeader($customheader);
5922 } else {
5923 $mail->addCustomHeader($from->customheaders);
5927 // If the X-PHP-Originating-Script email header is on then also add an additional
5928 // header with details of where exactly in moodle the email was triggered from,
5929 // either a call to message_send() or to email_to_user().
5930 if (ini_get('mail.add_x_header')) {
5932 $stack = debug_backtrace(false);
5933 $origin = $stack[0];
5935 foreach ($stack as $depth => $call) {
5936 if ($call['function'] == 'message_send') {
5937 $origin = $call;
5941 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
5942 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
5943 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
5946 if (!empty($from->priority)) {
5947 $mail->Priority = $from->priority;
5950 $renderer = $PAGE->get_renderer('core');
5951 $context = array(
5952 'sitefullname' => $SITE->fullname,
5953 'siteshortname' => $SITE->shortname,
5954 'sitewwwroot' => $CFG->wwwroot,
5955 'subject' => $subject,
5956 'to' => $user->email,
5957 'toname' => fullname($user),
5958 'from' => $mail->From,
5959 'fromname' => $mail->FromName,
5961 if (!empty($tempreplyto[0])) {
5962 $context['replyto'] = $tempreplyto[0][0];
5963 $context['replytoname'] = $tempreplyto[0][1];
5965 if ($user->id > 0) {
5966 $context['touserid'] = $user->id;
5967 $context['tousername'] = $user->username;
5970 if (!empty($user->mailformat) && $user->mailformat == 1) {
5971 // Only process html templates if the user preferences allow html email.
5973 if ($messagehtml) {
5974 // If html has been given then pass it through the template.
5975 $context['body'] = $messagehtml;
5976 $messagehtml = $renderer->render_from_template('core/email_html', $context);
5978 } else {
5979 // If no html has been given, BUT there is an html wrapping template then
5980 // auto convert the text to html and then wrap it.
5981 $autohtml = trim(text_to_html($messagetext));
5982 $context['body'] = $autohtml;
5983 $temphtml = $renderer->render_from_template('core/email_html', $context);
5984 if ($autohtml != $temphtml) {
5985 $messagehtml = $temphtml;
5990 $context['body'] = $messagetext;
5991 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
5992 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
5993 $messagetext = $renderer->render_from_template('core/email_text', $context);
5995 // Autogenerate a MessageID if it's missing.
5996 if (empty($mail->MessageID)) {
5997 $mail->MessageID = generate_email_messageid();
6000 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6001 // Don't ever send HTML to users who don't want it.
6002 $mail->isHTML(true);
6003 $mail->Encoding = 'quoted-printable';
6004 $mail->Body = $messagehtml;
6005 $mail->AltBody = "\n$messagetext\n";
6006 } else {
6007 $mail->IsHTML(false);
6008 $mail->Body = "\n$messagetext\n";
6011 if ($attachment && $attachname) {
6012 if (preg_match( "~\\.\\.~" , $attachment )) {
6013 // Security check for ".." in dir path.
6014 $supportuser = core_user::get_support_user();
6015 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6016 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6017 } else {
6018 require_once($CFG->libdir.'/filelib.php');
6019 $mimetype = mimeinfo('type', $attachname);
6021 $attachmentpath = $attachment;
6023 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6024 $attachpath = str_replace('\\', '/', $attachmentpath);
6025 // Make sure both variables are normalised before comparing.
6026 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
6028 // If the attachment is a full path to a file in the tempdir, use it as is,
6029 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6030 if (strpos($attachpath, $temppath) !== 0) {
6031 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
6034 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
6038 // Check if the email should be sent in an other charset then the default UTF-8.
6039 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6041 // Use the defined site mail charset or eventually the one preferred by the recipient.
6042 $charset = $CFG->sitemailcharset;
6043 if (!empty($CFG->allowusermailcharset)) {
6044 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6045 $charset = $useremailcharset;
6049 // Convert all the necessary strings if the charset is supported.
6050 $charsets = get_list_of_charsets();
6051 unset($charsets['UTF-8']);
6052 if (in_array($charset, $charsets)) {
6053 $mail->CharSet = $charset;
6054 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6055 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6056 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6057 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6059 foreach ($temprecipients as $key => $values) {
6060 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6062 foreach ($tempreplyto as $key => $values) {
6063 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6068 foreach ($temprecipients as $values) {
6069 $mail->addAddress($values[0], $values[1]);
6071 foreach ($tempreplyto as $values) {
6072 $mail->addReplyTo($values[0], $values[1]);
6075 if ($mail->send()) {
6076 set_send_count($user);
6077 if (!empty($mail->SMTPDebug)) {
6078 echo '</pre>';
6080 return true;
6081 } else {
6082 // Trigger event for failing to send email.
6083 $event = \core\event\email_failed::create(array(
6084 'context' => context_system::instance(),
6085 'userid' => $from->id,
6086 'relateduserid' => $user->id,
6087 'other' => array(
6088 'subject' => $subject,
6089 'message' => $messagetext,
6090 'errorinfo' => $mail->ErrorInfo
6093 $event->trigger();
6094 if (CLI_SCRIPT) {
6095 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6097 if (!empty($mail->SMTPDebug)) {
6098 echo '</pre>';
6100 return false;
6105 * Check to see if a user's real email address should be used for the "From" field.
6107 * @param object $from The user object for the user we are sending the email from.
6108 * @param object $user The user object that we are sending the email to.
6109 * @param array $unused No longer used.
6110 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6112 function can_send_from_real_email_address($from, $user, $unused = null) {
6113 global $CFG;
6114 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6115 return false;
6117 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6118 // Email is in the list of allowed domains for sending email,
6119 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6120 // in a course with the sender.
6121 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6122 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6123 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6124 && enrol_get_shared_courses($user, $from, false, true)))) {
6125 return true;
6127 return false;
6131 * Generate a signoff for emails based on support settings
6133 * @return string
6135 function generate_email_signoff() {
6136 global $CFG;
6138 $signoff = "\n";
6139 if (!empty($CFG->supportname)) {
6140 $signoff .= $CFG->supportname."\n";
6142 if (!empty($CFG->supportemail)) {
6143 $signoff .= $CFG->supportemail."\n";
6145 if (!empty($CFG->supportpage)) {
6146 $signoff .= $CFG->supportpage."\n";
6148 return $signoff;
6152 * Sets specified user's password and send the new password to the user via email.
6154 * @param stdClass $user A {@link $USER} object
6155 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6156 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6158 function setnew_password_and_mail($user, $fasthash = false) {
6159 global $CFG, $DB;
6161 // We try to send the mail in language the user understands,
6162 // unfortunately the filter_string() does not support alternative langs yet
6163 // so multilang will not work properly for site->fullname.
6164 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6166 $site = get_site();
6168 $supportuser = core_user::get_support_user();
6170 $newpassword = generate_password();
6172 update_internal_user_password($user, $newpassword, $fasthash);
6174 $a = new stdClass();
6175 $a->firstname = fullname($user, true);
6176 $a->sitename = format_string($site->fullname);
6177 $a->username = $user->username;
6178 $a->newpassword = $newpassword;
6179 $a->link = $CFG->wwwroot .'/login/?lang='.$lang;
6180 $a->signoff = generate_email_signoff();
6182 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6184 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6186 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6187 return email_to_user($user, $supportuser, $subject, $message);
6192 * Resets specified user's password and send the new password to the user via email.
6194 * @param stdClass $user A {@link $USER} object
6195 * @return bool Returns true if mail was sent OK and false if there was an error.
6197 function reset_password_and_mail($user) {
6198 global $CFG;
6200 $site = get_site();
6201 $supportuser = core_user::get_support_user();
6203 $userauth = get_auth_plugin($user->auth);
6204 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6205 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6206 return false;
6209 $newpassword = generate_password();
6211 if (!$userauth->user_update_password($user, $newpassword)) {
6212 print_error("cannotsetpassword");
6215 $a = new stdClass();
6216 $a->firstname = $user->firstname;
6217 $a->lastname = $user->lastname;
6218 $a->sitename = format_string($site->fullname);
6219 $a->username = $user->username;
6220 $a->newpassword = $newpassword;
6221 $a->link = $CFG->wwwroot .'/login/change_password.php';
6222 $a->signoff = generate_email_signoff();
6224 $message = get_string('newpasswordtext', '', $a);
6226 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6228 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6230 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6231 return email_to_user($user, $supportuser, $subject, $message);
6235 * Send email to specified user with confirmation text and activation link.
6237 * @param stdClass $user A {@link $USER} object
6238 * @param string $confirmationurl user confirmation URL
6239 * @return bool Returns true if mail was sent OK and false if there was an error.
6241 function send_confirmation_email($user, $confirmationurl = null) {
6242 global $CFG;
6244 $site = get_site();
6245 $supportuser = core_user::get_support_user();
6247 $data = new stdClass();
6248 $data->firstname = fullname($user);
6249 $data->sitename = format_string($site->fullname);
6250 $data->admin = generate_email_signoff();
6252 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6254 if (empty($confirmationurl)) {
6255 $confirmationurl = '/login/confirm.php';
6258 $confirmationurl = new moodle_url($confirmationurl);
6259 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6260 $confirmationurl->remove_params('data');
6261 $confirmationpath = $confirmationurl->out(false);
6263 // We need to custom encode the username to include trailing dots in the link.
6264 // Because of this custom encoding we can't use moodle_url directly.
6265 // Determine if a query string is present in the confirmation url.
6266 $hasquerystring = strpos($confirmationpath, '?') !== false;
6267 // Perform normal url encoding of the username first.
6268 $username = urlencode($user->username);
6269 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6270 $username = str_replace('.', '%2E', $username);
6272 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6274 $message = get_string('emailconfirmation', '', $data);
6275 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6277 $user->mailformat = 1; // Always send HTML version as well.
6279 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6280 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6284 * Sends a password change confirmation email.
6286 * @param stdClass $user A {@link $USER} object
6287 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6288 * @return bool Returns true if mail was sent OK and false if there was an error.
6290 function send_password_change_confirmation_email($user, $resetrecord) {
6291 global $CFG;
6293 $site = get_site();
6294 $supportuser = core_user::get_support_user();
6295 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6297 $data = new stdClass();
6298 $data->firstname = $user->firstname;
6299 $data->lastname = $user->lastname;
6300 $data->username = $user->username;
6301 $data->sitename = format_string($site->fullname);
6302 $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6303 $data->admin = generate_email_signoff();
6304 $data->resetminutes = $pwresetmins;
6306 $message = get_string('emailresetconfirmation', '', $data);
6307 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6309 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6310 return email_to_user($user, $supportuser, $subject, $message);
6315 * Sends an email containinginformation on how to change your password.
6317 * @param stdClass $user A {@link $USER} object
6318 * @return bool Returns true if mail was sent OK and false if there was an error.
6320 function send_password_change_info($user) {
6321 global $CFG;
6323 $site = get_site();
6324 $supportuser = core_user::get_support_user();
6325 $systemcontext = context_system::instance();
6327 $data = new stdClass();
6328 $data->firstname = $user->firstname;
6329 $data->lastname = $user->lastname;
6330 $data->username = $user->username;
6331 $data->sitename = format_string($site->fullname);
6332 $data->admin = generate_email_signoff();
6334 $userauth = get_auth_plugin($user->auth);
6336 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6337 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6338 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6339 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6340 return email_to_user($user, $supportuser, $subject, $message);
6343 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6344 // We have some external url for password changing.
6345 $data->link .= $userauth->change_password_url();
6347 } else {
6348 // No way to change password, sorry.
6349 $data->link = '';
6352 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6353 $message = get_string('emailpasswordchangeinfo', '', $data);
6354 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6355 } else {
6356 $message = get_string('emailpasswordchangeinfofail', '', $data);
6357 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6360 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6361 return email_to_user($user, $supportuser, $subject, $message);
6366 * Check that an email is allowed. It returns an error message if there was a problem.
6368 * @param string $email Content of email
6369 * @return string|false
6371 function email_is_not_allowed($email) {
6372 global $CFG;
6374 if (!empty($CFG->allowemailaddresses)) {
6375 $allowed = explode(' ', $CFG->allowemailaddresses);
6376 foreach ($allowed as $allowedpattern) {
6377 $allowedpattern = trim($allowedpattern);
6378 if (!$allowedpattern) {
6379 continue;
6381 if (strpos($allowedpattern, '.') === 0) {
6382 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6383 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6384 return false;
6387 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6388 return false;
6391 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6393 } else if (!empty($CFG->denyemailaddresses)) {
6394 $denied = explode(' ', $CFG->denyemailaddresses);
6395 foreach ($denied as $deniedpattern) {
6396 $deniedpattern = trim($deniedpattern);
6397 if (!$deniedpattern) {
6398 continue;
6400 if (strpos($deniedpattern, '.') === 0) {
6401 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6402 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6403 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6406 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6407 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6412 return false;
6415 // FILE HANDLING.
6418 * Returns local file storage instance
6420 * @return file_storage
6422 function get_file_storage($reset = false) {
6423 global $CFG;
6425 static $fs = null;
6427 if ($reset) {
6428 $fs = null;
6429 return;
6432 if ($fs) {
6433 return $fs;
6436 require_once("$CFG->libdir/filelib.php");
6438 $fs = new file_storage();
6440 return $fs;
6444 * Returns local file storage instance
6446 * @return file_browser
6448 function get_file_browser() {
6449 global $CFG;
6451 static $fb = null;
6453 if ($fb) {
6454 return $fb;
6457 require_once("$CFG->libdir/filelib.php");
6459 $fb = new file_browser();
6461 return $fb;
6465 * Returns file packer
6467 * @param string $mimetype default application/zip
6468 * @return file_packer
6470 function get_file_packer($mimetype='application/zip') {
6471 global $CFG;
6473 static $fp = array();
6475 if (isset($fp[$mimetype])) {
6476 return $fp[$mimetype];
6479 switch ($mimetype) {
6480 case 'application/zip':
6481 case 'application/vnd.moodle.profiling':
6482 $classname = 'zip_packer';
6483 break;
6485 case 'application/x-gzip' :
6486 $classname = 'tgz_packer';
6487 break;
6489 case 'application/vnd.moodle.backup':
6490 $classname = 'mbz_packer';
6491 break;
6493 default:
6494 return false;
6497 require_once("$CFG->libdir/filestorage/$classname.php");
6498 $fp[$mimetype] = new $classname();
6500 return $fp[$mimetype];
6504 * Returns current name of file on disk if it exists.
6506 * @param string $newfile File to be verified
6507 * @return string Current name of file on disk if true
6509 function valid_uploaded_file($newfile) {
6510 if (empty($newfile)) {
6511 return '';
6513 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6514 return $newfile['tmp_name'];
6515 } else {
6516 return '';
6521 * Returns the maximum size for uploading files.
6523 * There are seven possible upload limits:
6524 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6525 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6526 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6527 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6528 * 5. by the Moodle admin in $CFG->maxbytes
6529 * 6. by the teacher in the current course $course->maxbytes
6530 * 7. by the teacher for the current module, eg $assignment->maxbytes
6532 * These last two are passed to this function as arguments (in bytes).
6533 * Anything defined as 0 is ignored.
6534 * The smallest of all the non-zero numbers is returned.
6536 * @todo Finish documenting this function
6538 * @param int $sitebytes Set maximum size
6539 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6540 * @param int $modulebytes Current module ->maxbytes (in bytes)
6541 * @param bool $unused This parameter has been deprecated and is not used any more.
6542 * @return int The maximum size for uploading files.
6544 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6546 if (! $filesize = ini_get('upload_max_filesize')) {
6547 $filesize = '5M';
6549 $minimumsize = get_real_size($filesize);
6551 if ($postsize = ini_get('post_max_size')) {
6552 $postsize = get_real_size($postsize);
6553 if ($postsize < $minimumsize) {
6554 $minimumsize = $postsize;
6558 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6559 $minimumsize = $sitebytes;
6562 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6563 $minimumsize = $coursebytes;
6566 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6567 $minimumsize = $modulebytes;
6570 return $minimumsize;
6574 * Returns the maximum size for uploading files for the current user
6576 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6578 * @param context $context The context in which to check user capabilities
6579 * @param int $sitebytes Set maximum size
6580 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6581 * @param int $modulebytes Current module ->maxbytes (in bytes)
6582 * @param stdClass $user The user
6583 * @param bool $unused This parameter has been deprecated and is not used any more.
6584 * @return int The maximum size for uploading files.
6586 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6587 $unused = false) {
6588 global $USER;
6590 if (empty($user)) {
6591 $user = $USER;
6594 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6595 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6598 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6602 * Returns an array of possible sizes in local language
6604 * Related to {@link get_max_upload_file_size()} - this function returns an
6605 * array of possible sizes in an array, translated to the
6606 * local language.
6608 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6610 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6611 * with the value set to 0. This option will be the first in the list.
6613 * @uses SORT_NUMERIC
6614 * @param int $sitebytes Set maximum size
6615 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6616 * @param int $modulebytes Current module ->maxbytes (in bytes)
6617 * @param int|array $custombytes custom upload size/s which will be added to list,
6618 * Only value/s smaller then maxsize will be added to list.
6619 * @return array
6621 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6622 global $CFG;
6624 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6625 return array();
6628 if ($sitebytes == 0) {
6629 // Will get the minimum of upload_max_filesize or post_max_size.
6630 $sitebytes = get_max_upload_file_size();
6633 $filesize = array();
6634 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6635 5242880, 10485760, 20971520, 52428800, 104857600,
6636 262144000, 524288000, 786432000, 1073741824,
6637 2147483648, 4294967296, 8589934592);
6639 // If custombytes is given and is valid then add it to the list.
6640 if (is_number($custombytes) and $custombytes > 0) {
6641 $custombytes = (int)$custombytes;
6642 if (!in_array($custombytes, $sizelist)) {
6643 $sizelist[] = $custombytes;
6645 } else if (is_array($custombytes)) {
6646 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6649 // Allow maxbytes to be selected if it falls outside the above boundaries.
6650 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6651 // Note: get_real_size() is used in order to prevent problems with invalid values.
6652 $sizelist[] = get_real_size($CFG->maxbytes);
6655 foreach ($sizelist as $sizebytes) {
6656 if ($sizebytes < $maxsize && $sizebytes > 0) {
6657 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6661 $limitlevel = '';
6662 $displaysize = '';
6663 if ($modulebytes &&
6664 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6665 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6666 $limitlevel = get_string('activity', 'core');
6667 $displaysize = display_size($modulebytes);
6668 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6670 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6671 $limitlevel = get_string('course', 'core');
6672 $displaysize = display_size($coursebytes);
6673 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6675 } else if ($sitebytes) {
6676 $limitlevel = get_string('site', 'core');
6677 $displaysize = display_size($sitebytes);
6678 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6681 krsort($filesize, SORT_NUMERIC);
6682 if ($limitlevel) {
6683 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6684 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6687 return $filesize;
6691 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6693 * If excludefiles is defined, then that file/directory is ignored
6694 * If getdirs is true, then (sub)directories are included in the output
6695 * If getfiles is true, then files are included in the output
6696 * (at least one of these must be true!)
6698 * @todo Finish documenting this function. Add examples of $excludefile usage.
6700 * @param string $rootdir A given root directory to start from
6701 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6702 * @param bool $descend If true then subdirectories are recursed as well
6703 * @param bool $getdirs If true then (sub)directories are included in the output
6704 * @param bool $getfiles If true then files are included in the output
6705 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6707 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6709 $dirs = array();
6711 if (!$getdirs and !$getfiles) { // Nothing to show.
6712 return $dirs;
6715 if (!is_dir($rootdir)) { // Must be a directory.
6716 return $dirs;
6719 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6720 return $dirs;
6723 if (!is_array($excludefiles)) {
6724 $excludefiles = array($excludefiles);
6727 while (false !== ($file = readdir($dir))) {
6728 $firstchar = substr($file, 0, 1);
6729 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6730 continue;
6732 $fullfile = $rootdir .'/'. $file;
6733 if (filetype($fullfile) == 'dir') {
6734 if ($getdirs) {
6735 $dirs[] = $file;
6737 if ($descend) {
6738 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6739 foreach ($subdirs as $subdir) {
6740 $dirs[] = $file .'/'. $subdir;
6743 } else if ($getfiles) {
6744 $dirs[] = $file;
6747 closedir($dir);
6749 asort($dirs);
6751 return $dirs;
6756 * Adds up all the files in a directory and works out the size.
6758 * @param string $rootdir The directory to start from
6759 * @param string $excludefile A file to exclude when summing directory size
6760 * @return int The summed size of all files and subfiles within the root directory
6762 function get_directory_size($rootdir, $excludefile='') {
6763 global $CFG;
6765 // Do it this way if we can, it's much faster.
6766 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6767 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6768 $output = null;
6769 $return = null;
6770 exec($command, $output, $return);
6771 if (is_array($output)) {
6772 // We told it to return k.
6773 return get_real_size(intval($output[0]).'k');
6777 if (!is_dir($rootdir)) {
6778 // Must be a directory.
6779 return 0;
6782 if (!$dir = @opendir($rootdir)) {
6783 // Can't open it for some reason.
6784 return 0;
6787 $size = 0;
6789 while (false !== ($file = readdir($dir))) {
6790 $firstchar = substr($file, 0, 1);
6791 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6792 continue;
6794 $fullfile = $rootdir .'/'. $file;
6795 if (filetype($fullfile) == 'dir') {
6796 $size += get_directory_size($fullfile, $excludefile);
6797 } else {
6798 $size += filesize($fullfile);
6801 closedir($dir);
6803 return $size;
6807 * Converts bytes into display form
6809 * @static string $gb Localized string for size in gigabytes
6810 * @static string $mb Localized string for size in megabytes
6811 * @static string $kb Localized string for size in kilobytes
6812 * @static string $b Localized string for size in bytes
6813 * @param int $size The size to convert to human readable form
6814 * @return string
6816 function display_size($size) {
6818 static $gb, $mb, $kb, $b;
6820 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6821 return get_string('unlimited');
6824 if (empty($gb)) {
6825 $gb = get_string('sizegb');
6826 $mb = get_string('sizemb');
6827 $kb = get_string('sizekb');
6828 $b = get_string('sizeb');
6831 if ($size >= 1073741824) {
6832 $size = round($size / 1073741824 * 10) / 10 . $gb;
6833 } else if ($size >= 1048576) {
6834 $size = round($size / 1048576 * 10) / 10 . $mb;
6835 } else if ($size >= 1024) {
6836 $size = round($size / 1024 * 10) / 10 . $kb;
6837 } else {
6838 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6840 return $size;
6844 * Cleans a given filename by removing suspicious or troublesome characters
6846 * @see clean_param()
6847 * @param string $string file name
6848 * @return string cleaned file name
6850 function clean_filename($string) {
6851 return clean_param($string, PARAM_FILE);
6854 // STRING TRANSLATION.
6857 * Returns the code for the current language
6859 * @category string
6860 * @return string
6862 function current_language() {
6863 global $CFG, $USER, $SESSION, $COURSE;
6865 if (!empty($SESSION->forcelang)) {
6866 // Allows overriding course-forced language (useful for admins to check
6867 // issues in courses whose language they don't understand).
6868 // Also used by some code to temporarily get language-related information in a
6869 // specific language (see force_current_language()).
6870 $return = $SESSION->forcelang;
6872 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6873 // Course language can override all other settings for this page.
6874 $return = $COURSE->lang;
6876 } else if (!empty($SESSION->lang)) {
6877 // Session language can override other settings.
6878 $return = $SESSION->lang;
6880 } else if (!empty($USER->lang)) {
6881 $return = $USER->lang;
6883 } else if (isset($CFG->lang)) {
6884 $return = $CFG->lang;
6886 } else {
6887 $return = 'en';
6890 // Just in case this slipped in from somewhere by accident.
6891 $return = str_replace('_utf8', '', $return);
6893 return $return;
6897 * Returns parent language of current active language if defined
6899 * @category string
6900 * @param string $lang null means current language
6901 * @return string
6903 function get_parent_language($lang=null) {
6905 // Let's hack around the current language.
6906 if (!empty($lang)) {
6907 $oldforcelang = force_current_language($lang);
6910 $parentlang = get_string('parentlanguage', 'langconfig');
6911 if ($parentlang === 'en') {
6912 $parentlang = '';
6915 // Let's hack around the current language.
6916 if (!empty($lang)) {
6917 force_current_language($oldforcelang);
6920 return $parentlang;
6924 * Force the current language to get strings and dates localised in the given language.
6926 * After calling this function, all strings will be provided in the given language
6927 * until this function is called again, or equivalent code is run.
6929 * @param string $language
6930 * @return string previous $SESSION->forcelang value
6932 function force_current_language($language) {
6933 global $SESSION;
6934 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6935 if ($language !== $sessionforcelang) {
6936 // Seting forcelang to null or an empty string disables it's effect.
6937 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6938 $SESSION->forcelang = $language;
6939 moodle_setlocale();
6942 return $sessionforcelang;
6946 * Returns current string_manager instance.
6948 * The param $forcereload is needed for CLI installer only where the string_manager instance
6949 * must be replaced during the install.php script life time.
6951 * @category string
6952 * @param bool $forcereload shall the singleton be released and new instance created instead?
6953 * @return core_string_manager
6955 function get_string_manager($forcereload=false) {
6956 global $CFG;
6958 static $singleton = null;
6960 if ($forcereload) {
6961 $singleton = null;
6963 if ($singleton === null) {
6964 if (empty($CFG->early_install_lang)) {
6966 if (empty($CFG->langlist)) {
6967 $translist = array();
6968 } else {
6969 $translist = explode(',', $CFG->langlist);
6970 $translist = array_map('trim', $translist);
6973 if (!empty($CFG->config_php_settings['customstringmanager'])) {
6974 $classname = $CFG->config_php_settings['customstringmanager'];
6976 if (class_exists($classname)) {
6977 $implements = class_implements($classname);
6979 if (isset($implements['core_string_manager'])) {
6980 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist);
6981 return $singleton;
6983 } else {
6984 debugging('Unable to instantiate custom string manager: class '.$classname.
6985 ' does not implement the core_string_manager interface.');
6988 } else {
6989 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
6993 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6995 } else {
6996 $singleton = new core_string_manager_install();
7000 return $singleton;
7004 * Returns a localized string.
7006 * Returns the translated string specified by $identifier as
7007 * for $module. Uses the same format files as STphp.
7008 * $a is an object, string or number that can be used
7009 * within translation strings
7011 * eg 'hello {$a->firstname} {$a->lastname}'
7012 * or 'hello {$a}'
7014 * If you would like to directly echo the localized string use
7015 * the function {@link print_string()}
7017 * Example usage of this function involves finding the string you would
7018 * like a local equivalent of and using its identifier and module information
7019 * to retrieve it.<br/>
7020 * If you open moodle/lang/en/moodle.php and look near line 278
7021 * you will find a string to prompt a user for their word for 'course'
7022 * <code>
7023 * $string['course'] = 'Course';
7024 * </code>
7025 * So if you want to display the string 'Course'
7026 * in any language that supports it on your site
7027 * you just need to use the identifier 'course'
7028 * <code>
7029 * $mystring = '<strong>'. get_string('course') .'</strong>';
7030 * or
7031 * </code>
7032 * If the string you want is in another file you'd take a slightly
7033 * different approach. Looking in moodle/lang/en/calendar.php you find
7034 * around line 75:
7035 * <code>
7036 * $string['typecourse'] = 'Course event';
7037 * </code>
7038 * If you want to display the string "Course event" in any language
7039 * supported you would use the identifier 'typecourse' and the module 'calendar'
7040 * (because it is in the file calendar.php):
7041 * <code>
7042 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7043 * </code>
7045 * As a last resort, should the identifier fail to map to a string
7046 * the returned string will be [[ $identifier ]]
7048 * In Moodle 2.3 there is a new argument to this function $lazyload.
7049 * Setting $lazyload to true causes get_string to return a lang_string object
7050 * rather than the string itself. The fetching of the string is then put off until
7051 * the string object is first used. The object can be used by calling it's out
7052 * method or by casting the object to a string, either directly e.g.
7053 * (string)$stringobject
7054 * or indirectly by using the string within another string or echoing it out e.g.
7055 * echo $stringobject
7056 * return "<p>{$stringobject}</p>";
7057 * It is worth noting that using $lazyload and attempting to use the string as an
7058 * array key will cause a fatal error as objects cannot be used as array keys.
7059 * But you should never do that anyway!
7060 * For more information {@link lang_string}
7062 * @category string
7063 * @param string $identifier The key identifier for the localized string
7064 * @param string $component The module where the key identifier is stored,
7065 * usually expressed as the filename in the language pack without the
7066 * .php on the end but can also be written as mod/forum or grade/export/xls.
7067 * If none is specified then moodle.php is used.
7068 * @param string|object|array $a An object, string or number that can be used
7069 * within translation strings
7070 * @param bool $lazyload If set to true a string object is returned instead of
7071 * the string itself. The string then isn't calculated until it is first used.
7072 * @return string The localized string.
7073 * @throws coding_exception
7075 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7076 global $CFG;
7078 // If the lazy load argument has been supplied return a lang_string object
7079 // instead.
7080 // We need to make sure it is true (and a bool) as you will see below there
7081 // used to be a forth argument at one point.
7082 if ($lazyload === true) {
7083 return new lang_string($identifier, $component, $a);
7086 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7087 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7090 // There is now a forth argument again, this time it is a boolean however so
7091 // we can still check for the old extralocations parameter.
7092 if (!is_bool($lazyload) && !empty($lazyload)) {
7093 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7096 if (strpos($component, '/') !== false) {
7097 debugging('The module name you passed to get_string is the deprecated format ' .
7098 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7099 $componentpath = explode('/', $component);
7101 switch ($componentpath[0]) {
7102 case 'mod':
7103 $component = $componentpath[1];
7104 break;
7105 case 'blocks':
7106 case 'block':
7107 $component = 'block_'.$componentpath[1];
7108 break;
7109 case 'enrol':
7110 $component = 'enrol_'.$componentpath[1];
7111 break;
7112 case 'format':
7113 $component = 'format_'.$componentpath[1];
7114 break;
7115 case 'grade':
7116 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7117 break;
7121 $result = get_string_manager()->get_string($identifier, $component, $a);
7123 // Debugging feature lets you display string identifier and component.
7124 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7125 $result .= ' {' . $identifier . '/' . $component . '}';
7127 return $result;
7131 * Converts an array of strings to their localized value.
7133 * @param array $array An array of strings
7134 * @param string $component The language module that these strings can be found in.
7135 * @return stdClass translated strings.
7137 function get_strings($array, $component = '') {
7138 $string = new stdClass;
7139 foreach ($array as $item) {
7140 $string->$item = get_string($item, $component);
7142 return $string;
7146 * Prints out a translated string.
7148 * Prints out a translated string using the return value from the {@link get_string()} function.
7150 * Example usage of this function when the string is in the moodle.php file:<br/>
7151 * <code>
7152 * echo '<strong>';
7153 * print_string('course');
7154 * echo '</strong>';
7155 * </code>
7157 * Example usage of this function when the string is not in the moodle.php file:<br/>
7158 * <code>
7159 * echo '<h1>';
7160 * print_string('typecourse', 'calendar');
7161 * echo '</h1>';
7162 * </code>
7164 * @category string
7165 * @param string $identifier The key identifier for the localized string
7166 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7167 * @param string|object|array $a An object, string or number that can be used within translation strings
7169 function print_string($identifier, $component = '', $a = null) {
7170 echo get_string($identifier, $component, $a);
7174 * Returns a list of charset codes
7176 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7177 * (checking that such charset is supported by the texlib library!)
7179 * @return array And associative array with contents in the form of charset => charset
7181 function get_list_of_charsets() {
7183 $charsets = array(
7184 'EUC-JP' => 'EUC-JP',
7185 'ISO-2022-JP'=> 'ISO-2022-JP',
7186 'ISO-8859-1' => 'ISO-8859-1',
7187 'SHIFT-JIS' => 'SHIFT-JIS',
7188 'GB2312' => 'GB2312',
7189 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7190 'UTF-8' => 'UTF-8');
7192 asort($charsets);
7194 return $charsets;
7198 * Returns a list of valid and compatible themes
7200 * @return array
7202 function get_list_of_themes() {
7203 global $CFG;
7205 $themes = array();
7207 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7208 $themelist = explode(',', $CFG->themelist);
7209 } else {
7210 $themelist = array_keys(core_component::get_plugin_list("theme"));
7213 foreach ($themelist as $key => $themename) {
7214 $theme = theme_config::load($themename);
7215 $themes[$themename] = $theme;
7218 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7220 return $themes;
7224 * Factory function for emoticon_manager
7226 * @return emoticon_manager singleton
7228 function get_emoticon_manager() {
7229 static $singleton = null;
7231 if (is_null($singleton)) {
7232 $singleton = new emoticon_manager();
7235 return $singleton;
7239 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7241 * Whenever this manager mentiones 'emoticon object', the following data
7242 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7243 * altidentifier and altcomponent
7245 * @see admin_setting_emoticons
7247 * @copyright 2010 David Mudrak
7248 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7250 class emoticon_manager {
7253 * Returns the currently enabled emoticons
7255 * @return array of emoticon objects
7257 public function get_emoticons() {
7258 global $CFG;
7260 if (empty($CFG->emoticons)) {
7261 return array();
7264 $emoticons = $this->decode_stored_config($CFG->emoticons);
7266 if (!is_array($emoticons)) {
7267 // Something is wrong with the format of stored setting.
7268 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7269 return array();
7272 return $emoticons;
7276 * Converts emoticon object into renderable pix_emoticon object
7278 * @param stdClass $emoticon emoticon object
7279 * @param array $attributes explicit HTML attributes to set
7280 * @return pix_emoticon
7282 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7283 $stringmanager = get_string_manager();
7284 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7285 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7286 } else {
7287 $alt = s($emoticon->text);
7289 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7293 * Encodes the array of emoticon objects into a string storable in config table
7295 * @see self::decode_stored_config()
7296 * @param array $emoticons array of emtocion objects
7297 * @return string
7299 public function encode_stored_config(array $emoticons) {
7300 return json_encode($emoticons);
7304 * Decodes the string into an array of emoticon objects
7306 * @see self::encode_stored_config()
7307 * @param string $encoded
7308 * @return string|null
7310 public function decode_stored_config($encoded) {
7311 $decoded = json_decode($encoded);
7312 if (!is_array($decoded)) {
7313 return null;
7315 return $decoded;
7319 * Returns default set of emoticons supported by Moodle
7321 * @return array of sdtClasses
7323 public function default_emoticons() {
7324 return array(
7325 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7326 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7327 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7328 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7329 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7330 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7331 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7332 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7333 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7334 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7335 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7336 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7337 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7338 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7339 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7340 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7341 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7342 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7343 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7344 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7345 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7346 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7347 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7348 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7349 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7350 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7351 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7352 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7353 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7354 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7359 * Helper method preparing the stdClass with the emoticon properties
7361 * @param string|array $text or array of strings
7362 * @param string $imagename to be used by {@link pix_emoticon}
7363 * @param string $altidentifier alternative string identifier, null for no alt
7364 * @param string $altcomponent where the alternative string is defined
7365 * @param string $imagecomponent to be used by {@link pix_emoticon}
7366 * @return stdClass
7368 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7369 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7370 return (object)array(
7371 'text' => $text,
7372 'imagename' => $imagename,
7373 'imagecomponent' => $imagecomponent,
7374 'altidentifier' => $altidentifier,
7375 'altcomponent' => $altcomponent,
7380 // ENCRYPTION.
7383 * rc4encrypt
7385 * @param string $data Data to encrypt.
7386 * @return string The now encrypted data.
7388 function rc4encrypt($data) {
7389 return endecrypt(get_site_identifier(), $data, '');
7393 * rc4decrypt
7395 * @param string $data Data to decrypt.
7396 * @return string The now decrypted data.
7398 function rc4decrypt($data) {
7399 return endecrypt(get_site_identifier(), $data, 'de');
7403 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7405 * @todo Finish documenting this function
7407 * @param string $pwd The password to use when encrypting or decrypting
7408 * @param string $data The data to be decrypted/encrypted
7409 * @param string $case Either 'de' for decrypt or '' for encrypt
7410 * @return string
7412 function endecrypt ($pwd, $data, $case) {
7414 if ($case == 'de') {
7415 $data = urldecode($data);
7418 $key[] = '';
7419 $box[] = '';
7420 $pwdlength = strlen($pwd);
7422 for ($i = 0; $i <= 255; $i++) {
7423 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7424 $box[$i] = $i;
7427 $x = 0;
7429 for ($i = 0; $i <= 255; $i++) {
7430 $x = ($x + $box[$i] + $key[$i]) % 256;
7431 $tempswap = $box[$i];
7432 $box[$i] = $box[$x];
7433 $box[$x] = $tempswap;
7436 $cipher = '';
7438 $a = 0;
7439 $j = 0;
7441 for ($i = 0; $i < strlen($data); $i++) {
7442 $a = ($a + 1) % 256;
7443 $j = ($j + $box[$a]) % 256;
7444 $temp = $box[$a];
7445 $box[$a] = $box[$j];
7446 $box[$j] = $temp;
7447 $k = $box[(($box[$a] + $box[$j]) % 256)];
7448 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7449 $cipher .= chr($cipherby);
7452 if ($case == 'de') {
7453 $cipher = urldecode(urlencode($cipher));
7454 } else {
7455 $cipher = urlencode($cipher);
7458 return $cipher;
7461 // ENVIRONMENT CHECKING.
7464 * This method validates a plug name. It is much faster than calling clean_param.
7466 * @param string $name a string that might be a plugin name.
7467 * @return bool if this string is a valid plugin name.
7469 function is_valid_plugin_name($name) {
7470 // This does not work for 'mod', bad luck, use any other type.
7471 return core_component::is_valid_plugin_name('tool', $name);
7475 * Get a list of all the plugins of a given type that define a certain API function
7476 * in a certain file. The plugin component names and function names are returned.
7478 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7479 * @param string $function the part of the name of the function after the
7480 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7481 * names like report_courselist_hook.
7482 * @param string $file the name of file within the plugin that defines the
7483 * function. Defaults to lib.php.
7484 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7485 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7487 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7488 global $CFG;
7490 // We don't include here as all plugin types files would be included.
7491 $plugins = get_plugins_with_function($function, $file, false);
7493 if (empty($plugins[$plugintype])) {
7494 return array();
7497 $allplugins = core_component::get_plugin_list($plugintype);
7499 // Reformat the array and include the files.
7500 $pluginfunctions = array();
7501 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7503 // Check that it has not been removed and the file is still available.
7504 if (!empty($allplugins[$pluginname])) {
7506 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7507 if (file_exists($filepath)) {
7508 include_once($filepath);
7509 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7514 return $pluginfunctions;
7518 * Get a list of all the plugins that define a certain API function in a certain file.
7520 * @param string $function the part of the name of the function after the
7521 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7522 * names like report_courselist_hook.
7523 * @param string $file the name of file within the plugin that defines the
7524 * function. Defaults to lib.php.
7525 * @param bool $include Whether to include the files that contain the functions or not.
7526 * @return array with [plugintype][plugin] = functionname
7528 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7529 global $CFG;
7531 if (during_initial_install() || isset($CFG->upgraderunning)) {
7532 // API functions _must not_ be called during an installation or upgrade.
7533 return [];
7536 $cache = \cache::make('core', 'plugin_functions');
7538 // Including both although I doubt that we will find two functions definitions with the same name.
7539 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7540 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7541 $pluginfunctions = $cache->get($key);
7543 // Use the plugin manager to check that plugins are currently installed.
7544 $pluginmanager = \core_plugin_manager::instance();
7546 if ($pluginfunctions !== false) {
7548 // Checking that the files are still available.
7549 foreach ($pluginfunctions as $plugintype => $plugins) {
7551 $allplugins = \core_component::get_plugin_list($plugintype);
7552 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7553 foreach ($plugins as $plugin => $function) {
7554 if (!isset($installedplugins[$plugin])) {
7555 // Plugin code is still present on disk but it is not installed.
7556 unset($pluginfunctions[$plugintype][$plugin]);
7557 continue;
7560 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7561 if (empty($allplugins[$plugin])) {
7562 unset($pluginfunctions[$plugintype][$plugin]);
7563 continue;
7566 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7567 if ($include && $fileexists) {
7568 // Include the files if it was requested.
7569 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7570 } else if (!$fileexists) {
7571 // If the file is not available any more it should not be returned.
7572 unset($pluginfunctions[$plugintype][$plugin]);
7576 return $pluginfunctions;
7579 $pluginfunctions = array();
7581 // To fill the cached. Also, everything should continue working with cache disabled.
7582 $plugintypes = \core_component::get_plugin_types();
7583 foreach ($plugintypes as $plugintype => $unused) {
7585 // We need to include files here.
7586 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7587 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7588 foreach ($pluginswithfile as $plugin => $notused) {
7590 if (!isset($installedplugins[$plugin])) {
7591 continue;
7594 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7596 $pluginfunction = false;
7597 if (function_exists($fullfunction)) {
7598 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7599 $pluginfunction = $fullfunction;
7601 } else if ($plugintype === 'mod') {
7602 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7603 $shortfunction = $plugin . '_' . $function;
7604 if (function_exists($shortfunction)) {
7605 $pluginfunction = $shortfunction;
7609 if ($pluginfunction) {
7610 if (empty($pluginfunctions[$plugintype])) {
7611 $pluginfunctions[$plugintype] = array();
7613 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7618 $cache->set($key, $pluginfunctions);
7620 return $pluginfunctions;
7625 * Lists plugin-like directories within specified directory
7627 * This function was originally used for standard Moodle plugins, please use
7628 * new core_component::get_plugin_list() now.
7630 * This function is used for general directory listing and backwards compatility.
7632 * @param string $directory relative directory from root
7633 * @param string $exclude dir name to exclude from the list (defaults to none)
7634 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7635 * @return array Sorted array of directory names found under the requested parameters
7637 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7638 global $CFG;
7640 $plugins = array();
7642 if (empty($basedir)) {
7643 $basedir = $CFG->dirroot .'/'. $directory;
7645 } else {
7646 $basedir = $basedir .'/'. $directory;
7649 if ($CFG->debugdeveloper and empty($exclude)) {
7650 // Make sure devs do not use this to list normal plugins,
7651 // this is intended for general directories that are not plugins!
7653 $subtypes = core_component::get_plugin_types();
7654 if (in_array($basedir, $subtypes)) {
7655 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7657 unset($subtypes);
7660 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7661 if (!$dirhandle = opendir($basedir)) {
7662 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7663 return array();
7665 while (false !== ($dir = readdir($dirhandle))) {
7666 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7667 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7668 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7669 continue;
7671 if (filetype($basedir .'/'. $dir) != 'dir') {
7672 continue;
7674 $plugins[] = $dir;
7676 closedir($dirhandle);
7678 if ($plugins) {
7679 asort($plugins);
7681 return $plugins;
7685 * Invoke plugin's callback functions
7687 * @param string $type plugin type e.g. 'mod'
7688 * @param string $name plugin name
7689 * @param string $feature feature name
7690 * @param string $action feature's action
7691 * @param array $params parameters of callback function, should be an array
7692 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7693 * @return mixed
7695 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7697 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7698 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7702 * Invoke component's callback functions
7704 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7705 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7706 * @param array $params parameters of callback function
7707 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7708 * @return mixed
7710 function component_callback($component, $function, array $params = array(), $default = null) {
7712 $functionname = component_callback_exists($component, $function);
7714 if ($functionname) {
7715 // Function exists, so just return function result.
7716 $ret = call_user_func_array($functionname, $params);
7717 if (is_null($ret)) {
7718 return $default;
7719 } else {
7720 return $ret;
7723 return $default;
7727 * Determine if a component callback exists and return the function name to call. Note that this
7728 * function will include the required library files so that the functioname returned can be
7729 * called directly.
7731 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7732 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7733 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7734 * @throws coding_exception if invalid component specfied
7736 function component_callback_exists($component, $function) {
7737 global $CFG; // This is needed for the inclusions.
7739 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7740 if (empty($cleancomponent)) {
7741 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7743 $component = $cleancomponent;
7745 list($type, $name) = core_component::normalize_component($component);
7746 $component = $type . '_' . $name;
7748 $oldfunction = $name.'_'.$function;
7749 $function = $component.'_'.$function;
7751 $dir = core_component::get_component_directory($component);
7752 if (empty($dir)) {
7753 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7756 // Load library and look for function.
7757 if (file_exists($dir.'/lib.php')) {
7758 require_once($dir.'/lib.php');
7761 if (!function_exists($function) and function_exists($oldfunction)) {
7762 if ($type !== 'mod' and $type !== 'core') {
7763 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7765 $function = $oldfunction;
7768 if (function_exists($function)) {
7769 return $function;
7771 return false;
7775 * Call the specified callback method on the provided class.
7777 * If the callback returns null, then the default value is returned instead.
7778 * If the class does not exist, then the default value is returned.
7780 * @param string $classname The name of the class to call upon.
7781 * @param string $methodname The name of the staticically defined method on the class.
7782 * @param array $params The arguments to pass into the method.
7783 * @param mixed $default The default value.
7784 * @return mixed The return value.
7786 function component_class_callback($classname, $methodname, array $params, $default = null) {
7787 if (!class_exists($classname)) {
7788 return $default;
7791 if (!method_exists($classname, $methodname)) {
7792 return $default;
7795 $fullfunction = $classname . '::' . $methodname;
7796 $result = call_user_func_array($fullfunction, $params);
7798 if (null === $result) {
7799 return $default;
7800 } else {
7801 return $result;
7806 * Checks whether a plugin supports a specified feature.
7808 * @param string $type Plugin type e.g. 'mod'
7809 * @param string $name Plugin name e.g. 'forum'
7810 * @param string $feature Feature code (FEATURE_xx constant)
7811 * @param mixed $default default value if feature support unknown
7812 * @return mixed Feature result (false if not supported, null if feature is unknown,
7813 * otherwise usually true but may have other feature-specific value such as array)
7814 * @throws coding_exception
7816 function plugin_supports($type, $name, $feature, $default = null) {
7817 global $CFG;
7819 if ($type === 'mod' and $name === 'NEWMODULE') {
7820 // Somebody forgot to rename the module template.
7821 return false;
7824 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7825 if (empty($component)) {
7826 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7829 $function = null;
7831 if ($type === 'mod') {
7832 // We need this special case because we support subplugins in modules,
7833 // otherwise it would end up in infinite loop.
7834 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7835 include_once("$CFG->dirroot/mod/$name/lib.php");
7836 $function = $component.'_supports';
7837 if (!function_exists($function)) {
7838 // Legacy non-frankenstyle function name.
7839 $function = $name.'_supports';
7843 } else {
7844 if (!$path = core_component::get_plugin_directory($type, $name)) {
7845 // Non existent plugin type.
7846 return false;
7848 if (file_exists("$path/lib.php")) {
7849 include_once("$path/lib.php");
7850 $function = $component.'_supports';
7854 if ($function and function_exists($function)) {
7855 $supports = $function($feature);
7856 if (is_null($supports)) {
7857 // Plugin does not know - use default.
7858 return $default;
7859 } else {
7860 return $supports;
7864 // Plugin does not care, so use default.
7865 return $default;
7869 * Returns true if the current version of PHP is greater that the specified one.
7871 * @todo Check PHP version being required here is it too low?
7873 * @param string $version The version of php being tested.
7874 * @return bool
7876 function check_php_version($version='5.2.4') {
7877 return (version_compare(phpversion(), $version) >= 0);
7881 * Determine if moodle installation requires update.
7883 * Checks version numbers of main code and all plugins to see
7884 * if there are any mismatches.
7886 * @return bool
7888 function moodle_needs_upgrading() {
7889 global $CFG;
7891 if (empty($CFG->version)) {
7892 return true;
7895 // There is no need to purge plugininfo caches here because
7896 // these caches are not used during upgrade and they are purged after
7897 // every upgrade.
7899 if (empty($CFG->allversionshash)) {
7900 return true;
7903 $hash = core_component::get_all_versions_hash();
7905 return ($hash !== $CFG->allversionshash);
7909 * Returns the major version of this site
7911 * Moodle version numbers consist of three numbers separated by a dot, for
7912 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7913 * called major version. This function extracts the major version from either
7914 * $CFG->release (default) or eventually from the $release variable defined in
7915 * the main version.php.
7917 * @param bool $fromdisk should the version if source code files be used
7918 * @return string|false the major version like '2.3', false if could not be determined
7920 function moodle_major_version($fromdisk = false) {
7921 global $CFG;
7923 if ($fromdisk) {
7924 $release = null;
7925 require($CFG->dirroot.'/version.php');
7926 if (empty($release)) {
7927 return false;
7930 } else {
7931 if (empty($CFG->release)) {
7932 return false;
7934 $release = $CFG->release;
7937 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7938 return $matches[0];
7939 } else {
7940 return false;
7944 // MISCELLANEOUS.
7947 * Sets the system locale
7949 * @category string
7950 * @param string $locale Can be used to force a locale
7952 function moodle_setlocale($locale='') {
7953 global $CFG;
7955 static $currentlocale = ''; // Last locale caching.
7957 $oldlocale = $currentlocale;
7959 // Fetch the correct locale based on ostype.
7960 if ($CFG->ostype == 'WINDOWS') {
7961 $stringtofetch = 'localewin';
7962 } else {
7963 $stringtofetch = 'locale';
7966 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7967 if (!empty($locale)) {
7968 $currentlocale = $locale;
7969 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7970 $currentlocale = $CFG->locale;
7971 } else {
7972 $currentlocale = get_string($stringtofetch, 'langconfig');
7975 // Do nothing if locale already set up.
7976 if ($oldlocale == $currentlocale) {
7977 return;
7980 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7981 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7982 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7984 // Get current values.
7985 $monetary= setlocale (LC_MONETARY, 0);
7986 $numeric = setlocale (LC_NUMERIC, 0);
7987 $ctype = setlocale (LC_CTYPE, 0);
7988 if ($CFG->ostype != 'WINDOWS') {
7989 $messages= setlocale (LC_MESSAGES, 0);
7991 // Set locale to all.
7992 $result = setlocale (LC_ALL, $currentlocale);
7993 // If setting of locale fails try the other utf8 or utf-8 variant,
7994 // some operating systems support both (Debian), others just one (OSX).
7995 if ($result === false) {
7996 if (stripos($currentlocale, '.UTF-8') !== false) {
7997 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7998 setlocale (LC_ALL, $newlocale);
7999 } else if (stripos($currentlocale, '.UTF8') !== false) {
8000 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8001 setlocale (LC_ALL, $newlocale);
8004 // Set old values.
8005 setlocale (LC_MONETARY, $monetary);
8006 setlocale (LC_NUMERIC, $numeric);
8007 if ($CFG->ostype != 'WINDOWS') {
8008 setlocale (LC_MESSAGES, $messages);
8010 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8011 // To workaround a well-known PHP problem with Turkish letter Ii.
8012 setlocale (LC_CTYPE, $ctype);
8017 * Count words in a string.
8019 * Words are defined as things between whitespace.
8021 * @category string
8022 * @param string $string The text to be searched for words.
8023 * @return int The count of words in the specified string
8025 function count_words($string) {
8026 $string = strip_tags($string);
8027 // Decode HTML entities.
8028 $string = html_entity_decode($string);
8029 // Replace underscores (which are classed as word characters) with spaces.
8030 $string = preg_replace('/_/u', ' ', $string);
8031 // Remove any characters that shouldn't be treated as word boundaries.
8032 $string = preg_replace('/[\'"’-]/u', '', $string);
8033 // Remove dots and commas from within numbers only.
8034 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
8036 return count(preg_split('/\w\b/u', $string)) - 1;
8040 * Count letters in a string.
8042 * Letters are defined as chars not in tags and different from whitespace.
8044 * @category string
8045 * @param string $string The text to be searched for letters.
8046 * @return int The count of letters in the specified text.
8048 function count_letters($string) {
8049 $string = strip_tags($string); // Tags are out now.
8050 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8052 return core_text::strlen($string);
8056 * Generate and return a random string of the specified length.
8058 * @param int $length The length of the string to be created.
8059 * @return string
8061 function random_string($length=15) {
8062 $randombytes = random_bytes_emulate($length);
8063 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8064 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8065 $pool .= '0123456789';
8066 $poollen = strlen($pool);
8067 $string = '';
8068 for ($i = 0; $i < $length; $i++) {
8069 $rand = ord($randombytes[$i]);
8070 $string .= substr($pool, ($rand%($poollen)), 1);
8072 return $string;
8076 * Generate a complex random string (useful for md5 salts)
8078 * This function is based on the above {@link random_string()} however it uses a
8079 * larger pool of characters and generates a string between 24 and 32 characters
8081 * @param int $length Optional if set generates a string to exactly this length
8082 * @return string
8084 function complex_random_string($length=null) {
8085 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8086 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8087 $poollen = strlen($pool);
8088 if ($length===null) {
8089 $length = floor(rand(24, 32));
8091 $randombytes = random_bytes_emulate($length);
8092 $string = '';
8093 for ($i = 0; $i < $length; $i++) {
8094 $rand = ord($randombytes[$i]);
8095 $string .= $pool[($rand%$poollen)];
8097 return $string;
8101 * Try to generates cryptographically secure pseudo-random bytes.
8103 * Note this is achieved by fallbacking between:
8104 * - PHP 7 random_bytes().
8105 * - OpenSSL openssl_random_pseudo_bytes().
8106 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8108 * @param int $length requested length in bytes
8109 * @return string binary data
8111 function random_bytes_emulate($length) {
8112 global $CFG;
8113 if ($length <= 0) {
8114 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8115 return '';
8117 if (function_exists('random_bytes')) {
8118 // Use PHP 7 goodness.
8119 $hash = @random_bytes($length);
8120 if ($hash !== false) {
8121 return $hash;
8124 if (function_exists('openssl_random_pseudo_bytes')) {
8125 // If you have the openssl extension enabled.
8126 $hash = openssl_random_pseudo_bytes($length);
8127 if ($hash !== false) {
8128 return $hash;
8132 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8133 $staticdata = serialize($CFG) . serialize($_SERVER);
8134 $hash = '';
8135 do {
8136 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8137 } while (strlen($hash) < $length);
8139 return substr($hash, 0, $length);
8143 * Given some text (which may contain HTML) and an ideal length,
8144 * this function truncates the text neatly on a word boundary if possible
8146 * @category string
8147 * @param string $text text to be shortened
8148 * @param int $ideal ideal string length
8149 * @param boolean $exact if false, $text will not be cut mid-word
8150 * @param string $ending The string to append if the passed string is truncated
8151 * @return string $truncate shortened string
8153 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8154 // If the plain text is shorter than the maximum length, return the whole text.
8155 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8156 return $text;
8159 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8160 // and only tag in its 'line'.
8161 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8163 $totallength = core_text::strlen($ending);
8164 $truncate = '';
8166 // This array stores information about open and close tags and their position
8167 // in the truncated string. Each item in the array is an object with fields
8168 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8169 // (byte position in truncated text).
8170 $tagdetails = array();
8172 foreach ($lines as $linematchings) {
8173 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8174 if (!empty($linematchings[1])) {
8175 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8176 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8177 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8178 // Record closing tag.
8179 $tagdetails[] = (object) array(
8180 'open' => false,
8181 'tag' => core_text::strtolower($tagmatchings[1]),
8182 'pos' => core_text::strlen($truncate),
8185 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8186 // Record opening tag.
8187 $tagdetails[] = (object) array(
8188 'open' => true,
8189 'tag' => core_text::strtolower($tagmatchings[1]),
8190 'pos' => core_text::strlen($truncate),
8192 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8193 $tagdetails[] = (object) array(
8194 'open' => true,
8195 'tag' => core_text::strtolower('if'),
8196 'pos' => core_text::strlen($truncate),
8198 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8199 $tagdetails[] = (object) array(
8200 'open' => false,
8201 'tag' => core_text::strtolower('if'),
8202 'pos' => core_text::strlen($truncate),
8206 // Add html-tag to $truncate'd text.
8207 $truncate .= $linematchings[1];
8210 // Calculate the length of the plain text part of the line; handle entities as one character.
8211 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8212 if ($totallength + $contentlength > $ideal) {
8213 // The number of characters which are left.
8214 $left = $ideal - $totallength;
8215 $entitieslength = 0;
8216 // Search for html entities.
8217 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)) {
8218 // Calculate the real length of all entities in the legal range.
8219 foreach ($entities[0] as $entity) {
8220 if ($entity[1]+1-$entitieslength <= $left) {
8221 $left--;
8222 $entitieslength += core_text::strlen($entity[0]);
8223 } else {
8224 // No more characters left.
8225 break;
8229 $breakpos = $left + $entitieslength;
8231 // If the words shouldn't be cut in the middle...
8232 if (!$exact) {
8233 // Search the last occurence of a space.
8234 for (; $breakpos > 0; $breakpos--) {
8235 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8236 if ($char === '.' or $char === ' ') {
8237 $breakpos += 1;
8238 break;
8239 } else if (strlen($char) > 2) {
8240 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8241 $breakpos += 1;
8242 break;
8247 if ($breakpos == 0) {
8248 // This deals with the test_shorten_text_no_spaces case.
8249 $breakpos = $left + $entitieslength;
8250 } else if ($breakpos > $left + $entitieslength) {
8251 // This deals with the previous for loop breaking on the first char.
8252 $breakpos = $left + $entitieslength;
8255 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8256 // Maximum length is reached, so get off the loop.
8257 break;
8258 } else {
8259 $truncate .= $linematchings[2];
8260 $totallength += $contentlength;
8263 // If the maximum length is reached, get off the loop.
8264 if ($totallength >= $ideal) {
8265 break;
8269 // Add the defined ending to the text.
8270 $truncate .= $ending;
8272 // Now calculate the list of open html tags based on the truncate position.
8273 $opentags = array();
8274 foreach ($tagdetails as $taginfo) {
8275 if ($taginfo->open) {
8276 // Add tag to the beginning of $opentags list.
8277 array_unshift($opentags, $taginfo->tag);
8278 } else {
8279 // Can have multiple exact same open tags, close the last one.
8280 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8281 if ($pos !== false) {
8282 unset($opentags[$pos]);
8287 // Close all unclosed html-tags.
8288 foreach ($opentags as $tag) {
8289 if ($tag === 'if') {
8290 $truncate .= '<!--<![endif]-->';
8291 } else {
8292 $truncate .= '</' . $tag . '>';
8296 return $truncate;
8300 * Shortens a given filename by removing characters positioned after the ideal string length.
8301 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8302 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8304 * @param string $filename file name
8305 * @param int $length ideal string length
8306 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8307 * @return string $shortened shortened file name
8309 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8310 $shortened = $filename;
8311 // Extract a part of the filename if it's char size exceeds the ideal string length.
8312 if (core_text::strlen($filename) > $length) {
8313 // Exclude extension if present in filename.
8314 $mimetypes = get_mimetypes_array();
8315 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8316 if ($extension && !empty($mimetypes[$extension])) {
8317 $basename = pathinfo($filename, PATHINFO_FILENAME);
8318 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8319 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8320 $shortened .= '.' . $extension;
8321 } else {
8322 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8323 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8326 return $shortened;
8330 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8332 * @param array $path The paths to reduce the length.
8333 * @param int $length Ideal string length
8334 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8335 * @return array $result Shortened paths in array.
8337 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8338 $result = null;
8340 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8341 $carry[] = shorten_filename($singlepath, $length, $includehash);
8342 return $carry;
8343 }, []);
8345 return $result;
8349 * Given dates in seconds, how many weeks is the date from startdate
8350 * The first week is 1, the second 2 etc ...
8352 * @param int $startdate Timestamp for the start date
8353 * @param int $thedate Timestamp for the end date
8354 * @return string
8356 function getweek ($startdate, $thedate) {
8357 if ($thedate < $startdate) {
8358 return 0;
8361 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8365 * Returns a randomly generated password of length $maxlen. inspired by
8367 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8368 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8370 * @param int $maxlen The maximum size of the password being generated.
8371 * @return string
8373 function generate_password($maxlen=10) {
8374 global $CFG;
8376 if (empty($CFG->passwordpolicy)) {
8377 $fillers = PASSWORD_DIGITS;
8378 $wordlist = file($CFG->wordlist);
8379 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8380 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8381 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8382 $password = $word1 . $filler1 . $word2;
8383 } else {
8384 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8385 $digits = $CFG->minpassworddigits;
8386 $lower = $CFG->minpasswordlower;
8387 $upper = $CFG->minpasswordupper;
8388 $nonalphanum = $CFG->minpasswordnonalphanum;
8389 $total = $lower + $upper + $digits + $nonalphanum;
8390 // Var minlength should be the greater one of the two ( $minlen and $total ).
8391 $minlen = $minlen < $total ? $total : $minlen;
8392 // Var maxlen can never be smaller than minlen.
8393 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8394 $additional = $maxlen - $total;
8396 // Make sure we have enough characters to fulfill
8397 // complexity requirements.
8398 $passworddigits = PASSWORD_DIGITS;
8399 while ($digits > strlen($passworddigits)) {
8400 $passworddigits .= PASSWORD_DIGITS;
8402 $passwordlower = PASSWORD_LOWER;
8403 while ($lower > strlen($passwordlower)) {
8404 $passwordlower .= PASSWORD_LOWER;
8406 $passwordupper = PASSWORD_UPPER;
8407 while ($upper > strlen($passwordupper)) {
8408 $passwordupper .= PASSWORD_UPPER;
8410 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8411 while ($nonalphanum > strlen($passwordnonalphanum)) {
8412 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8415 // Now mix and shuffle it all.
8416 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8417 substr(str_shuffle ($passwordupper), 0, $upper) .
8418 substr(str_shuffle ($passworddigits), 0, $digits) .
8419 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8420 substr(str_shuffle ($passwordlower .
8421 $passwordupper .
8422 $passworddigits .
8423 $passwordnonalphanum), 0 , $additional));
8426 return substr ($password, 0, $maxlen);
8430 * Given a float, prints it nicely.
8431 * Localized floats must not be used in calculations!
8433 * The stripzeros feature is intended for making numbers look nicer in small
8434 * areas where it is not necessary to indicate the degree of accuracy by showing
8435 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8436 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8438 * @param float $float The float to print
8439 * @param int $decimalpoints The number of decimal places to print.
8440 * @param bool $localized use localized decimal separator
8441 * @param bool $stripzeros If true, removes final zeros after decimal point
8442 * @return string locale float
8444 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8445 if (is_null($float)) {
8446 return '';
8448 if ($localized) {
8449 $separator = get_string('decsep', 'langconfig');
8450 } else {
8451 $separator = '.';
8453 $result = number_format($float, $decimalpoints, $separator, '');
8454 if ($stripzeros) {
8455 // Remove zeros and final dot if not needed.
8456 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8458 return $result;
8462 * Converts locale specific floating point/comma number back to standard PHP float value
8463 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8465 * @param string $localefloat locale aware float representation
8466 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8467 * @return mixed float|bool - false or the parsed float.
8469 function unformat_float($localefloat, $strict = false) {
8470 $localefloat = trim($localefloat);
8472 if ($localefloat == '') {
8473 return null;
8476 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8477 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8479 if ($strict && !is_numeric($localefloat)) {
8480 return false;
8483 return (float)$localefloat;
8487 * Given a simple array, this shuffles it up just like shuffle()
8488 * Unlike PHP's shuffle() this function works on any machine.
8490 * @param array $array The array to be rearranged
8491 * @return array
8493 function swapshuffle($array) {
8495 $last = count($array) - 1;
8496 for ($i = 0; $i <= $last; $i++) {
8497 $from = rand(0, $last);
8498 $curr = $array[$i];
8499 $array[$i] = $array[$from];
8500 $array[$from] = $curr;
8502 return $array;
8506 * Like {@link swapshuffle()}, but works on associative arrays
8508 * @param array $array The associative array to be rearranged
8509 * @return array
8511 function swapshuffle_assoc($array) {
8513 $newarray = array();
8514 $newkeys = swapshuffle(array_keys($array));
8516 foreach ($newkeys as $newkey) {
8517 $newarray[$newkey] = $array[$newkey];
8519 return $newarray;
8523 * Given an arbitrary array, and a number of draws,
8524 * this function returns an array with that amount
8525 * of items. The indexes are retained.
8527 * @todo Finish documenting this function
8529 * @param array $array
8530 * @param int $draws
8531 * @return array
8533 function draw_rand_array($array, $draws) {
8535 $return = array();
8537 $last = count($array);
8539 if ($draws > $last) {
8540 $draws = $last;
8543 while ($draws > 0) {
8544 $last--;
8546 $keys = array_keys($array);
8547 $rand = rand(0, $last);
8549 $return[$keys[$rand]] = $array[$keys[$rand]];
8550 unset($array[$keys[$rand]]);
8552 $draws--;
8555 return $return;
8559 * Calculate the difference between two microtimes
8561 * @param string $a The first Microtime
8562 * @param string $b The second Microtime
8563 * @return string
8565 function microtime_diff($a, $b) {
8566 list($adec, $asec) = explode(' ', $a);
8567 list($bdec, $bsec) = explode(' ', $b);
8568 return $bsec - $asec + $bdec - $adec;
8572 * Given a list (eg a,b,c,d,e) this function returns
8573 * an array of 1->a, 2->b, 3->c etc
8575 * @param string $list The string to explode into array bits
8576 * @param string $separator The separator used within the list string
8577 * @return array The now assembled array
8579 function make_menu_from_list($list, $separator=',') {
8581 $array = array_reverse(explode($separator, $list), true);
8582 foreach ($array as $key => $item) {
8583 $outarray[$key+1] = trim($item);
8585 return $outarray;
8589 * Creates an array that represents all the current grades that
8590 * can be chosen using the given grading type.
8592 * Negative numbers
8593 * are scales, zero is no grade, and positive numbers are maximum
8594 * grades.
8596 * @todo Finish documenting this function or better deprecated this completely!
8598 * @param int $gradingtype
8599 * @return array
8601 function make_grades_menu($gradingtype) {
8602 global $DB;
8604 $grades = array();
8605 if ($gradingtype < 0) {
8606 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8607 return make_menu_from_list($scale->scale);
8609 } else if ($gradingtype > 0) {
8610 for ($i=$gradingtype; $i>=0; $i--) {
8611 $grades[$i] = $i .' / '. $gradingtype;
8613 return $grades;
8615 return $grades;
8619 * make_unique_id_code
8621 * @todo Finish documenting this function
8623 * @uses $_SERVER
8624 * @param string $extra Extra string to append to the end of the code
8625 * @return string
8627 function make_unique_id_code($extra = '') {
8629 $hostname = 'unknownhost';
8630 if (!empty($_SERVER['HTTP_HOST'])) {
8631 $hostname = $_SERVER['HTTP_HOST'];
8632 } else if (!empty($_ENV['HTTP_HOST'])) {
8633 $hostname = $_ENV['HTTP_HOST'];
8634 } else if (!empty($_SERVER['SERVER_NAME'])) {
8635 $hostname = $_SERVER['SERVER_NAME'];
8636 } else if (!empty($_ENV['SERVER_NAME'])) {
8637 $hostname = $_ENV['SERVER_NAME'];
8640 $date = gmdate("ymdHis");
8642 $random = random_string(6);
8644 if ($extra) {
8645 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8646 } else {
8647 return $hostname .'+'. $date .'+'. $random;
8653 * Function to check the passed address is within the passed subnet
8655 * The parameter is a comma separated string of subnet definitions.
8656 * Subnet strings can be in one of three formats:
8657 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8658 * 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)
8659 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8660 * Code for type 1 modified from user posted comments by mediator at
8661 * {@link http://au.php.net/manual/en/function.ip2long.php}
8663 * @param string $addr The address you are checking
8664 * @param string $subnetstr The string of subnet addresses
8665 * @return bool
8667 function address_in_subnet($addr, $subnetstr) {
8669 if ($addr == '0.0.0.0') {
8670 return false;
8672 $subnets = explode(',', $subnetstr);
8673 $found = false;
8674 $addr = trim($addr);
8675 $addr = cleanremoteaddr($addr, false); // Normalise.
8676 if ($addr === null) {
8677 return false;
8679 $addrparts = explode(':', $addr);
8681 $ipv6 = strpos($addr, ':');
8683 foreach ($subnets as $subnet) {
8684 $subnet = trim($subnet);
8685 if ($subnet === '') {
8686 continue;
8689 if (strpos($subnet, '/') !== false) {
8690 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8691 list($ip, $mask) = explode('/', $subnet);
8692 $mask = trim($mask);
8693 if (!is_number($mask)) {
8694 continue; // Incorect mask number, eh?
8696 $ip = cleanremoteaddr($ip, false); // Normalise.
8697 if ($ip === null) {
8698 continue;
8700 if (strpos($ip, ':') !== false) {
8701 // IPv6.
8702 if (!$ipv6) {
8703 continue;
8705 if ($mask > 128 or $mask < 0) {
8706 continue; // Nonsense.
8708 if ($mask == 0) {
8709 return true; // Any address.
8711 if ($mask == 128) {
8712 if ($ip === $addr) {
8713 return true;
8715 continue;
8717 $ipparts = explode(':', $ip);
8718 $modulo = $mask % 16;
8719 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8720 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8721 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8722 if ($modulo == 0) {
8723 return true;
8725 $pos = ($mask-$modulo)/16;
8726 $ipnet = hexdec($ipparts[$pos]);
8727 $addrnet = hexdec($addrparts[$pos]);
8728 $mask = 0xffff << (16 - $modulo);
8729 if (($addrnet & $mask) == ($ipnet & $mask)) {
8730 return true;
8734 } else {
8735 // IPv4.
8736 if ($ipv6) {
8737 continue;
8739 if ($mask > 32 or $mask < 0) {
8740 continue; // Nonsense.
8742 if ($mask == 0) {
8743 return true;
8745 if ($mask == 32) {
8746 if ($ip === $addr) {
8747 return true;
8749 continue;
8751 $mask = 0xffffffff << (32 - $mask);
8752 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8753 return true;
8757 } else if (strpos($subnet, '-') !== false) {
8758 // 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.
8759 $parts = explode('-', $subnet);
8760 if (count($parts) != 2) {
8761 continue;
8764 if (strpos($subnet, ':') !== false) {
8765 // IPv6.
8766 if (!$ipv6) {
8767 continue;
8769 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8770 if ($ipstart === null) {
8771 continue;
8773 $ipparts = explode(':', $ipstart);
8774 $start = hexdec(array_pop($ipparts));
8775 $ipparts[] = trim($parts[1]);
8776 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8777 if ($ipend === null) {
8778 continue;
8780 $ipparts[7] = '';
8781 $ipnet = implode(':', $ipparts);
8782 if (strpos($addr, $ipnet) !== 0) {
8783 continue;
8785 $ipparts = explode(':', $ipend);
8786 $end = hexdec($ipparts[7]);
8788 $addrend = hexdec($addrparts[7]);
8790 if (($addrend >= $start) and ($addrend <= $end)) {
8791 return true;
8794 } else {
8795 // IPv4.
8796 if ($ipv6) {
8797 continue;
8799 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8800 if ($ipstart === null) {
8801 continue;
8803 $ipparts = explode('.', $ipstart);
8804 $ipparts[3] = trim($parts[1]);
8805 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8806 if ($ipend === null) {
8807 continue;
8810 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8811 return true;
8815 } else {
8816 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8817 if (strpos($subnet, ':') !== false) {
8818 // IPv6.
8819 if (!$ipv6) {
8820 continue;
8822 $parts = explode(':', $subnet);
8823 $count = count($parts);
8824 if ($parts[$count-1] === '') {
8825 unset($parts[$count-1]); // Trim trailing :'s.
8826 $count--;
8827 $subnet = implode('.', $parts);
8829 $isip = cleanremoteaddr($subnet, false); // Normalise.
8830 if ($isip !== null) {
8831 if ($isip === $addr) {
8832 return true;
8834 continue;
8835 } else if ($count > 8) {
8836 continue;
8838 $zeros = array_fill(0, 8-$count, '0');
8839 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8840 if (address_in_subnet($addr, $subnet)) {
8841 return true;
8844 } else {
8845 // IPv4.
8846 if ($ipv6) {
8847 continue;
8849 $parts = explode('.', $subnet);
8850 $count = count($parts);
8851 if ($parts[$count-1] === '') {
8852 unset($parts[$count-1]); // Trim trailing .
8853 $count--;
8854 $subnet = implode('.', $parts);
8856 if ($count == 4) {
8857 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8858 if ($subnet === $addr) {
8859 return true;
8861 continue;
8862 } else if ($count > 4) {
8863 continue;
8865 $zeros = array_fill(0, 4-$count, '0');
8866 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8867 if (address_in_subnet($addr, $subnet)) {
8868 return true;
8874 return false;
8878 * For outputting debugging info
8880 * @param string $string The string to write
8881 * @param string $eol The end of line char(s) to use
8882 * @param string $sleep Period to make the application sleep
8883 * This ensures any messages have time to display before redirect
8885 function mtrace($string, $eol="\n", $sleep=0) {
8886 global $CFG;
8888 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
8889 $fn = $CFG->mtrace_wrapper;
8890 $fn($string, $eol);
8891 return;
8892 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
8893 fwrite(STDOUT, $string.$eol);
8894 } else {
8895 echo $string . $eol;
8898 flush();
8900 // Delay to keep message on user's screen in case of subsequent redirect.
8901 if ($sleep) {
8902 sleep($sleep);
8907 * Replace 1 or more slashes or backslashes to 1 slash
8909 * @param string $path The path to strip
8910 * @return string the path with double slashes removed
8912 function cleardoubleslashes ($path) {
8913 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8917 * Is the current ip in a given list?
8919 * @param string $list
8920 * @return bool
8922 function remoteip_in_list($list) {
8923 $inlist = false;
8924 $clientip = getremoteaddr(null);
8926 if (!$clientip) {
8927 // Ensure access on cli.
8928 return true;
8931 $list = explode("\n", $list);
8932 foreach ($list as $line) {
8933 $tokens = explode('#', $line);
8934 $subnet = trim($tokens[0]);
8935 if (address_in_subnet($clientip, $subnet)) {
8936 $inlist = true;
8937 break;
8940 return $inlist;
8944 * Returns most reliable client address
8946 * @param string $default If an address can't be determined, then return this
8947 * @return string The remote IP address
8949 function getremoteaddr($default='0.0.0.0') {
8950 global $CFG;
8952 if (empty($CFG->getremoteaddrconf)) {
8953 // This will happen, for example, before just after the upgrade, as the
8954 // user is redirected to the admin screen.
8955 $variablestoskip = 0;
8956 } else {
8957 $variablestoskip = $CFG->getremoteaddrconf;
8959 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8960 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8961 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8962 return $address ? $address : $default;
8965 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8966 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8967 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8968 $address = $forwardedaddresses[0];
8970 if (substr_count($address, ":") > 1) {
8971 // Remove port and brackets from IPv6.
8972 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8973 $address = $matches[1];
8975 } else {
8976 // Remove port from IPv4.
8977 if (substr_count($address, ":") == 1) {
8978 $parts = explode(":", $address);
8979 $address = $parts[0];
8983 $address = cleanremoteaddr($address);
8984 return $address ? $address : $default;
8987 if (!empty($_SERVER['REMOTE_ADDR'])) {
8988 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8989 return $address ? $address : $default;
8990 } else {
8991 return $default;
8996 * Cleans an ip address. Internal addresses are now allowed.
8997 * (Originally local addresses were not allowed.)
8999 * @param string $addr IPv4 or IPv6 address
9000 * @param bool $compress use IPv6 address compression
9001 * @return string normalised ip address string, null if error
9003 function cleanremoteaddr($addr, $compress=false) {
9004 $addr = trim($addr);
9006 if (strpos($addr, ':') !== false) {
9007 // Can be only IPv6.
9008 $parts = explode(':', $addr);
9009 $count = count($parts);
9011 if (strpos($parts[$count-1], '.') !== false) {
9012 // Legacy ipv4 notation.
9013 $last = array_pop($parts);
9014 $ipv4 = cleanremoteaddr($last, true);
9015 if ($ipv4 === null) {
9016 return null;
9018 $bits = explode('.', $ipv4);
9019 $parts[] = dechex($bits[0]).dechex($bits[1]);
9020 $parts[] = dechex($bits[2]).dechex($bits[3]);
9021 $count = count($parts);
9022 $addr = implode(':', $parts);
9025 if ($count < 3 or $count > 8) {
9026 return null; // Severly malformed.
9029 if ($count != 8) {
9030 if (strpos($addr, '::') === false) {
9031 return null; // Malformed.
9033 // Uncompress.
9034 $insertat = array_search('', $parts, true);
9035 $missing = array_fill(0, 1 + 8 - $count, '0');
9036 array_splice($parts, $insertat, 1, $missing);
9037 foreach ($parts as $key => $part) {
9038 if ($part === '') {
9039 $parts[$key] = '0';
9044 $adr = implode(':', $parts);
9045 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9046 return null; // Incorrect format - sorry.
9049 // Normalise 0s and case.
9050 $parts = array_map('hexdec', $parts);
9051 $parts = array_map('dechex', $parts);
9053 $result = implode(':', $parts);
9055 if (!$compress) {
9056 return $result;
9059 if ($result === '0:0:0:0:0:0:0:0') {
9060 return '::'; // All addresses.
9063 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9064 if ($compressed !== $result) {
9065 return $compressed;
9068 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9069 if ($compressed !== $result) {
9070 return $compressed;
9073 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9074 if ($compressed !== $result) {
9075 return $compressed;
9078 return $result;
9081 // First get all things that look like IPv4 addresses.
9082 $parts = array();
9083 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9084 return null;
9086 unset($parts[0]);
9088 foreach ($parts as $key => $match) {
9089 if ($match > 255) {
9090 return null;
9092 $parts[$key] = (int)$match; // Normalise 0s.
9095 return implode('.', $parts);
9100 * Is IP address a public address?
9102 * @param string $ip The ip to check
9103 * @return bool true if the ip is public
9105 function ip_is_public($ip) {
9106 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9110 * This function will make a complete copy of anything it's given,
9111 * regardless of whether it's an object or not.
9113 * @param mixed $thing Something you want cloned
9114 * @return mixed What ever it is you passed it
9116 function fullclone($thing) {
9117 return unserialize(serialize($thing));
9121 * Used to make sure that $min <= $value <= $max
9123 * Make sure that value is between min, and max
9125 * @param int $min The minimum value
9126 * @param int $value The value to check
9127 * @param int $max The maximum value
9128 * @return int
9130 function bounded_number($min, $value, $max) {
9131 if ($value < $min) {
9132 return $min;
9134 if ($value > $max) {
9135 return $max;
9137 return $value;
9141 * Check if there is a nested array within the passed array
9143 * @param array $array
9144 * @return bool true if there is a nested array false otherwise
9146 function array_is_nested($array) {
9147 foreach ($array as $value) {
9148 if (is_array($value)) {
9149 return true;
9152 return false;
9156 * get_performance_info() pairs up with init_performance_info()
9157 * loaded in setup.php. Returns an array with 'html' and 'txt'
9158 * values ready for use, and each of the individual stats provided
9159 * separately as well.
9161 * @return array
9163 function get_performance_info() {
9164 global $CFG, $PERF, $DB, $PAGE;
9166 $info = array();
9167 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9169 $info['html'] = '';
9170 if (!empty($CFG->themedesignermode)) {
9171 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9172 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9174 $info['html'] .= '<ul class="list-unstyled m-l-1 row">'; // Holds userfriendly HTML representation.
9176 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9178 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9179 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9181 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9182 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9184 if (function_exists('memory_get_usage')) {
9185 $info['memory_total'] = memory_get_usage();
9186 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9187 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9188 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9189 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9192 if (function_exists('memory_get_peak_usage')) {
9193 $info['memory_peak'] = memory_get_peak_usage();
9194 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9195 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9198 $info['html'] .= '</ul><ul class="list-unstyled m-l-1 row">';
9199 $inc = get_included_files();
9200 $info['includecount'] = count($inc);
9201 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9202 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9204 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9205 // We can not track more performance before installation or before PAGE init, sorry.
9206 return $info;
9209 $filtermanager = filter_manager::instance();
9210 if (method_exists($filtermanager, 'get_performance_summary')) {
9211 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9212 $info = array_merge($filterinfo, $info);
9213 foreach ($filterinfo as $key => $value) {
9214 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9215 $info['txt'] .= "$key: $value ";
9219 $stringmanager = get_string_manager();
9220 if (method_exists($stringmanager, 'get_performance_summary')) {
9221 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9222 $info = array_merge($filterinfo, $info);
9223 foreach ($filterinfo as $key => $value) {
9224 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9225 $info['txt'] .= "$key: $value ";
9229 if (!empty($PERF->logwrites)) {
9230 $info['logwrites'] = $PERF->logwrites;
9231 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9232 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9235 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9236 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9237 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9239 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9240 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9241 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9243 if (function_exists('posix_times')) {
9244 $ptimes = posix_times();
9245 if (is_array($ptimes)) {
9246 foreach ($ptimes as $key => $val) {
9247 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9249 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9250 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9251 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9255 // Grab the load average for the last minute.
9256 // /proc will only work under some linux configurations
9257 // while uptime is there under MacOSX/Darwin and other unices.
9258 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9259 list($serverload) = explode(' ', $loadavg[0]);
9260 unset($loadavg);
9261 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9262 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9263 $serverload = $matches[1];
9264 } else {
9265 trigger_error('Could not parse uptime output!');
9268 if (!empty($serverload)) {
9269 $info['serverload'] = $serverload;
9270 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9271 $info['txt'] .= "serverload: {$info['serverload']} ";
9274 // Display size of session if session started.
9275 if ($si = \core\session\manager::get_performance_info()) {
9276 $info['sessionsize'] = $si['size'];
9277 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9278 $info['txt'] .= $si['txt'];
9281 $info['html'] .= '</ul>';
9282 if ($stats = cache_helper::get_stats()) {
9283 $html = '<ul class="cachesused list-unstyled m-l-1 row">';
9284 $html .= '<li class="cache-stats-heading font-weight-bold">Caches used (hits/misses/sets)</li>';
9285 $html .= '</ul><ul class="cachesused list-unstyled m-l-1">';
9286 $text = 'Caches used (hits/misses/sets): ';
9287 $hits = 0;
9288 $misses = 0;
9289 $sets = 0;
9290 foreach ($stats as $definition => $details) {
9291 switch ($details['mode']) {
9292 case cache_store::MODE_APPLICATION:
9293 $modeclass = 'application';
9294 $mode = ' <span title="application cache">[a]</span>';
9295 break;
9296 case cache_store::MODE_SESSION:
9297 $modeclass = 'session';
9298 $mode = ' <span title="session cache">[s]</span>';
9299 break;
9300 case cache_store::MODE_REQUEST:
9301 $modeclass = 'request';
9302 $mode = ' <span title="request cache">[r]</span>';
9303 break;
9305 $html .= '<ul class="cache-definition-stats list-unstyled m-l-1 m-b-1 cache-mode-'.$modeclass.' card d-inline-block">';
9306 $html .= '<li class="cache-definition-stats-heading p-t-1 card-header bg-dark bg-inverse font-weight-bold">' .
9307 $definition . $mode.'</li>';
9308 $text .= "$definition {";
9309 foreach ($details['stores'] as $store => $data) {
9310 $hits += $data['hits'];
9311 $misses += $data['misses'];
9312 $sets += $data['sets'];
9313 if ($data['hits'] == 0 and $data['misses'] > 0) {
9314 $cachestoreclass = 'nohits text-danger';
9315 } else if ($data['hits'] < $data['misses']) {
9316 $cachestoreclass = 'lowhits text-warning';
9317 } else {
9318 $cachestoreclass = 'hihits text-success';
9320 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9321 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">" .
9322 "$store: $data[hits] / $data[misses] / $data[sets]</li>";
9323 // This makes boxes of same sizes.
9324 if (count($details['stores']) == 1) {
9325 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">&nbsp;</li>";
9328 $html .= '</ul>';
9329 $text .= '} ';
9331 $html .= '</ul> ';
9332 $html .= "<div class='cache-total-stats row'>Total: $hits / $misses / $sets</div>";
9333 $info['cachesused'] = "$hits / $misses / $sets";
9334 $info['html'] .= $html;
9335 $info['txt'] .= $text.'. ';
9336 } else {
9337 $info['cachesused'] = '0 / 0 / 0';
9338 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9339 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9342 $info['html'] = '<div class="performanceinfo siteinfo container-fluid">'.$info['html'].'</div>';
9343 return $info;
9347 * Delete directory or only its content
9349 * @param string $dir directory path
9350 * @param bool $contentonly
9351 * @return bool success, true also if dir does not exist
9353 function remove_dir($dir, $contentonly=false) {
9354 if (!file_exists($dir)) {
9355 // Nothing to do.
9356 return true;
9358 if (!$handle = opendir($dir)) {
9359 return false;
9361 $result = true;
9362 while (false!==($item = readdir($handle))) {
9363 if ($item != '.' && $item != '..') {
9364 if (is_dir($dir.'/'.$item)) {
9365 $result = remove_dir($dir.'/'.$item) && $result;
9366 } else {
9367 $result = unlink($dir.'/'.$item) && $result;
9371 closedir($handle);
9372 if ($contentonly) {
9373 clearstatcache(); // Make sure file stat cache is properly invalidated.
9374 return $result;
9376 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9377 clearstatcache(); // Make sure file stat cache is properly invalidated.
9378 return $result;
9382 * Detect if an object or a class contains a given property
9383 * will take an actual object or the name of a class
9385 * @param mix $obj Name of class or real object to test
9386 * @param string $property name of property to find
9387 * @return bool true if property exists
9389 function object_property_exists( $obj, $property ) {
9390 if (is_string( $obj )) {
9391 $properties = get_class_vars( $obj );
9392 } else {
9393 $properties = get_object_vars( $obj );
9395 return array_key_exists( $property, $properties );
9399 * Converts an object into an associative array
9401 * This function converts an object into an associative array by iterating
9402 * over its public properties. Because this function uses the foreach
9403 * construct, Iterators are respected. It works recursively on arrays of objects.
9404 * Arrays and simple values are returned as is.
9406 * If class has magic properties, it can implement IteratorAggregate
9407 * and return all available properties in getIterator()
9409 * @param mixed $var
9410 * @return array
9412 function convert_to_array($var) {
9413 $result = array();
9415 // Loop over elements/properties.
9416 foreach ($var as $key => $value) {
9417 // Recursively convert objects.
9418 if (is_object($value) || is_array($value)) {
9419 $result[$key] = convert_to_array($value);
9420 } else {
9421 // Simple values are untouched.
9422 $result[$key] = $value;
9425 return $result;
9429 * Detect a custom script replacement in the data directory that will
9430 * replace an existing moodle script
9432 * @return string|bool full path name if a custom script exists, false if no custom script exists
9434 function custom_script_path() {
9435 global $CFG, $SCRIPT;
9437 if ($SCRIPT === null) {
9438 // Probably some weird external script.
9439 return false;
9442 $scriptpath = $CFG->customscripts . $SCRIPT;
9444 // Check the custom script exists.
9445 if (file_exists($scriptpath) and is_file($scriptpath)) {
9446 return $scriptpath;
9447 } else {
9448 return false;
9453 * Returns whether or not the user object is a remote MNET user. This function
9454 * is in moodlelib because it does not rely on loading any of the MNET code.
9456 * @param object $user A valid user object
9457 * @return bool True if the user is from a remote Moodle.
9459 function is_mnet_remote_user($user) {
9460 global $CFG;
9462 if (!isset($CFG->mnet_localhost_id)) {
9463 include_once($CFG->dirroot . '/mnet/lib.php');
9464 $env = new mnet_environment();
9465 $env->init();
9466 unset($env);
9469 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9473 * This function will search for browser prefereed languages, setting Moodle
9474 * to use the best one available if $SESSION->lang is undefined
9476 function setup_lang_from_browser() {
9477 global $CFG, $SESSION, $USER;
9479 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9480 // Lang is defined in session or user profile, nothing to do.
9481 return;
9484 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9485 return;
9488 // Extract and clean langs from headers.
9489 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9490 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9491 $rawlangs = explode(',', $rawlangs); // Convert to array.
9492 $langs = array();
9494 $order = 1.0;
9495 foreach ($rawlangs as $lang) {
9496 if (strpos($lang, ';') === false) {
9497 $langs[(string)$order] = $lang;
9498 $order = $order-0.01;
9499 } else {
9500 $parts = explode(';', $lang);
9501 $pos = strpos($parts[1], '=');
9502 $langs[substr($parts[1], $pos+1)] = $parts[0];
9505 krsort($langs, SORT_NUMERIC);
9507 // Look for such langs under standard locations.
9508 foreach ($langs as $lang) {
9509 // Clean it properly for include.
9510 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9511 if (get_string_manager()->translation_exists($lang, false)) {
9512 // Lang exists, set it in session.
9513 $SESSION->lang = $lang;
9514 // We have finished. Go out.
9515 break;
9518 return;
9522 * Check if $url matches anything in proxybypass list
9524 * Any errors just result in the proxy being used (least bad)
9526 * @param string $url url to check
9527 * @return boolean true if we should bypass the proxy
9529 function is_proxybypass( $url ) {
9530 global $CFG;
9532 // Sanity check.
9533 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9534 return false;
9537 // Get the host part out of the url.
9538 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9539 return false;
9542 // Get the possible bypass hosts into an array.
9543 $matches = explode( ',', $CFG->proxybypass );
9545 // Check for a match.
9546 // (IPs need to match the left hand side and hosts the right of the url,
9547 // but we can recklessly check both as there can't be a false +ve).
9548 foreach ($matches as $match) {
9549 $match = trim($match);
9551 // Try for IP match (Left side).
9552 $lhs = substr($host, 0, strlen($match));
9553 if (strcasecmp($match, $lhs)==0) {
9554 return true;
9557 // Try for host match (Right side).
9558 $rhs = substr($host, -strlen($match));
9559 if (strcasecmp($match, $rhs)==0) {
9560 return true;
9564 // Nothing matched.
9565 return false;
9569 * Check if the passed navigation is of the new style
9571 * @param mixed $navigation
9572 * @return bool true for yes false for no
9574 function is_newnav($navigation) {
9575 if (is_array($navigation) && !empty($navigation['newnav'])) {
9576 return true;
9577 } else {
9578 return false;
9583 * Checks whether the given variable name is defined as a variable within the given object.
9585 * This will NOT work with stdClass objects, which have no class variables.
9587 * @param string $var The variable name
9588 * @param object $object The object to check
9589 * @return boolean
9591 function in_object_vars($var, $object) {
9592 $classvars = get_class_vars(get_class($object));
9593 $classvars = array_keys($classvars);
9594 return in_array($var, $classvars);
9598 * Returns an array without repeated objects.
9599 * This function is similar to array_unique, but for arrays that have objects as values
9601 * @param array $array
9602 * @param bool $keepkeyassoc
9603 * @return array
9605 function object_array_unique($array, $keepkeyassoc = true) {
9606 $duplicatekeys = array();
9607 $tmp = array();
9609 foreach ($array as $key => $val) {
9610 // Convert objects to arrays, in_array() does not support objects.
9611 if (is_object($val)) {
9612 $val = (array)$val;
9615 if (!in_array($val, $tmp)) {
9616 $tmp[] = $val;
9617 } else {
9618 $duplicatekeys[] = $key;
9622 foreach ($duplicatekeys as $key) {
9623 unset($array[$key]);
9626 return $keepkeyassoc ? $array : array_values($array);
9630 * Is a userid the primary administrator?
9632 * @param int $userid int id of user to check
9633 * @return boolean
9635 function is_primary_admin($userid) {
9636 $primaryadmin = get_admin();
9638 if ($userid == $primaryadmin->id) {
9639 return true;
9640 } else {
9641 return false;
9646 * Returns the site identifier
9648 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9650 function get_site_identifier() {
9651 global $CFG;
9652 // Check to see if it is missing. If so, initialise it.
9653 if (empty($CFG->siteidentifier)) {
9654 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9656 // Return it.
9657 return $CFG->siteidentifier;
9661 * Check whether the given password has no more than the specified
9662 * number of consecutive identical characters.
9664 * @param string $password password to be checked against the password policy
9665 * @param integer $maxchars maximum number of consecutive identical characters
9666 * @return bool
9668 function check_consecutive_identical_characters($password, $maxchars) {
9670 if ($maxchars < 1) {
9671 return true; // Zero 0 is to disable this check.
9673 if (strlen($password) <= $maxchars) {
9674 return true; // Too short to fail this test.
9677 $previouschar = '';
9678 $consecutivecount = 1;
9679 foreach (str_split($password) as $char) {
9680 if ($char != $previouschar) {
9681 $consecutivecount = 1;
9682 } else {
9683 $consecutivecount++;
9684 if ($consecutivecount > $maxchars) {
9685 return false; // Check failed already.
9689 $previouschar = $char;
9692 return true;
9696 * Helper function to do partial function binding.
9697 * so we can use it for preg_replace_callback, for example
9698 * this works with php functions, user functions, static methods and class methods
9699 * it returns you a callback that you can pass on like so:
9701 * $callback = partial('somefunction', $arg1, $arg2);
9702 * or
9703 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9704 * or even
9705 * $obj = new someclass();
9706 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9708 * and then the arguments that are passed through at calltime are appended to the argument list.
9710 * @param mixed $function a php callback
9711 * @param mixed $arg1,... $argv arguments to partially bind with
9712 * @return array Array callback
9714 function partial() {
9715 if (!class_exists('partial')) {
9717 * Used to manage function binding.
9718 * @copyright 2009 Penny Leach
9719 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9721 class partial{
9722 /** @var array */
9723 public $values = array();
9724 /** @var string The function to call as a callback. */
9725 public $func;
9727 * Constructor
9728 * @param string $func
9729 * @param array $args
9731 public function __construct($func, $args) {
9732 $this->values = $args;
9733 $this->func = $func;
9736 * Calls the callback function.
9737 * @return mixed
9739 public function method() {
9740 $args = func_get_args();
9741 return call_user_func_array($this->func, array_merge($this->values, $args));
9745 $args = func_get_args();
9746 $func = array_shift($args);
9747 $p = new partial($func, $args);
9748 return array($p, 'method');
9752 * helper function to load up and initialise the mnet environment
9753 * this must be called before you use mnet functions.
9755 * @return mnet_environment the equivalent of old $MNET global
9757 function get_mnet_environment() {
9758 global $CFG;
9759 require_once($CFG->dirroot . '/mnet/lib.php');
9760 static $instance = null;
9761 if (empty($instance)) {
9762 $instance = new mnet_environment();
9763 $instance->init();
9765 return $instance;
9769 * during xmlrpc server code execution, any code wishing to access
9770 * information about the remote peer must use this to get it.
9772 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9774 function get_mnet_remote_client() {
9775 if (!defined('MNET_SERVER')) {
9776 debugging(get_string('notinxmlrpcserver', 'mnet'));
9777 return false;
9779 global $MNET_REMOTE_CLIENT;
9780 if (isset($MNET_REMOTE_CLIENT)) {
9781 return $MNET_REMOTE_CLIENT;
9783 return false;
9787 * during the xmlrpc server code execution, this will be called
9788 * to setup the object returned by {@link get_mnet_remote_client}
9790 * @param mnet_remote_client $client the client to set up
9791 * @throws moodle_exception
9793 function set_mnet_remote_client($client) {
9794 if (!defined('MNET_SERVER')) {
9795 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9797 global $MNET_REMOTE_CLIENT;
9798 $MNET_REMOTE_CLIENT = $client;
9802 * return the jump url for a given remote user
9803 * this is used for rewriting forum post links in emails, etc
9805 * @param stdclass $user the user to get the idp url for
9807 function mnet_get_idp_jump_url($user) {
9808 global $CFG;
9810 static $mnetjumps = array();
9811 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9812 $idp = mnet_get_peer_host($user->mnethostid);
9813 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9814 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9816 return $mnetjumps[$user->mnethostid];
9820 * Gets the homepage to use for the current user
9822 * @return int One of HOMEPAGE_*
9824 function get_home_page() {
9825 global $CFG;
9827 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9828 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9829 return HOMEPAGE_MY;
9830 } else {
9831 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9834 return HOMEPAGE_SITE;
9838 * Gets the name of a course to be displayed when showing a list of courses.
9839 * By default this is just $course->fullname but user can configure it. The
9840 * result of this function should be passed through print_string.
9841 * @param stdClass|course_in_list $course Moodle course object
9842 * @return string Display name of course (either fullname or short + fullname)
9844 function get_course_display_name_for_list($course) {
9845 global $CFG;
9846 if (!empty($CFG->courselistshortnames)) {
9847 if (!($course instanceof stdClass)) {
9848 $course = (object)convert_to_array($course);
9850 return get_string('courseextendednamedisplay', '', $course);
9851 } else {
9852 return $course->fullname;
9857 * Safe analogue of unserialize() that can only parse arrays
9859 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
9860 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
9861 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
9863 * @param string $expression
9864 * @return array|bool either parsed array or false if parsing was impossible.
9866 function unserialize_array($expression) {
9867 $subs = [];
9868 // Find nested arrays, parse them and store in $subs , substitute with special string.
9869 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
9870 $key = '--SUB' . count($subs) . '--';
9871 $subs[$key] = unserialize_array($matches[2]);
9872 if ($subs[$key] === false) {
9873 return false;
9875 $expression = str_replace($matches[2], $key . ';', $expression);
9878 // Check the expression is an array.
9879 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
9880 return false;
9882 // Get the size and elements of an array (key;value;key;value;....).
9883 $parts = explode(';', $matches1[2]);
9884 $size = intval($matches1[1]);
9885 if (count($parts) < $size * 2 + 1) {
9886 return false;
9888 // Analyze each part and make sure it is an integer or string or a substitute.
9889 $value = [];
9890 for ($i = 0; $i < $size * 2; $i++) {
9891 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
9892 $parts[$i] = (int)$matches2[1];
9893 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
9894 $parts[$i] = $matches3[2];
9895 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
9896 $parts[$i] = $subs[$parts[$i]];
9897 } else {
9898 return false;
9901 // Combine keys and values.
9902 for ($i = 0; $i < $size * 2; $i += 2) {
9903 $value[$parts[$i]] = $parts[$i+1];
9905 return $value;
9909 * The lang_string class
9911 * This special class is used to create an object representation of a string request.
9912 * It is special because processing doesn't occur until the object is first used.
9913 * The class was created especially to aid performance in areas where strings were
9914 * required to be generated but were not necessarily used.
9915 * As an example the admin tree when generated uses over 1500 strings, of which
9916 * normally only 1/3 are ever actually printed at any time.
9917 * The performance advantage is achieved by not actually processing strings that
9918 * arn't being used, as such reducing the processing required for the page.
9920 * How to use the lang_string class?
9921 * There are two methods of using the lang_string class, first through the
9922 * forth argument of the get_string function, and secondly directly.
9923 * The following are examples of both.
9924 * 1. Through get_string calls e.g.
9925 * $string = get_string($identifier, $component, $a, true);
9926 * $string = get_string('yes', 'moodle', null, true);
9927 * 2. Direct instantiation
9928 * $string = new lang_string($identifier, $component, $a, $lang);
9929 * $string = new lang_string('yes');
9931 * How do I use a lang_string object?
9932 * The lang_string object makes use of a magic __toString method so that you
9933 * are able to use the object exactly as you would use a string in most cases.
9934 * This means you are able to collect it into a variable and then directly
9935 * echo it, or concatenate it into another string, or similar.
9936 * The other thing you can do is manually get the string by calling the
9937 * lang_strings out method e.g.
9938 * $string = new lang_string('yes');
9939 * $string->out();
9940 * Also worth noting is that the out method can take one argument, $lang which
9941 * allows the developer to change the language on the fly.
9943 * When should I use a lang_string object?
9944 * The lang_string object is designed to be used in any situation where a
9945 * string may not be needed, but needs to be generated.
9946 * The admin tree is a good example of where lang_string objects should be
9947 * used.
9948 * A more practical example would be any class that requries strings that may
9949 * not be printed (after all classes get renderer by renderers and who knows
9950 * what they will do ;))
9952 * When should I not use a lang_string object?
9953 * Don't use lang_strings when you are going to use a string immediately.
9954 * There is no need as it will be processed immediately and there will be no
9955 * advantage, and in fact perhaps a negative hit as a class has to be
9956 * instantiated for a lang_string object, however get_string won't require
9957 * that.
9959 * Limitations:
9960 * 1. You cannot use a lang_string object as an array offset. Doing so will
9961 * result in PHP throwing an error. (You can use it as an object property!)
9963 * @package core
9964 * @category string
9965 * @copyright 2011 Sam Hemelryk
9966 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9968 class lang_string {
9970 /** @var string The strings identifier */
9971 protected $identifier;
9972 /** @var string The strings component. Default '' */
9973 protected $component = '';
9974 /** @var array|stdClass Any arguments required for the string. Default null */
9975 protected $a = null;
9976 /** @var string The language to use when processing the string. Default null */
9977 protected $lang = null;
9979 /** @var string The processed string (once processed) */
9980 protected $string = null;
9983 * A special boolean. If set to true then the object has been woken up and
9984 * cannot be regenerated. If this is set then $this->string MUST be used.
9985 * @var bool
9987 protected $forcedstring = false;
9990 * Constructs a lang_string object
9992 * This function should do as little processing as possible to ensure the best
9993 * performance for strings that won't be used.
9995 * @param string $identifier The strings identifier
9996 * @param string $component The strings component
9997 * @param stdClass|array $a Any arguments the string requires
9998 * @param string $lang The language to use when processing the string.
9999 * @throws coding_exception
10001 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10002 if (empty($component)) {
10003 $component = 'moodle';
10006 $this->identifier = $identifier;
10007 $this->component = $component;
10008 $this->lang = $lang;
10010 // We MUST duplicate $a to ensure that it if it changes by reference those
10011 // changes are not carried across.
10012 // To do this we always ensure $a or its properties/values are strings
10013 // and that any properties/values that arn't convertable are forgotten.
10014 if (!empty($a)) {
10015 if (is_scalar($a)) {
10016 $this->a = $a;
10017 } else if ($a instanceof lang_string) {
10018 $this->a = $a->out();
10019 } else if (is_object($a) or is_array($a)) {
10020 $a = (array)$a;
10021 $this->a = array();
10022 foreach ($a as $key => $value) {
10023 // Make sure conversion errors don't get displayed (results in '').
10024 if (is_array($value)) {
10025 $this->a[$key] = '';
10026 } else if (is_object($value)) {
10027 if (method_exists($value, '__toString')) {
10028 $this->a[$key] = $value->__toString();
10029 } else {
10030 $this->a[$key] = '';
10032 } else {
10033 $this->a[$key] = (string)$value;
10039 if (debugging(false, DEBUG_DEVELOPER)) {
10040 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10041 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10043 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10044 throw new coding_exception('Invalid string compontent. Please check your string definition');
10046 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10047 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10053 * Processes the string.
10055 * This function actually processes the string, stores it in the string property
10056 * and then returns it.
10057 * You will notice that this function is VERY similar to the get_string method.
10058 * That is because it is pretty much doing the same thing.
10059 * However as this function is an upgrade it isn't as tolerant to backwards
10060 * compatibility.
10062 * @return string
10063 * @throws coding_exception
10065 protected function get_string() {
10066 global $CFG;
10068 // Check if we need to process the string.
10069 if ($this->string === null) {
10070 // Check the quality of the identifier.
10071 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10072 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);
10075 // Process the string.
10076 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10077 // Debugging feature lets you display string identifier and component.
10078 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10079 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10082 // Return the string.
10083 return $this->string;
10087 * Returns the string
10089 * @param string $lang The langauge to use when processing the string
10090 * @return string
10092 public function out($lang = null) {
10093 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10094 if ($this->forcedstring) {
10095 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10096 return $this->get_string();
10098 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10099 return $translatedstring->out();
10101 return $this->get_string();
10105 * Magic __toString method for printing a string
10107 * @return string
10109 public function __toString() {
10110 return $this->get_string();
10114 * Magic __set_state method used for var_export
10116 * @return string
10118 public function __set_state() {
10119 return $this->get_string();
10123 * Prepares the lang_string for sleep and stores only the forcedstring and
10124 * string properties... the string cannot be regenerated so we need to ensure
10125 * it is generated for this.
10127 * @return string
10129 public function __sleep() {
10130 $this->get_string();
10131 $this->forcedstring = true;
10132 return array('forcedstring', 'string', 'lang');
10136 * Returns the identifier.
10138 * @return string
10140 public function get_identifier() {
10141 return $this->identifier;
10145 * Returns the component.
10147 * @return string
10149 public function get_component() {
10150 return $this->component;