MDL-36754 output: Support token pluginfiles in group pic
[moodle.git] / lib / moodlelib.php
blob4962aa46499b11a87561bccc4d0e0ed0dc0a33cb
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 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3116 * @return int Instance ID
3118 function require_user_key_login($script, $instance = null, $keyvalue = null) {
3119 global $DB;
3121 if (!NO_MOODLE_COOKIES) {
3122 print_error('sessioncookiesdisable');
3125 // Extra safety.
3126 \core\session\manager::write_close();
3128 if (null === $keyvalue) {
3129 $keyvalue = required_param('key', PARAM_ALPHANUM);
3132 $key = validate_user_key($keyvalue, $script, $instance);
3134 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3135 print_error('invaliduserid');
3138 // Emulate normal session.
3139 enrol_check_plugins($user);
3140 \core\session\manager::set_user($user);
3142 // Note we are not using normal login.
3143 if (!defined('USER_KEY_LOGIN')) {
3144 define('USER_KEY_LOGIN', true);
3147 // Return instance id - it might be empty.
3148 return $key->instance;
3152 * Creates a new private user access key.
3154 * @param string $script unique target identifier
3155 * @param int $userid
3156 * @param int $instance optional instance id
3157 * @param string $iprestriction optional ip restricted access
3158 * @param int $validuntil key valid only until given data
3159 * @return string access key value
3161 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3162 global $DB;
3164 $key = new stdClass();
3165 $key->script = $script;
3166 $key->userid = $userid;
3167 $key->instance = $instance;
3168 $key->iprestriction = $iprestriction;
3169 $key->validuntil = $validuntil;
3170 $key->timecreated = time();
3172 // Something long and unique.
3173 $key->value = md5($userid.'_'.time().random_string(40));
3174 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3175 // Must be unique.
3176 $key->value = md5($userid.'_'.time().random_string(40));
3178 $DB->insert_record('user_private_key', $key);
3179 return $key->value;
3183 * Delete the user's new private user access keys for a particular script.
3185 * @param string $script unique target identifier
3186 * @param int $userid
3187 * @return void
3189 function delete_user_key($script, $userid) {
3190 global $DB;
3191 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3195 * Gets a private user access key (and creates one if one doesn't exist).
3197 * @param string $script unique target identifier
3198 * @param int $userid
3199 * @param int $instance optional instance id
3200 * @param string $iprestriction optional ip restricted access
3201 * @param int $validuntil key valid only until given date
3202 * @return string access key value
3204 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3205 global $DB;
3207 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3208 'instance' => $instance, 'iprestriction' => $iprestriction,
3209 'validuntil' => $validuntil))) {
3210 return $key->value;
3211 } else {
3212 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3218 * Modify the user table by setting the currently logged in user's last login to now.
3220 * @return bool Always returns true
3222 function update_user_login_times() {
3223 global $USER, $DB;
3225 if (isguestuser()) {
3226 // Do not update guest access times/ips for performance.
3227 return true;
3230 $now = time();
3232 $user = new stdClass();
3233 $user->id = $USER->id;
3235 // Make sure all users that logged in have some firstaccess.
3236 if ($USER->firstaccess == 0) {
3237 $USER->firstaccess = $user->firstaccess = $now;
3240 // Store the previous current as lastlogin.
3241 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3243 $USER->currentlogin = $user->currentlogin = $now;
3245 // Function user_accesstime_log() may not update immediately, better do it here.
3246 $USER->lastaccess = $user->lastaccess = $now;
3247 $USER->lastip = $user->lastip = getremoteaddr();
3249 // Note: do not call user_update_user() here because this is part of the login process,
3250 // the login event means that these fields were updated.
3251 $DB->update_record('user', $user);
3252 return true;
3256 * Determines if a user has completed setting up their account.
3258 * The lax mode (with $strict = false) has been introduced for special cases
3259 * only where we want to skip certain checks intentionally. This is valid in
3260 * certain mnet or ajax scenarios when the user cannot / should not be
3261 * redirected to edit their profile. In most cases, you should perform the
3262 * strict check.
3264 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3265 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3266 * @return bool
3268 function user_not_fully_set_up($user, $strict = true) {
3269 global $CFG;
3270 require_once($CFG->dirroot.'/user/profile/lib.php');
3272 if (isguestuser($user)) {
3273 return false;
3276 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3277 return true;
3280 if ($strict) {
3281 if (empty($user->id)) {
3282 // Strict mode can be used with existing accounts only.
3283 return true;
3285 if (!profile_has_required_custom_fields_set($user->id)) {
3286 return true;
3290 return false;
3294 * Check whether the user has exceeded the bounce threshold
3296 * @param stdClass $user A {@link $USER} object
3297 * @return bool true => User has exceeded bounce threshold
3299 function over_bounce_threshold($user) {
3300 global $CFG, $DB;
3302 if (empty($CFG->handlebounces)) {
3303 return false;
3306 if (empty($user->id)) {
3307 // No real (DB) user, nothing to do here.
3308 return false;
3311 // Set sensible defaults.
3312 if (empty($CFG->minbounces)) {
3313 $CFG->minbounces = 10;
3315 if (empty($CFG->bounceratio)) {
3316 $CFG->bounceratio = .20;
3318 $bouncecount = 0;
3319 $sendcount = 0;
3320 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3321 $bouncecount = $bounce->value;
3323 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3324 $sendcount = $send->value;
3326 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3330 * Used to increment or reset email sent count
3332 * @param stdClass $user object containing an id
3333 * @param bool $reset will reset the count to 0
3334 * @return void
3336 function set_send_count($user, $reset=false) {
3337 global $DB;
3339 if (empty($user->id)) {
3340 // No real (DB) user, nothing to do here.
3341 return;
3344 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3345 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3346 $DB->update_record('user_preferences', $pref);
3347 } else if (!empty($reset)) {
3348 // If it's not there and we're resetting, don't bother. Make a new one.
3349 $pref = new stdClass();
3350 $pref->name = 'email_send_count';
3351 $pref->value = 1;
3352 $pref->userid = $user->id;
3353 $DB->insert_record('user_preferences', $pref, false);
3358 * Increment or reset user's email bounce count
3360 * @param stdClass $user object containing an id
3361 * @param bool $reset will reset the count to 0
3363 function set_bounce_count($user, $reset=false) {
3364 global $DB;
3366 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3367 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3368 $DB->update_record('user_preferences', $pref);
3369 } else if (!empty($reset)) {
3370 // If it's not there and we're resetting, don't bother. Make a new one.
3371 $pref = new stdClass();
3372 $pref->name = 'email_bounce_count';
3373 $pref->value = 1;
3374 $pref->userid = $user->id;
3375 $DB->insert_record('user_preferences', $pref, false);
3380 * Determines if the logged in user is currently moving an activity
3382 * @param int $courseid The id of the course being tested
3383 * @return bool
3385 function ismoving($courseid) {
3386 global $USER;
3388 if (!empty($USER->activitycopy)) {
3389 return ($USER->activitycopycourse == $courseid);
3391 return false;
3395 * Returns a persons full name
3397 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3398 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3399 * specify one.
3401 * @param stdClass $user A {@link $USER} object to get full name of.
3402 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3403 * @return string
3405 function fullname($user, $override=false) {
3406 global $CFG, $SESSION;
3408 if (!isset($user->firstname) and !isset($user->lastname)) {
3409 return '';
3412 // Get all of the name fields.
3413 $allnames = get_all_user_name_fields();
3414 if ($CFG->debugdeveloper) {
3415 foreach ($allnames as $allname) {
3416 if (!property_exists($user, $allname)) {
3417 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3418 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3419 // Message has been sent, no point in sending the message multiple times.
3420 break;
3425 if (!$override) {
3426 if (!empty($CFG->forcefirstname)) {
3427 $user->firstname = $CFG->forcefirstname;
3429 if (!empty($CFG->forcelastname)) {
3430 $user->lastname = $CFG->forcelastname;
3434 if (!empty($SESSION->fullnamedisplay)) {
3435 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3438 $template = null;
3439 // If the fullnamedisplay setting is available, set the template to that.
3440 if (isset($CFG->fullnamedisplay)) {
3441 $template = $CFG->fullnamedisplay;
3443 // If the template is empty, or set to language, return the language string.
3444 if ((empty($template) || $template == 'language') && !$override) {
3445 return get_string('fullnamedisplay', null, $user);
3448 // Check to see if we are displaying according to the alternative full name format.
3449 if ($override) {
3450 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3451 // Default to show just the user names according to the fullnamedisplay string.
3452 return get_string('fullnamedisplay', null, $user);
3453 } else {
3454 // If the override is true, then change the template to use the complete name.
3455 $template = $CFG->alternativefullnameformat;
3459 $requirednames = array();
3460 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3461 foreach ($allnames as $allname) {
3462 if (strpos($template, $allname) !== false) {
3463 $requirednames[] = $allname;
3467 $displayname = $template;
3468 // Switch in the actual data into the template.
3469 foreach ($requirednames as $altname) {
3470 if (isset($user->$altname)) {
3471 // Using empty() on the below if statement causes breakages.
3472 if ((string)$user->$altname == '') {
3473 $displayname = str_replace($altname, 'EMPTY', $displayname);
3474 } else {
3475 $displayname = str_replace($altname, $user->$altname, $displayname);
3477 } else {
3478 $displayname = str_replace($altname, 'EMPTY', $displayname);
3481 // Tidy up any misc. characters (Not perfect, but gets most characters).
3482 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3483 // katakana and parenthesis.
3484 $patterns = array();
3485 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3486 // filled in by a user.
3487 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3488 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3489 // This regular expression is to remove any double spaces in the display name.
3490 $patterns[] = '/\s{2,}/u';
3491 foreach ($patterns as $pattern) {
3492 $displayname = preg_replace($pattern, ' ', $displayname);
3495 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3496 $displayname = trim($displayname);
3497 if (empty($displayname)) {
3498 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3499 // people in general feel is a good setting to fall back on.
3500 $displayname = $user->firstname;
3502 return $displayname;
3506 * A centralised location for the all name fields. Returns an array / sql string snippet.
3508 * @param bool $returnsql True for an sql select field snippet.
3509 * @param string $tableprefix table query prefix to use in front of each field.
3510 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3511 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3512 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3513 * @return array|string All name fields.
3515 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3516 // This array is provided in this order because when called by fullname() (above) if firstname is before
3517 // firstnamephonetic str_replace() will change the wrong placeholder.
3518 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3519 'lastnamephonetic' => 'lastnamephonetic',
3520 'middlename' => 'middlename',
3521 'alternatename' => 'alternatename',
3522 'firstname' => 'firstname',
3523 'lastname' => 'lastname');
3525 // Let's add a prefix to the array of user name fields if provided.
3526 if ($prefix) {
3527 foreach ($alternatenames as $key => $altname) {
3528 $alternatenames[$key] = $prefix . $altname;
3532 // If we want the end result to have firstname and lastname at the front / top of the result.
3533 if ($order) {
3534 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3535 for ($i = 0; $i < 2; $i++) {
3536 // Get the last element.
3537 $lastelement = end($alternatenames);
3538 // Remove it from the array.
3539 unset($alternatenames[$lastelement]);
3540 // Put the element back on the top of the array.
3541 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3545 // Create an sql field snippet if requested.
3546 if ($returnsql) {
3547 if ($tableprefix) {
3548 if ($fieldprefix) {
3549 foreach ($alternatenames as $key => $altname) {
3550 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3552 } else {
3553 foreach ($alternatenames as $key => $altname) {
3554 $alternatenames[$key] = $tableprefix . '.' . $altname;
3558 $alternatenames = implode(',', $alternatenames);
3560 return $alternatenames;
3564 * Reduces lines of duplicated code for getting user name fields.
3566 * See also {@link user_picture::unalias()}
3568 * @param object $addtoobject Object to add user name fields to.
3569 * @param object $secondobject Object that contains user name field information.
3570 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3571 * @param array $additionalfields Additional fields to be matched with data in the second object.
3572 * The key can be set to the user table field name.
3573 * @return object User name fields.
3575 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3576 $fields = get_all_user_name_fields(false, null, $prefix);
3577 if ($additionalfields) {
3578 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3579 // the key is a number and then sets the key to the array value.
3580 foreach ($additionalfields as $key => $value) {
3581 if (is_numeric($key)) {
3582 $additionalfields[$value] = $prefix . $value;
3583 unset($additionalfields[$key]);
3584 } else {
3585 $additionalfields[$key] = $prefix . $value;
3588 $fields = array_merge($fields, $additionalfields);
3590 foreach ($fields as $key => $field) {
3591 // Important that we have all of the user name fields present in the object that we are sending back.
3592 $addtoobject->$key = '';
3593 if (isset($secondobject->$field)) {
3594 $addtoobject->$key = $secondobject->$field;
3597 return $addtoobject;
3601 * Returns an array of values in order of occurance in a provided string.
3602 * The key in the result is the character postion in the string.
3604 * @param array $values Values to be found in the string format
3605 * @param string $stringformat The string which may contain values being searched for.
3606 * @return array An array of values in order according to placement in the string format.
3608 function order_in_string($values, $stringformat) {
3609 $valuearray = array();
3610 foreach ($values as $value) {
3611 $pattern = "/$value\b/";
3612 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3613 if (preg_match($pattern, $stringformat)) {
3614 $replacement = "thing";
3615 // Replace the value with something more unique to ensure we get the right position when using strpos().
3616 $newformat = preg_replace($pattern, $replacement, $stringformat);
3617 $position = strpos($newformat, $replacement);
3618 $valuearray[$position] = $value;
3621 ksort($valuearray);
3622 return $valuearray;
3626 * Checks if current user is shown any extra fields when listing users.
3628 * @param object $context Context
3629 * @param array $already Array of fields that we're going to show anyway
3630 * so don't bother listing them
3631 * @return array Array of field names from user table, not including anything
3632 * listed in $already
3634 function get_extra_user_fields($context, $already = array()) {
3635 global $CFG;
3637 // Only users with permission get the extra fields.
3638 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3639 return array();
3642 // Split showuseridentity on comma (filter needed in case the showuseridentity is empty).
3643 $extra = array_filter(explode(',', $CFG->showuseridentity));
3645 foreach ($extra as $key => $field) {
3646 if (in_array($field, $already)) {
3647 unset($extra[$key]);
3651 // If the identity fields are also among hidden fields, make sure the user can see them.
3652 $hiddenfields = array_filter(explode(',', $CFG->hiddenuserfields));
3653 $hiddenidentifiers = array_intersect($extra, $hiddenfields);
3655 if ($hiddenidentifiers) {
3656 if ($context->get_course_context(false)) {
3657 // We are somewhere inside a course.
3658 $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3660 } else {
3661 // We are not inside a course.
3662 $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
3665 if (!$canviewhiddenuserfields) {
3666 // Remove hidden identifiers from the list.
3667 $extra = array_diff($extra, $hiddenidentifiers);
3671 // Re-index the entries.
3672 $extra = array_values($extra);
3674 return $extra;
3678 * If the current user is to be shown extra user fields when listing or
3679 * selecting users, returns a string suitable for including in an SQL select
3680 * clause to retrieve those fields.
3682 * @param context $context Context
3683 * @param string $alias Alias of user table, e.g. 'u' (default none)
3684 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3685 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3686 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3688 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3689 $fields = get_extra_user_fields($context, $already);
3690 $result = '';
3691 // Add punctuation for alias.
3692 if ($alias !== '') {
3693 $alias .= '.';
3695 foreach ($fields as $field) {
3696 $result .= ', ' . $alias . $field;
3697 if ($prefix) {
3698 $result .= ' AS ' . $prefix . $field;
3701 return $result;
3705 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3706 * @param string $field Field name, e.g. 'phone1'
3707 * @return string Text description taken from language file, e.g. 'Phone number'
3709 function get_user_field_name($field) {
3710 // Some fields have language strings which are not the same as field name.
3711 switch ($field) {
3712 case 'url' : {
3713 return get_string('webpage');
3715 case 'icq' : {
3716 return get_string('icqnumber');
3718 case 'skype' : {
3719 return get_string('skypeid');
3721 case 'aim' : {
3722 return get_string('aimid');
3724 case 'yahoo' : {
3725 return get_string('yahooid');
3727 case 'msn' : {
3728 return get_string('msnid');
3730 case 'picture' : {
3731 return get_string('pictureofuser');
3734 // Otherwise just use the same lang string.
3735 return get_string($field);
3739 * Returns whether a given authentication plugin exists.
3741 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3742 * @return boolean Whether the plugin is available.
3744 function exists_auth_plugin($auth) {
3745 global $CFG;
3747 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3748 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3750 return false;
3754 * Checks if a given plugin is in the list of enabled authentication plugins.
3756 * @param string $auth Authentication plugin.
3757 * @return boolean Whether the plugin is enabled.
3759 function is_enabled_auth($auth) {
3760 if (empty($auth)) {
3761 return false;
3764 $enabled = get_enabled_auth_plugins();
3766 return in_array($auth, $enabled);
3770 * Returns an authentication plugin instance.
3772 * @param string $auth name of authentication plugin
3773 * @return auth_plugin_base An instance of the required authentication plugin.
3775 function get_auth_plugin($auth) {
3776 global $CFG;
3778 // Check the plugin exists first.
3779 if (! exists_auth_plugin($auth)) {
3780 print_error('authpluginnotfound', 'debug', '', $auth);
3783 // Return auth plugin instance.
3784 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3785 $class = "auth_plugin_$auth";
3786 return new $class;
3790 * Returns array of active auth plugins.
3792 * @param bool $fix fix $CFG->auth if needed
3793 * @return array
3795 function get_enabled_auth_plugins($fix=false) {
3796 global $CFG;
3798 $default = array('manual', 'nologin');
3800 if (empty($CFG->auth)) {
3801 $auths = array();
3802 } else {
3803 $auths = explode(',', $CFG->auth);
3806 if ($fix) {
3807 $auths = array_unique($auths);
3808 foreach ($auths as $k => $authname) {
3809 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3810 unset($auths[$k]);
3813 $newconfig = implode(',', $auths);
3814 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3815 set_config('auth', $newconfig);
3819 return (array_merge($default, $auths));
3823 * Returns true if an internal authentication method is being used.
3824 * if method not specified then, global default is assumed
3826 * @param string $auth Form of authentication required
3827 * @return bool
3829 function is_internal_auth($auth) {
3830 // Throws error if bad $auth.
3831 $authplugin = get_auth_plugin($auth);
3832 return $authplugin->is_internal();
3836 * Returns true if the user is a 'restored' one.
3838 * Used in the login process to inform the user and allow him/her to reset the password
3840 * @param string $username username to be checked
3841 * @return bool
3843 function is_restored_user($username) {
3844 global $CFG, $DB;
3846 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3850 * Returns an array of user fields
3852 * @return array User field/column names
3854 function get_user_fieldnames() {
3855 global $DB;
3857 $fieldarray = $DB->get_columns('user');
3858 unset($fieldarray['id']);
3859 $fieldarray = array_keys($fieldarray);
3861 return $fieldarray;
3865 * Creates a bare-bones user record
3867 * @todo Outline auth types and provide code example
3869 * @param string $username New user's username to add to record
3870 * @param string $password New user's password to add to record
3871 * @param string $auth Form of authentication required
3872 * @return stdClass A complete user object
3874 function create_user_record($username, $password, $auth = 'manual') {
3875 global $CFG, $DB;
3876 require_once($CFG->dirroot.'/user/profile/lib.php');
3877 require_once($CFG->dirroot.'/user/lib.php');
3879 // Just in case check text case.
3880 $username = trim(core_text::strtolower($username));
3882 $authplugin = get_auth_plugin($auth);
3883 $customfields = $authplugin->get_custom_user_profile_fields();
3884 $newuser = new stdClass();
3885 if ($newinfo = $authplugin->get_userinfo($username)) {
3886 $newinfo = truncate_userinfo($newinfo);
3887 foreach ($newinfo as $key => $value) {
3888 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3889 $newuser->$key = $value;
3894 if (!empty($newuser->email)) {
3895 if (email_is_not_allowed($newuser->email)) {
3896 unset($newuser->email);
3900 if (!isset($newuser->city)) {
3901 $newuser->city = '';
3904 $newuser->auth = $auth;
3905 $newuser->username = $username;
3907 // Fix for MDL-8480
3908 // user CFG lang for user if $newuser->lang is empty
3909 // or $user->lang is not an installed language.
3910 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3911 $newuser->lang = $CFG->lang;
3913 $newuser->confirmed = 1;
3914 $newuser->lastip = getremoteaddr();
3915 $newuser->timecreated = time();
3916 $newuser->timemodified = $newuser->timecreated;
3917 $newuser->mnethostid = $CFG->mnet_localhost_id;
3919 $newuser->id = user_create_user($newuser, false, false);
3921 // Save user profile data.
3922 profile_save_data($newuser);
3924 $user = get_complete_user_data('id', $newuser->id);
3925 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3926 set_user_preference('auth_forcepasswordchange', 1, $user);
3928 // Set the password.
3929 update_internal_user_password($user, $password);
3931 // Trigger event.
3932 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3934 return $user;
3938 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3940 * @param string $username user's username to update the record
3941 * @return stdClass A complete user object
3943 function update_user_record($username) {
3944 global $DB, $CFG;
3945 // Just in case check text case.
3946 $username = trim(core_text::strtolower($username));
3948 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3949 return update_user_record_by_id($oldinfo->id);
3953 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3955 * @param int $id user id
3956 * @return stdClass A complete user object
3958 function update_user_record_by_id($id) {
3959 global $DB, $CFG;
3960 require_once($CFG->dirroot."/user/profile/lib.php");
3961 require_once($CFG->dirroot.'/user/lib.php');
3963 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3964 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3966 $newuser = array();
3967 $userauth = get_auth_plugin($oldinfo->auth);
3969 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3970 $newinfo = truncate_userinfo($newinfo);
3971 $customfields = $userauth->get_custom_user_profile_fields();
3973 foreach ($newinfo as $key => $value) {
3974 $iscustom = in_array($key, $customfields);
3975 if (!$iscustom) {
3976 $key = strtolower($key);
3978 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3979 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3980 // Unknown or must not be changed.
3981 continue;
3983 if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
3984 continue;
3986 $confval = $userauth->config->{'field_updatelocal_' . $key};
3987 $lockval = $userauth->config->{'field_lock_' . $key};
3988 if ($confval === 'onlogin') {
3989 // MDL-4207 Don't overwrite modified user profile values with
3990 // empty LDAP values when 'unlocked if empty' is set. The purpose
3991 // of the setting 'unlocked if empty' is to allow the user to fill
3992 // in a value for the selected field _if LDAP is giving
3993 // nothing_ for this field. Thus it makes sense to let this value
3994 // stand in until LDAP is giving a value for this field.
3995 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3996 if ($iscustom || (in_array($key, $userauth->userfields) &&
3997 ((string)$oldinfo->$key !== (string)$value))) {
3998 $newuser[$key] = (string)$value;
4003 if ($newuser) {
4004 $newuser['id'] = $oldinfo->id;
4005 $newuser['timemodified'] = time();
4006 user_update_user((object) $newuser, false, false);
4008 // Save user profile data.
4009 profile_save_data((object) $newuser);
4011 // Trigger event.
4012 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4016 return get_complete_user_data('id', $oldinfo->id);
4020 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4022 * @param array $info Array of user properties to truncate if needed
4023 * @return array The now truncated information that was passed in
4025 function truncate_userinfo(array $info) {
4026 // Define the limits.
4027 $limit = array(
4028 'username' => 100,
4029 'idnumber' => 255,
4030 'firstname' => 100,
4031 'lastname' => 100,
4032 'email' => 100,
4033 'icq' => 15,
4034 'phone1' => 20,
4035 'phone2' => 20,
4036 'institution' => 255,
4037 'department' => 255,
4038 'address' => 255,
4039 'city' => 120,
4040 'country' => 2,
4041 'url' => 255,
4044 // Apply where needed.
4045 foreach (array_keys($info) as $key) {
4046 if (!empty($limit[$key])) {
4047 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4051 return $info;
4055 * Marks user deleted in internal user database and notifies the auth plugin.
4056 * Also unenrols user from all roles and does other cleanup.
4058 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4060 * @param stdClass $user full user object before delete
4061 * @return boolean success
4062 * @throws coding_exception if invalid $user parameter detected
4064 function delete_user(stdClass $user) {
4065 global $CFG, $DB;
4066 require_once($CFG->libdir.'/grouplib.php');
4067 require_once($CFG->libdir.'/gradelib.php');
4068 require_once($CFG->dirroot.'/message/lib.php');
4069 require_once($CFG->dirroot.'/user/lib.php');
4071 // Make sure nobody sends bogus record type as parameter.
4072 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4073 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4076 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4077 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4078 debugging('Attempt to delete unknown user account.');
4079 return false;
4082 // There must be always exactly one guest record, originally the guest account was identified by username only,
4083 // now we use $CFG->siteguest for performance reasons.
4084 if ($user->username === 'guest' or isguestuser($user)) {
4085 debugging('Guest user account can not be deleted.');
4086 return false;
4089 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4090 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4091 if ($user->auth === 'manual' and is_siteadmin($user)) {
4092 debugging('Local administrator accounts can not be deleted.');
4093 return false;
4096 // Allow plugins to use this user object before we completely delete it.
4097 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4098 foreach ($pluginsfunction as $plugintype => $plugins) {
4099 foreach ($plugins as $pluginfunction) {
4100 $pluginfunction($user);
4105 // Keep user record before updating it, as we have to pass this to user_deleted event.
4106 $olduser = clone $user;
4108 // Keep a copy of user context, we need it for event.
4109 $usercontext = context_user::instance($user->id);
4111 // Delete all grades - backup is kept in grade_grades_history table.
4112 grade_user_delete($user->id);
4114 // TODO: remove from cohorts using standard API here.
4116 // Remove user tags.
4117 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4119 // Unconditionally unenrol from all courses.
4120 enrol_user_delete($user);
4122 // Unenrol from all roles in all contexts.
4123 // This might be slow but it is really needed - modules might do some extra cleanup!
4124 role_unassign_all(array('userid' => $user->id));
4126 // Now do a brute force cleanup.
4128 // Remove from all cohorts.
4129 $DB->delete_records('cohort_members', array('userid' => $user->id));
4131 // Remove from all groups.
4132 $DB->delete_records('groups_members', array('userid' => $user->id));
4134 // Brute force unenrol from all courses.
4135 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4137 // Purge user preferences.
4138 $DB->delete_records('user_preferences', array('userid' => $user->id));
4140 // Purge user extra profile info.
4141 $DB->delete_records('user_info_data', array('userid' => $user->id));
4143 // Purge log of previous password hashes.
4144 $DB->delete_records('user_password_history', array('userid' => $user->id));
4146 // Last course access not necessary either.
4147 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4148 // Remove all user tokens.
4149 $DB->delete_records('external_tokens', array('userid' => $user->id));
4151 // Unauthorise the user for all services.
4152 $DB->delete_records('external_services_users', array('userid' => $user->id));
4154 // Remove users private keys.
4155 $DB->delete_records('user_private_key', array('userid' => $user->id));
4157 // Remove users customised pages.
4158 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4160 // Force logout - may fail if file based sessions used, sorry.
4161 \core\session\manager::kill_user_sessions($user->id);
4163 // Generate username from email address, or a fake email.
4164 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4165 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
4167 // Workaround for bulk deletes of users with the same email address.
4168 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4169 $delname++;
4172 // Mark internal user record as "deleted".
4173 $updateuser = new stdClass();
4174 $updateuser->id = $user->id;
4175 $updateuser->deleted = 1;
4176 $updateuser->username = $delname; // Remember it just in case.
4177 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4178 $updateuser->idnumber = ''; // Clear this field to free it up.
4179 $updateuser->picture = 0;
4180 $updateuser->timemodified = time();
4182 // Don't trigger update event, as user is being deleted.
4183 user_update_user($updateuser, false, false);
4185 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4186 context_helper::delete_instance(CONTEXT_USER, $user->id);
4188 // Any plugin that needs to cleanup should register this event.
4189 // Trigger event.
4190 $event = \core\event\user_deleted::create(
4191 array(
4192 'objectid' => $user->id,
4193 'relateduserid' => $user->id,
4194 'context' => $usercontext,
4195 'other' => array(
4196 'username' => $user->username,
4197 'email' => $user->email,
4198 'idnumber' => $user->idnumber,
4199 'picture' => $user->picture,
4200 'mnethostid' => $user->mnethostid
4204 $event->add_record_snapshot('user', $olduser);
4205 $event->trigger();
4207 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4208 // should know about this updated property persisted to the user's table.
4209 $user->timemodified = $updateuser->timemodified;
4211 // Notify auth plugin - do not block the delete even when plugin fails.
4212 $authplugin = get_auth_plugin($user->auth);
4213 $authplugin->user_delete($user);
4215 return true;
4219 * Retrieve the guest user object.
4221 * @return stdClass A {@link $USER} object
4223 function guest_user() {
4224 global $CFG, $DB;
4226 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4227 $newuser->confirmed = 1;
4228 $newuser->lang = $CFG->lang;
4229 $newuser->lastip = getremoteaddr();
4232 return $newuser;
4236 * Authenticates a user against the chosen authentication mechanism
4238 * Given a username and password, this function looks them
4239 * up using the currently selected authentication mechanism,
4240 * and if the authentication is successful, it returns a
4241 * valid $user object from the 'user' table.
4243 * Uses auth_ functions from the currently active auth module
4245 * After authenticate_user_login() returns success, you will need to
4246 * log that the user has logged in, and call complete_user_login() to set
4247 * the session up.
4249 * Note: this function works only with non-mnet accounts!
4251 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4252 * @param string $password User's password
4253 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4254 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4255 * @return stdClass|false A {@link $USER} object or false if error
4257 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4258 global $CFG, $DB;
4259 require_once("$CFG->libdir/authlib.php");
4261 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4262 // we have found the user
4264 } else if (!empty($CFG->authloginviaemail)) {
4265 if ($email = clean_param($username, PARAM_EMAIL)) {
4266 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4267 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4268 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4269 if (count($users) === 1) {
4270 // Use email for login only if unique.
4271 $user = reset($users);
4272 $user = get_complete_user_data('id', $user->id);
4273 $username = $user->username;
4275 unset($users);
4279 $authsenabled = get_enabled_auth_plugins();
4281 if ($user) {
4282 // Use manual if auth not set.
4283 $auth = empty($user->auth) ? 'manual' : $user->auth;
4285 if (in_array($user->auth, $authsenabled)) {
4286 $authplugin = get_auth_plugin($user->auth);
4287 $authplugin->pre_user_login_hook($user);
4290 if (!empty($user->suspended)) {
4291 $failurereason = AUTH_LOGIN_SUSPENDED;
4293 // Trigger login failed event.
4294 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4295 'other' => array('username' => $username, 'reason' => $failurereason)));
4296 $event->trigger();
4297 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4298 return false;
4300 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4301 // Legacy way to suspend user.
4302 $failurereason = AUTH_LOGIN_SUSPENDED;
4304 // Trigger login failed event.
4305 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4306 'other' => array('username' => $username, 'reason' => $failurereason)));
4307 $event->trigger();
4308 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4309 return false;
4311 $auths = array($auth);
4313 } else {
4314 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4315 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4316 $failurereason = AUTH_LOGIN_NOUSER;
4318 // Trigger login failed event.
4319 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4320 'reason' => $failurereason)));
4321 $event->trigger();
4322 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4323 return false;
4326 // User does not exist.
4327 $auths = $authsenabled;
4328 $user = new stdClass();
4329 $user->id = 0;
4332 if ($ignorelockout) {
4333 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4334 // or this function is called from a SSO script.
4335 } else if ($user->id) {
4336 // Verify login lockout after other ways that may prevent user login.
4337 if (login_is_lockedout($user)) {
4338 $failurereason = AUTH_LOGIN_LOCKOUT;
4340 // Trigger login failed event.
4341 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4342 'other' => array('username' => $username, 'reason' => $failurereason)));
4343 $event->trigger();
4345 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4346 return false;
4348 } else {
4349 // We can not lockout non-existing accounts.
4352 foreach ($auths as $auth) {
4353 $authplugin = get_auth_plugin($auth);
4355 // On auth fail fall through to the next plugin.
4356 if (!$authplugin->user_login($username, $password)) {
4357 continue;
4360 // Successful authentication.
4361 if ($user->id) {
4362 // User already exists in database.
4363 if (empty($user->auth)) {
4364 // For some reason auth isn't set yet.
4365 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4366 $user->auth = $auth;
4369 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4370 // the current hash algorithm while we have access to the user's password.
4371 update_internal_user_password($user, $password);
4373 if ($authplugin->is_synchronised_with_external()) {
4374 // Update user record from external DB.
4375 $user = update_user_record_by_id($user->id);
4377 } else {
4378 // The user is authenticated but user creation may be disabled.
4379 if (!empty($CFG->authpreventaccountcreation)) {
4380 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4382 // Trigger login failed event.
4383 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4384 'reason' => $failurereason)));
4385 $event->trigger();
4387 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4388 $_SERVER['HTTP_USER_AGENT']);
4389 return false;
4390 } else {
4391 $user = create_user_record($username, $password, $auth);
4395 $authplugin->sync_roles($user);
4397 foreach ($authsenabled as $hau) {
4398 $hauth = get_auth_plugin($hau);
4399 $hauth->user_authenticated_hook($user, $username, $password);
4402 if (empty($user->id)) {
4403 $failurereason = AUTH_LOGIN_NOUSER;
4404 // Trigger login failed event.
4405 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4406 'reason' => $failurereason)));
4407 $event->trigger();
4408 return false;
4411 if (!empty($user->suspended)) {
4412 // Just in case some auth plugin suspended account.
4413 $failurereason = AUTH_LOGIN_SUSPENDED;
4414 // Trigger login failed event.
4415 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4416 'other' => array('username' => $username, 'reason' => $failurereason)));
4417 $event->trigger();
4418 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4419 return false;
4422 login_attempt_valid($user);
4423 $failurereason = AUTH_LOGIN_OK;
4424 return $user;
4427 // Failed if all the plugins have failed.
4428 if (debugging('', DEBUG_ALL)) {
4429 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4432 if ($user->id) {
4433 login_attempt_failed($user);
4434 $failurereason = AUTH_LOGIN_FAILED;
4435 // Trigger login failed event.
4436 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4437 'other' => array('username' => $username, 'reason' => $failurereason)));
4438 $event->trigger();
4439 } else {
4440 $failurereason = AUTH_LOGIN_NOUSER;
4441 // Trigger login failed event.
4442 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4443 'reason' => $failurereason)));
4444 $event->trigger();
4447 return false;
4451 * Call to complete the user login process after authenticate_user_login()
4452 * has succeeded. It will setup the $USER variable and other required bits
4453 * and pieces.
4455 * NOTE:
4456 * - It will NOT log anything -- up to the caller to decide what to log.
4457 * - this function does not set any cookies any more!
4459 * @param stdClass $user
4460 * @return stdClass A {@link $USER} object - BC only, do not use
4462 function complete_user_login($user) {
4463 global $CFG, $DB, $USER, $SESSION;
4465 \core\session\manager::login_user($user);
4467 // Reload preferences from DB.
4468 unset($USER->preference);
4469 check_user_preferences_loaded($USER);
4471 // Update login times.
4472 update_user_login_times();
4474 // Extra session prefs init.
4475 set_login_session_preferences();
4477 // Trigger login event.
4478 $event = \core\event\user_loggedin::create(
4479 array(
4480 'userid' => $USER->id,
4481 'objectid' => $USER->id,
4482 'other' => array('username' => $USER->username),
4485 $event->trigger();
4487 // Queue migrating the messaging data, if we need to.
4488 if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4489 // Check if there are any legacy messages to migrate.
4490 if (\core_message\helper::legacy_messages_exist($USER->id)) {
4491 \core_message\task\migrate_message_data::queue_task($USER->id);
4492 } else {
4493 set_user_preference('core_message_migrate_data', true, $USER->id);
4497 if (isguestuser()) {
4498 // No need to continue when user is THE guest.
4499 return $USER;
4502 if (CLI_SCRIPT) {
4503 // We can redirect to password change URL only in browser.
4504 return $USER;
4507 // Select password change url.
4508 $userauth = get_auth_plugin($USER->auth);
4510 // Check whether the user should be changing password.
4511 if (get_user_preferences('auth_forcepasswordchange', false)) {
4512 if ($userauth->can_change_password()) {
4513 if ($changeurl = $userauth->change_password_url()) {
4514 redirect($changeurl);
4515 } else {
4516 require_once($CFG->dirroot . '/login/lib.php');
4517 $SESSION->wantsurl = core_login_get_return_url();
4518 redirect($CFG->wwwroot.'/login/change_password.php');
4520 } else {
4521 print_error('nopasswordchangeforced', 'auth');
4524 return $USER;
4528 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4530 * @param string $password String to check.
4531 * @return boolean True if the $password matches the format of an md5 sum.
4533 function password_is_legacy_hash($password) {
4534 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4538 * Compare password against hash stored in user object to determine if it is valid.
4540 * If necessary it also updates the stored hash to the current format.
4542 * @param stdClass $user (Password property may be updated).
4543 * @param string $password Plain text password.
4544 * @return bool True if password is valid.
4546 function validate_internal_user_password($user, $password) {
4547 global $CFG;
4549 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4550 // Internal password is not used at all, it can not validate.
4551 return false;
4554 // If hash isn't a legacy (md5) hash, validate using the library function.
4555 if (!password_is_legacy_hash($user->password)) {
4556 return password_verify($password, $user->password);
4559 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4560 // is valid we can then update it to the new algorithm.
4562 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4563 $validated = false;
4565 if ($user->password === md5($password.$sitesalt)
4566 or $user->password === md5($password)
4567 or $user->password === md5(addslashes($password).$sitesalt)
4568 or $user->password === md5(addslashes($password))) {
4569 // Note: we are intentionally using the addslashes() here because we
4570 // need to accept old password hashes of passwords with magic quotes.
4571 $validated = true;
4573 } else {
4574 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4575 $alt = 'passwordsaltalt'.$i;
4576 if (!empty($CFG->$alt)) {
4577 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4578 $validated = true;
4579 break;
4585 if ($validated) {
4586 // If the password matches the existing md5 hash, update to the
4587 // current hash algorithm while we have access to the user's password.
4588 update_internal_user_password($user, $password);
4591 return $validated;
4595 * Calculate hash for a plain text password.
4597 * @param string $password Plain text password to be hashed.
4598 * @param bool $fasthash If true, use a low cost factor when generating the hash
4599 * This is much faster to generate but makes the hash
4600 * less secure. It is used when lots of hashes need to
4601 * be generated quickly.
4602 * @return string The hashed password.
4604 * @throws moodle_exception If a problem occurs while generating the hash.
4606 function hash_internal_user_password($password, $fasthash = false) {
4607 global $CFG;
4609 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4610 $options = ($fasthash) ? array('cost' => 4) : array();
4612 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4614 if ($generatedhash === false || $generatedhash === null) {
4615 throw new moodle_exception('Failed to generate password hash.');
4618 return $generatedhash;
4622 * Update password hash in user object (if necessary).
4624 * The password is updated if:
4625 * 1. The password has changed (the hash of $user->password is different
4626 * to the hash of $password).
4627 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4628 * md5 algorithm).
4630 * Updating the password will modify the $user object and the database
4631 * record to use the current hashing algorithm.
4632 * It will remove Web Services user tokens too.
4634 * @param stdClass $user User object (password property may be updated).
4635 * @param string $password Plain text password.
4636 * @param bool $fasthash If true, use a low cost factor when generating the hash
4637 * This is much faster to generate but makes the hash
4638 * less secure. It is used when lots of hashes need to
4639 * be generated quickly.
4640 * @return bool Always returns true.
4642 function update_internal_user_password($user, $password, $fasthash = false) {
4643 global $CFG, $DB;
4645 // Figure out what the hashed password should be.
4646 if (!isset($user->auth)) {
4647 debugging('User record in update_internal_user_password() must include field auth',
4648 DEBUG_DEVELOPER);
4649 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4651 $authplugin = get_auth_plugin($user->auth);
4652 if ($authplugin->prevent_local_passwords()) {
4653 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4654 } else {
4655 $hashedpassword = hash_internal_user_password($password, $fasthash);
4658 $algorithmchanged = false;
4660 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4661 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4662 $passwordchanged = ($user->password !== $hashedpassword);
4664 } else if (isset($user->password)) {
4665 // If verification fails then it means the password has changed.
4666 $passwordchanged = !password_verify($password, $user->password);
4667 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4668 } else {
4669 // While creating new user, password in unset in $user object, to avoid
4670 // saving it with user_create()
4671 $passwordchanged = true;
4674 if ($passwordchanged || $algorithmchanged) {
4675 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4676 $user->password = $hashedpassword;
4678 // Trigger event.
4679 $user = $DB->get_record('user', array('id' => $user->id));
4680 \core\event\user_password_updated::create_from_user($user)->trigger();
4682 // Remove WS user tokens.
4683 if (!empty($CFG->passwordchangetokendeletion)) {
4684 require_once($CFG->dirroot.'/webservice/lib.php');
4685 webservice::delete_user_ws_tokens($user->id);
4689 return true;
4693 * Get a complete user record, which includes all the info in the user record.
4695 * Intended for setting as $USER session variable
4697 * @param string $field The user field to be checked for a given value.
4698 * @param string $value The value to match for $field.
4699 * @param int $mnethostid
4700 * @return mixed False, or A {@link $USER} object.
4702 function get_complete_user_data($field, $value, $mnethostid = null) {
4703 global $CFG, $DB;
4705 if (!$field || !$value) {
4706 return false;
4709 // Build the WHERE clause for an SQL query.
4710 $params = array('fieldval' => $value);
4711 $constraints = "$field = :fieldval AND deleted <> 1";
4713 // If we are loading user data based on anything other than id,
4714 // we must also restrict our search based on mnet host.
4715 if ($field != 'id') {
4716 if (empty($mnethostid)) {
4717 // If empty, we restrict to local users.
4718 $mnethostid = $CFG->mnet_localhost_id;
4721 if (!empty($mnethostid)) {
4722 $params['mnethostid'] = $mnethostid;
4723 $constraints .= " AND mnethostid = :mnethostid";
4726 // Get all the basic user data.
4727 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4728 return false;
4731 // Get various settings and preferences.
4733 // Preload preference cache.
4734 check_user_preferences_loaded($user);
4736 // Load course enrolment related stuff.
4737 $user->lastcourseaccess = array(); // During last session.
4738 $user->currentcourseaccess = array(); // During current session.
4739 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4740 foreach ($lastaccesses as $lastaccess) {
4741 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4745 $sql = "SELECT g.id, g.courseid
4746 FROM {groups} g, {groups_members} gm
4747 WHERE gm.groupid=g.id AND gm.userid=?";
4749 // This is a special hack to speedup calendar display.
4750 $user->groupmember = array();
4751 if (!isguestuser($user)) {
4752 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4753 foreach ($groups as $group) {
4754 if (!array_key_exists($group->courseid, $user->groupmember)) {
4755 $user->groupmember[$group->courseid] = array();
4757 $user->groupmember[$group->courseid][$group->id] = $group->id;
4762 // Add cohort theme.
4763 if (!empty($CFG->allowcohortthemes)) {
4764 require_once($CFG->dirroot . '/cohort/lib.php');
4765 if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4766 $user->cohorttheme = $cohorttheme;
4770 // Add the custom profile fields to the user record.
4771 $user->profile = array();
4772 if (!isguestuser($user)) {
4773 require_once($CFG->dirroot.'/user/profile/lib.php');
4774 profile_load_custom_fields($user);
4777 // Rewrite some variables if necessary.
4778 if (!empty($user->description)) {
4779 // No need to cart all of it around.
4780 $user->description = true;
4782 if (isguestuser($user)) {
4783 // Guest language always same as site.
4784 $user->lang = $CFG->lang;
4785 // Name always in current language.
4786 $user->firstname = get_string('guestuser');
4787 $user->lastname = ' ';
4790 return $user;
4794 * Validate a password against the configured password policy
4796 * @param string $password the password to be checked against the password policy
4797 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4798 * @return bool true if the password is valid according to the policy. false otherwise.
4800 function check_password_policy($password, &$errmsg) {
4801 global $CFG;
4803 if (!empty($CFG->passwordpolicy)) {
4804 $errmsg = '';
4805 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4806 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4808 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4809 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4811 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4812 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4814 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4815 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4817 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4818 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4820 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4821 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4825 // Fire any additional password policy functions from plugins.
4826 // Plugin functions should output an error message string or empty string for success.
4827 $pluginsfunction = get_plugins_with_function('check_password_policy');
4828 foreach ($pluginsfunction as $plugintype => $plugins) {
4829 foreach ($plugins as $pluginfunction) {
4830 $pluginerr = $pluginfunction($password);
4831 if ($pluginerr) {
4832 $errmsg .= '<div>'. $pluginerr .'</div>';
4837 if ($errmsg == '') {
4838 return true;
4839 } else {
4840 return false;
4846 * When logging in, this function is run to set certain preferences for the current SESSION.
4848 function set_login_session_preferences() {
4849 global $SESSION;
4851 $SESSION->justloggedin = true;
4853 unset($SESSION->lang);
4854 unset($SESSION->forcelang);
4855 unset($SESSION->load_navigation_admin);
4860 * Delete a course, including all related data from the database, and any associated files.
4862 * @param mixed $courseorid The id of the course or course object to delete.
4863 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4864 * @return bool true if all the removals succeeded. false if there were any failures. If this
4865 * method returns false, some of the removals will probably have succeeded, and others
4866 * failed, but you have no way of knowing which.
4868 function delete_course($courseorid, $showfeedback = true) {
4869 global $DB;
4871 if (is_object($courseorid)) {
4872 $courseid = $courseorid->id;
4873 $course = $courseorid;
4874 } else {
4875 $courseid = $courseorid;
4876 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4877 return false;
4880 $context = context_course::instance($courseid);
4882 // Frontpage course can not be deleted!!
4883 if ($courseid == SITEID) {
4884 return false;
4887 // Allow plugins to use this course before we completely delete it.
4888 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
4889 foreach ($pluginsfunction as $plugintype => $plugins) {
4890 foreach ($plugins as $pluginfunction) {
4891 $pluginfunction($course);
4896 // Make the course completely empty.
4897 remove_course_contents($courseid, $showfeedback);
4899 // Delete the course and related context instance.
4900 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4902 $DB->delete_records("course", array("id" => $courseid));
4903 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4905 // Reset all course related caches here.
4906 if (class_exists('format_base', false)) {
4907 format_base::reset_course_cache($courseid);
4910 // Trigger a course deleted event.
4911 $event = \core\event\course_deleted::create(array(
4912 'objectid' => $course->id,
4913 'context' => $context,
4914 'other' => array(
4915 'shortname' => $course->shortname,
4916 'fullname' => $course->fullname,
4917 'idnumber' => $course->idnumber
4920 $event->add_record_snapshot('course', $course);
4921 $event->trigger();
4923 return true;
4927 * Clear a course out completely, deleting all content but don't delete the course itself.
4929 * This function does not verify any permissions.
4931 * Please note this function also deletes all user enrolments,
4932 * enrolment instances and role assignments by default.
4934 * $options:
4935 * - 'keep_roles_and_enrolments' - false by default
4936 * - 'keep_groups_and_groupings' - false by default
4938 * @param int $courseid The id of the course that is being deleted
4939 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4940 * @param array $options extra options
4941 * @return bool true if all the removals succeeded. false if there were any failures. If this
4942 * method returns false, some of the removals will probably have succeeded, and others
4943 * failed, but you have no way of knowing which.
4945 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4946 global $CFG, $DB, $OUTPUT;
4948 require_once($CFG->libdir.'/badgeslib.php');
4949 require_once($CFG->libdir.'/completionlib.php');
4950 require_once($CFG->libdir.'/questionlib.php');
4951 require_once($CFG->libdir.'/gradelib.php');
4952 require_once($CFG->dirroot.'/group/lib.php');
4953 require_once($CFG->dirroot.'/comment/lib.php');
4954 require_once($CFG->dirroot.'/rating/lib.php');
4955 require_once($CFG->dirroot.'/notes/lib.php');
4957 // Handle course badges.
4958 badges_handle_course_deletion($courseid);
4960 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4961 $strdeleted = get_string('deleted').' - ';
4963 // Some crazy wishlist of stuff we should skip during purging of course content.
4964 $options = (array)$options;
4966 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
4967 $coursecontext = context_course::instance($courseid);
4968 $fs = get_file_storage();
4970 // Delete course completion information, this has to be done before grades and enrols.
4971 $cc = new completion_info($course);
4972 $cc->clear_criteria();
4973 if ($showfeedback) {
4974 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4977 // Remove all data from gradebook - this needs to be done before course modules
4978 // because while deleting this information, the system may need to reference
4979 // the course modules that own the grades.
4980 remove_course_grades($courseid, $showfeedback);
4981 remove_grade_letters($coursecontext, $showfeedback);
4983 // Delete course blocks in any all child contexts,
4984 // they may depend on modules so delete them first.
4985 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4986 foreach ($childcontexts as $childcontext) {
4987 blocks_delete_all_for_context($childcontext->id);
4989 unset($childcontexts);
4990 blocks_delete_all_for_context($coursecontext->id);
4991 if ($showfeedback) {
4992 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4995 // Get the list of all modules that are properly installed.
4996 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
4998 // Delete every instance of every module,
4999 // this has to be done before deleting of course level stuff.
5000 $locations = core_component::get_plugin_list('mod');
5001 foreach ($locations as $modname => $moddir) {
5002 if ($modname === 'NEWMODULE') {
5003 continue;
5005 if (array_key_exists($modname, $allmodules)) {
5006 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5007 FROM {".$modname."} m
5008 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5009 WHERE m.course = :courseid";
5010 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5011 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5013 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5014 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5016 if ($instances) {
5017 foreach ($instances as $cm) {
5018 if ($cm->id) {
5019 // Delete activity context questions and question categories.
5020 question_delete_activity($cm, $showfeedback);
5021 // Notify the competency subsystem.
5022 \core_competency\api::hook_course_module_deleted($cm);
5024 if (function_exists($moddelete)) {
5025 // This purges all module data in related tables, extra user prefs, settings, etc.
5026 $moddelete($cm->modinstance);
5027 } else {
5028 // NOTE: we should not allow installation of modules with missing delete support!
5029 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5030 $DB->delete_records($modname, array('id' => $cm->modinstance));
5033 if ($cm->id) {
5034 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5035 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5036 $DB->delete_records('course_modules', array('id' => $cm->id));
5040 if ($instances and $showfeedback) {
5041 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5043 } else {
5044 // Ooops, this module is not properly installed, force-delete it in the next block.
5048 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5050 // Delete completion defaults.
5051 $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5053 // Remove all data from availability and completion tables that is associated
5054 // with course-modules belonging to this course. Note this is done even if the
5055 // features are not enabled now, in case they were enabled previously.
5056 $DB->delete_records_select('course_modules_completion',
5057 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5058 array($courseid));
5060 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5061 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5062 $allmodulesbyid = array_flip($allmodules);
5063 foreach ($cms as $cm) {
5064 if (array_key_exists($cm->module, $allmodulesbyid)) {
5065 try {
5066 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5067 } catch (Exception $e) {
5068 // Ignore weird or missing table problems.
5071 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5072 $DB->delete_records('course_modules', array('id' => $cm->id));
5075 if ($showfeedback) {
5076 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5079 // Delete questions and question categories.
5080 question_delete_course($course, $showfeedback);
5081 if ($showfeedback) {
5082 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5085 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5086 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5087 foreach ($childcontexts as $childcontext) {
5088 $childcontext->delete();
5090 unset($childcontexts);
5092 // Remove all roles and enrolments by default.
5093 if (empty($options['keep_roles_and_enrolments'])) {
5094 // This hack is used in restore when deleting contents of existing course.
5095 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5096 enrol_course_delete($course);
5097 if ($showfeedback) {
5098 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5102 // Delete any groups, removing members and grouping/course links first.
5103 if (empty($options['keep_groups_and_groupings'])) {
5104 groups_delete_groupings($course->id, $showfeedback);
5105 groups_delete_groups($course->id, $showfeedback);
5108 // Filters be gone!
5109 filter_delete_all_for_context($coursecontext->id);
5111 // Notes, you shall not pass!
5112 note_delete_all($course->id);
5114 // Die comments!
5115 comment::delete_comments($coursecontext->id);
5117 // Ratings are history too.
5118 $delopt = new stdclass();
5119 $delopt->contextid = $coursecontext->id;
5120 $rm = new rating_manager();
5121 $rm->delete_ratings($delopt);
5123 // Delete course tags.
5124 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5126 // Notify the competency subsystem.
5127 \core_competency\api::hook_course_deleted($course);
5129 // Delete calendar events.
5130 $DB->delete_records('event', array('courseid' => $course->id));
5131 $fs->delete_area_files($coursecontext->id, 'calendar');
5133 // Delete all related records in other core tables that may have a courseid
5134 // This array stores the tables that need to be cleared, as
5135 // table_name => column_name that contains the course id.
5136 $tablestoclear = array(
5137 'backup_courses' => 'courseid', // Scheduled backup stuff.
5138 'user_lastaccess' => 'courseid', // User access info.
5140 foreach ($tablestoclear as $table => $col) {
5141 $DB->delete_records($table, array($col => $course->id));
5144 // Delete all course backup files.
5145 $fs->delete_area_files($coursecontext->id, 'backup');
5147 // Cleanup course record - remove links to deleted stuff.
5148 $oldcourse = new stdClass();
5149 $oldcourse->id = $course->id;
5150 $oldcourse->summary = '';
5151 $oldcourse->cacherev = 0;
5152 $oldcourse->legacyfiles = 0;
5153 if (!empty($options['keep_groups_and_groupings'])) {
5154 $oldcourse->defaultgroupingid = 0;
5156 $DB->update_record('course', $oldcourse);
5158 // Delete course sections.
5159 $DB->delete_records('course_sections', array('course' => $course->id));
5161 // Delete legacy, section and any other course files.
5162 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5164 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5165 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5166 // Easy, do not delete the context itself...
5167 $coursecontext->delete_content();
5168 } else {
5169 // Hack alert!!!!
5170 // We can not drop all context stuff because it would bork enrolments and roles,
5171 // there might be also files used by enrol plugins...
5174 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5175 // also some non-standard unsupported plugins may try to store something there.
5176 fulldelete($CFG->dataroot.'/'.$course->id);
5178 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5179 $cachemodinfo = cache::make('core', 'coursemodinfo');
5180 $cachemodinfo->delete($courseid);
5182 // Trigger a course content deleted event.
5183 $event = \core\event\course_content_deleted::create(array(
5184 'objectid' => $course->id,
5185 'context' => $coursecontext,
5186 'other' => array('shortname' => $course->shortname,
5187 'fullname' => $course->fullname,
5188 'options' => $options) // Passing this for legacy reasons.
5190 $event->add_record_snapshot('course', $course);
5191 $event->trigger();
5193 return true;
5197 * Change dates in module - used from course reset.
5199 * @param string $modname forum, assignment, etc
5200 * @param array $fields array of date fields from mod table
5201 * @param int $timeshift time difference
5202 * @param int $courseid
5203 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5204 * @return bool success
5206 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5207 global $CFG, $DB;
5208 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5210 $return = true;
5211 $params = array($timeshift, $courseid);
5212 foreach ($fields as $field) {
5213 $updatesql = "UPDATE {".$modname."}
5214 SET $field = $field + ?
5215 WHERE course=? AND $field<>0";
5216 if ($modid) {
5217 $updatesql .= ' AND id=?';
5218 $params[] = $modid;
5220 $return = $DB->execute($updatesql, $params) && $return;
5223 return $return;
5227 * This function will empty a course of user data.
5228 * It will retain the activities and the structure of the course.
5230 * @param object $data an object containing all the settings including courseid (without magic quotes)
5231 * @return array status array of array component, item, error
5233 function reset_course_userdata($data) {
5234 global $CFG, $DB;
5235 require_once($CFG->libdir.'/gradelib.php');
5236 require_once($CFG->libdir.'/completionlib.php');
5237 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5238 require_once($CFG->dirroot.'/group/lib.php');
5240 $data->courseid = $data->id;
5241 $context = context_course::instance($data->courseid);
5243 $eventparams = array(
5244 'context' => $context,
5245 'courseid' => $data->id,
5246 'other' => array(
5247 'reset_options' => (array) $data
5250 $event = \core\event\course_reset_started::create($eventparams);
5251 $event->trigger();
5253 // Calculate the time shift of dates.
5254 if (!empty($data->reset_start_date)) {
5255 // Time part of course startdate should be zero.
5256 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5257 } else {
5258 $data->timeshift = 0;
5261 // Result array: component, item, error.
5262 $status = array();
5264 // Start the resetting.
5265 $componentstr = get_string('general');
5267 // Move the course start time.
5268 if (!empty($data->reset_start_date) and $data->timeshift) {
5269 // Change course start data.
5270 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5271 // Update all course and group events - do not move activity events.
5272 $updatesql = "UPDATE {event}
5273 SET timestart = timestart + ?
5274 WHERE courseid=? AND instance=0";
5275 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5277 // Update any date activity restrictions.
5278 if ($CFG->enableavailability) {
5279 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5282 // Update completion expected dates.
5283 if ($CFG->enablecompletion) {
5284 $modinfo = get_fast_modinfo($data->courseid);
5285 $changed = false;
5286 foreach ($modinfo->get_cms() as $cm) {
5287 if ($cm->completion && !empty($cm->completionexpected)) {
5288 $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5289 array('id' => $cm->id));
5290 $changed = true;
5294 // Clear course cache if changes made.
5295 if ($changed) {
5296 rebuild_course_cache($data->courseid, true);
5299 // Update course date completion criteria.
5300 \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5303 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5306 if (!empty($data->reset_end_date)) {
5307 // If the user set a end date value respect it.
5308 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5309 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5310 // If there is a time shift apply it to the end date as well.
5311 $enddate = $data->reset_end_date_old + $data->timeshift;
5312 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5315 if (!empty($data->reset_events)) {
5316 $DB->delete_records('event', array('courseid' => $data->courseid));
5317 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5320 if (!empty($data->reset_notes)) {
5321 require_once($CFG->dirroot.'/notes/lib.php');
5322 note_delete_all($data->courseid);
5323 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5326 if (!empty($data->delete_blog_associations)) {
5327 require_once($CFG->dirroot.'/blog/lib.php');
5328 blog_remove_associations_for_course($data->courseid);
5329 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5332 if (!empty($data->reset_completion)) {
5333 // Delete course and activity completion information.
5334 $course = $DB->get_record('course', array('id' => $data->courseid));
5335 $cc = new completion_info($course);
5336 $cc->delete_all_completion_data();
5337 $status[] = array('component' => $componentstr,
5338 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5341 if (!empty($data->reset_competency_ratings)) {
5342 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5343 $status[] = array('component' => $componentstr,
5344 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5347 $componentstr = get_string('roles');
5349 if (!empty($data->reset_roles_overrides)) {
5350 $children = $context->get_child_contexts();
5351 foreach ($children as $child) {
5352 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5354 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5355 // Force refresh for logged in users.
5356 $context->mark_dirty();
5357 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5360 if (!empty($data->reset_roles_local)) {
5361 $children = $context->get_child_contexts();
5362 foreach ($children as $child) {
5363 role_unassign_all(array('contextid' => $child->id));
5365 // Force refresh for logged in users.
5366 $context->mark_dirty();
5367 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5370 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5371 $data->unenrolled = array();
5372 if (!empty($data->unenrol_users)) {
5373 $plugins = enrol_get_plugins(true);
5374 $instances = enrol_get_instances($data->courseid, true);
5375 foreach ($instances as $key => $instance) {
5376 if (!isset($plugins[$instance->enrol])) {
5377 unset($instances[$key]);
5378 continue;
5382 foreach ($data->unenrol_users as $withroleid) {
5383 if ($withroleid) {
5384 $sql = "SELECT ue.*
5385 FROM {user_enrolments} ue
5386 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5387 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5388 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5389 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5391 } else {
5392 // Without any role assigned at course context.
5393 $sql = "SELECT ue.*
5394 FROM {user_enrolments} ue
5395 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5396 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5397 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5398 WHERE ra.id IS null";
5399 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5402 $rs = $DB->get_recordset_sql($sql, $params);
5403 foreach ($rs as $ue) {
5404 if (!isset($instances[$ue->enrolid])) {
5405 continue;
5407 $instance = $instances[$ue->enrolid];
5408 $plugin = $plugins[$instance->enrol];
5409 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5410 continue;
5413 $plugin->unenrol_user($instance, $ue->userid);
5414 $data->unenrolled[$ue->userid] = $ue->userid;
5416 $rs->close();
5419 if (!empty($data->unenrolled)) {
5420 $status[] = array(
5421 'component' => $componentstr,
5422 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5423 'error' => false
5427 $componentstr = get_string('groups');
5429 // Remove all group members.
5430 if (!empty($data->reset_groups_members)) {
5431 groups_delete_group_members($data->courseid);
5432 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5435 // Remove all groups.
5436 if (!empty($data->reset_groups_remove)) {
5437 groups_delete_groups($data->courseid, false);
5438 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5441 // Remove all grouping members.
5442 if (!empty($data->reset_groupings_members)) {
5443 groups_delete_groupings_groups($data->courseid, false);
5444 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5447 // Remove all groupings.
5448 if (!empty($data->reset_groupings_remove)) {
5449 groups_delete_groupings($data->courseid, false);
5450 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5453 // Look in every instance of every module for data to delete.
5454 $unsupportedmods = array();
5455 if ($allmods = $DB->get_records('modules') ) {
5456 foreach ($allmods as $mod) {
5457 $modname = $mod->name;
5458 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5459 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5460 if (file_exists($modfile)) {
5461 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5462 continue; // Skip mods with no instances.
5464 include_once($modfile);
5465 if (function_exists($moddeleteuserdata)) {
5466 $modstatus = $moddeleteuserdata($data);
5467 if (is_array($modstatus)) {
5468 $status = array_merge($status, $modstatus);
5469 } else {
5470 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5472 } else {
5473 $unsupportedmods[] = $mod;
5475 } else {
5476 debugging('Missing lib.php in '.$modname.' module!');
5478 // Update calendar events for all modules.
5479 course_module_bulk_update_calendar_events($modname, $data->courseid);
5483 // Mention unsupported mods.
5484 if (!empty($unsupportedmods)) {
5485 foreach ($unsupportedmods as $mod) {
5486 $status[] = array(
5487 'component' => get_string('modulenameplural', $mod->name),
5488 'item' => '',
5489 'error' => get_string('resetnotimplemented')
5494 $componentstr = get_string('gradebook', 'grades');
5495 // Reset gradebook,.
5496 if (!empty($data->reset_gradebook_items)) {
5497 remove_course_grades($data->courseid, false);
5498 grade_grab_course_grades($data->courseid);
5499 grade_regrade_final_grades($data->courseid);
5500 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5502 } else if (!empty($data->reset_gradebook_grades)) {
5503 grade_course_reset($data->courseid);
5504 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5506 // Reset comments.
5507 if (!empty($data->reset_comments)) {
5508 require_once($CFG->dirroot.'/comment/lib.php');
5509 comment::reset_course_page_comments($context);
5512 $event = \core\event\course_reset_ended::create($eventparams);
5513 $event->trigger();
5515 return $status;
5519 * Generate an email processing address.
5521 * @param int $modid
5522 * @param string $modargs
5523 * @return string Returns email processing address
5525 function generate_email_processing_address($modid, $modargs) {
5526 global $CFG;
5528 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5529 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5535 * @todo Finish documenting this function
5537 * @param string $modargs
5538 * @param string $body Currently unused
5540 function moodle_process_email($modargs, $body) {
5541 global $DB;
5543 // The first char should be an unencoded letter. We'll take this as an action.
5544 switch ($modargs{0}) {
5545 case 'B': { // Bounce.
5546 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5547 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5548 // Check the half md5 of their email.
5549 $md5check = substr(md5($user->email), 0, 16);
5550 if ($md5check == substr($modargs, -16)) {
5551 set_bounce_count($user);
5553 // Else maybe they've already changed it?
5556 break;
5557 // Maybe more later?
5561 // CORRESPONDENCE.
5564 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5566 * @param string $action 'get', 'buffer', 'close' or 'flush'
5567 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5569 function get_mailer($action='get') {
5570 global $CFG;
5572 /** @var moodle_phpmailer $mailer */
5573 static $mailer = null;
5574 static $counter = 0;
5576 if (!isset($CFG->smtpmaxbulk)) {
5577 $CFG->smtpmaxbulk = 1;
5580 if ($action == 'get') {
5581 $prevkeepalive = false;
5583 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5584 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5585 $counter++;
5586 // Reset the mailer.
5587 $mailer->Priority = 3;
5588 $mailer->CharSet = 'UTF-8'; // Our default.
5589 $mailer->ContentType = "text/plain";
5590 $mailer->Encoding = "8bit";
5591 $mailer->From = "root@localhost";
5592 $mailer->FromName = "Root User";
5593 $mailer->Sender = "";
5594 $mailer->Subject = "";
5595 $mailer->Body = "";
5596 $mailer->AltBody = "";
5597 $mailer->ConfirmReadingTo = "";
5599 $mailer->clearAllRecipients();
5600 $mailer->clearReplyTos();
5601 $mailer->clearAttachments();
5602 $mailer->clearCustomHeaders();
5603 return $mailer;
5606 $prevkeepalive = $mailer->SMTPKeepAlive;
5607 get_mailer('flush');
5610 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5611 $mailer = new moodle_phpmailer();
5613 $counter = 1;
5615 if ($CFG->smtphosts == 'qmail') {
5616 // Use Qmail system.
5617 $mailer->isQmail();
5619 } else if (empty($CFG->smtphosts)) {
5620 // Use PHP mail() = sendmail.
5621 $mailer->isMail();
5623 } else {
5624 // Use SMTP directly.
5625 $mailer->isSMTP();
5626 if (!empty($CFG->debugsmtp)) {
5627 $mailer->SMTPDebug = 3;
5629 // Specify main and backup servers.
5630 $mailer->Host = $CFG->smtphosts;
5631 // Specify secure connection protocol.
5632 $mailer->SMTPSecure = $CFG->smtpsecure;
5633 // Use previous keepalive.
5634 $mailer->SMTPKeepAlive = $prevkeepalive;
5636 if ($CFG->smtpuser) {
5637 // Use SMTP authentication.
5638 $mailer->SMTPAuth = true;
5639 $mailer->Username = $CFG->smtpuser;
5640 $mailer->Password = $CFG->smtppass;
5644 return $mailer;
5647 $nothing = null;
5649 // Keep smtp session open after sending.
5650 if ($action == 'buffer') {
5651 if (!empty($CFG->smtpmaxbulk)) {
5652 get_mailer('flush');
5653 $m = get_mailer();
5654 if ($m->Mailer == 'smtp') {
5655 $m->SMTPKeepAlive = true;
5658 return $nothing;
5661 // Close smtp session, but continue buffering.
5662 if ($action == 'flush') {
5663 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5664 if (!empty($mailer->SMTPDebug)) {
5665 echo '<pre>'."\n";
5667 $mailer->SmtpClose();
5668 if (!empty($mailer->SMTPDebug)) {
5669 echo '</pre>';
5672 return $nothing;
5675 // Close smtp session, do not buffer anymore.
5676 if ($action == 'close') {
5677 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5678 get_mailer('flush');
5679 $mailer->SMTPKeepAlive = false;
5681 $mailer = null; // Better force new instance.
5682 return $nothing;
5687 * A helper function to test for email diversion
5689 * @param string $email
5690 * @return bool Returns true if the email should be diverted
5692 function email_should_be_diverted($email) {
5693 global $CFG;
5695 if (empty($CFG->divertallemailsto)) {
5696 return false;
5699 if (empty($CFG->divertallemailsexcept)) {
5700 return true;
5703 $patterns = array_map('trim', explode(',', $CFG->divertallemailsexcept));
5704 foreach ($patterns as $pattern) {
5705 if (preg_match("/$pattern/", $email)) {
5706 return false;
5710 return true;
5714 * Generate a unique email Message-ID using the moodle domain and install path
5716 * @param string $localpart An optional unique message id prefix.
5717 * @return string The formatted ID ready for appending to the email headers.
5719 function generate_email_messageid($localpart = null) {
5720 global $CFG;
5722 $urlinfo = parse_url($CFG->wwwroot);
5723 $base = '@' . $urlinfo['host'];
5725 // If multiple moodles are on the same domain we want to tell them
5726 // apart so we add the install path to the local part. This means
5727 // that the id local part should never contain a / character so
5728 // we can correctly parse the id to reassemble the wwwroot.
5729 if (isset($urlinfo['path'])) {
5730 $base = $urlinfo['path'] . $base;
5733 if (empty($localpart)) {
5734 $localpart = uniqid('', true);
5737 // Because we may have an option /installpath suffix to the local part
5738 // of the id we need to escape any / chars which are in the $localpart.
5739 $localpart = str_replace('/', '%2F', $localpart);
5741 return '<' . $localpart . $base . '>';
5745 * Send an email to a specified user
5747 * @param stdClass $user A {@link $USER} object
5748 * @param stdClass $from A {@link $USER} object
5749 * @param string $subject plain text subject line of the email
5750 * @param string $messagetext plain text version of the message
5751 * @param string $messagehtml complete html version of the message (optional)
5752 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5753 * @param string $attachname the name of the file (extension indicates MIME)
5754 * @param bool $usetrueaddress determines whether $from email address should
5755 * be sent out. Will be overruled by user profile setting for maildisplay
5756 * @param string $replyto Email address to reply to
5757 * @param string $replytoname Name of reply to recipient
5758 * @param int $wordwrapwidth custom word wrap width, default 79
5759 * @return bool Returns true if mail was sent OK and false if there was an error.
5761 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5762 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5764 global $CFG, $PAGE, $SITE;
5766 if (empty($user) or empty($user->id)) {
5767 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5768 return false;
5771 if (empty($user->email)) {
5772 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5773 return false;
5776 if (!empty($user->deleted)) {
5777 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5778 return false;
5781 if (defined('BEHAT_SITE_RUNNING')) {
5782 // Fake email sending in behat.
5783 return true;
5786 if (!empty($CFG->noemailever)) {
5787 // Hidden setting for development sites, set in config.php if needed.
5788 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5789 return true;
5792 if (email_should_be_diverted($user->email)) {
5793 $subject = "[DIVERTED {$user->email}] $subject";
5794 $user = clone($user);
5795 $user->email = $CFG->divertallemailsto;
5798 // Skip mail to suspended users.
5799 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5800 return true;
5803 if (!validate_email($user->email)) {
5804 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5805 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5806 return false;
5809 if (over_bounce_threshold($user)) {
5810 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5811 return false;
5814 // TLD .invalid is specifically reserved for invalid domain names.
5815 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5816 if (substr($user->email, -8) == '.invalid') {
5817 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5818 return true; // This is not an error.
5821 // If the user is a remote mnet user, parse the email text for URL to the
5822 // wwwroot and modify the url to direct the user's browser to login at their
5823 // home site (identity provider - idp) before hitting the link itself.
5824 if (is_mnet_remote_user($user)) {
5825 require_once($CFG->dirroot.'/mnet/lib.php');
5827 $jumpurl = mnet_get_idp_jump_url($user);
5828 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5830 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5831 $callback,
5832 $messagetext);
5833 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5834 $callback,
5835 $messagehtml);
5837 $mail = get_mailer();
5839 if (!empty($mail->SMTPDebug)) {
5840 echo '<pre>' . "\n";
5843 $temprecipients = array();
5844 $tempreplyto = array();
5846 // Make sure that we fall back onto some reasonable no-reply address.
5847 $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
5848 $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
5850 if (!validate_email($noreplyaddress)) {
5851 debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
5852 $noreplyaddress = $noreplyaddressdefault;
5855 // Make up an email address for handling bounces.
5856 if (!empty($CFG->handlebounces)) {
5857 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5858 $mail->Sender = generate_email_processing_address(0, $modargs);
5859 } else {
5860 $mail->Sender = $noreplyaddress;
5863 // Make sure that the explicit replyto is valid, fall back to the implicit one.
5864 if (!empty($replyto) && !validate_email($replyto)) {
5865 debugging('email_to_user: Invalid replyto-email '.s($replyto));
5866 $replyto = $noreplyaddress;
5869 if (is_string($from)) { // So we can pass whatever we want if there is need.
5870 $mail->From = $noreplyaddress;
5871 $mail->FromName = $from;
5872 // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
5873 // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
5874 // in a course with the sender.
5875 } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
5876 if (!validate_email($from->email)) {
5877 debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
5878 // Better not to use $noreplyaddress in this case.
5879 return false;
5881 $mail->From = $from->email;
5882 $fromdetails = new stdClass();
5883 $fromdetails->name = fullname($from);
5884 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5885 $fromdetails->siteshortname = format_string($SITE->shortname);
5886 $fromstring = $fromdetails->name;
5887 if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
5888 $fromstring = get_string('emailvia', 'core', $fromdetails);
5890 $mail->FromName = $fromstring;
5891 if (empty($replyto)) {
5892 $tempreplyto[] = array($from->email, fullname($from));
5894 } else {
5895 $mail->From = $noreplyaddress;
5896 $fromdetails = new stdClass();
5897 $fromdetails->name = fullname($from);
5898 $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5899 $fromdetails->siteshortname = format_string($SITE->shortname);
5900 $fromstring = $fromdetails->name;
5901 if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
5902 $fromstring = get_string('emailvia', 'core', $fromdetails);
5904 $mail->FromName = $fromstring;
5905 if (empty($replyto)) {
5906 $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
5910 if (!empty($replyto)) {
5911 $tempreplyto[] = array($replyto, $replytoname);
5914 $temprecipients[] = array($user->email, fullname($user));
5916 // Set word wrap.
5917 $mail->WordWrap = $wordwrapwidth;
5919 if (!empty($from->customheaders)) {
5920 // Add custom headers.
5921 if (is_array($from->customheaders)) {
5922 foreach ($from->customheaders as $customheader) {
5923 $mail->addCustomHeader($customheader);
5925 } else {
5926 $mail->addCustomHeader($from->customheaders);
5930 // If the X-PHP-Originating-Script email header is on then also add an additional
5931 // header with details of where exactly in moodle the email was triggered from,
5932 // either a call to message_send() or to email_to_user().
5933 if (ini_get('mail.add_x_header')) {
5935 $stack = debug_backtrace(false);
5936 $origin = $stack[0];
5938 foreach ($stack as $depth => $call) {
5939 if ($call['function'] == 'message_send') {
5940 $origin = $call;
5944 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
5945 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
5946 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
5949 if (!empty($from->priority)) {
5950 $mail->Priority = $from->priority;
5953 $renderer = $PAGE->get_renderer('core');
5954 $context = array(
5955 'sitefullname' => $SITE->fullname,
5956 'siteshortname' => $SITE->shortname,
5957 'sitewwwroot' => $CFG->wwwroot,
5958 'subject' => $subject,
5959 'to' => $user->email,
5960 'toname' => fullname($user),
5961 'from' => $mail->From,
5962 'fromname' => $mail->FromName,
5964 if (!empty($tempreplyto[0])) {
5965 $context['replyto'] = $tempreplyto[0][0];
5966 $context['replytoname'] = $tempreplyto[0][1];
5968 if ($user->id > 0) {
5969 $context['touserid'] = $user->id;
5970 $context['tousername'] = $user->username;
5973 if (!empty($user->mailformat) && $user->mailformat == 1) {
5974 // Only process html templates if the user preferences allow html email.
5976 if ($messagehtml) {
5977 // If html has been given then pass it through the template.
5978 $context['body'] = $messagehtml;
5979 $messagehtml = $renderer->render_from_template('core/email_html', $context);
5981 } else {
5982 // If no html has been given, BUT there is an html wrapping template then
5983 // auto convert the text to html and then wrap it.
5984 $autohtml = trim(text_to_html($messagetext));
5985 $context['body'] = $autohtml;
5986 $temphtml = $renderer->render_from_template('core/email_html', $context);
5987 if ($autohtml != $temphtml) {
5988 $messagehtml = $temphtml;
5993 $context['body'] = $messagetext;
5994 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
5995 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
5996 $messagetext = $renderer->render_from_template('core/email_text', $context);
5998 // Autogenerate a MessageID if it's missing.
5999 if (empty($mail->MessageID)) {
6000 $mail->MessageID = generate_email_messageid();
6003 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6004 // Don't ever send HTML to users who don't want it.
6005 $mail->isHTML(true);
6006 $mail->Encoding = 'quoted-printable';
6007 $mail->Body = $messagehtml;
6008 $mail->AltBody = "\n$messagetext\n";
6009 } else {
6010 $mail->IsHTML(false);
6011 $mail->Body = "\n$messagetext\n";
6014 if ($attachment && $attachname) {
6015 if (preg_match( "~\\.\\.~" , $attachment )) {
6016 // Security check for ".." in dir path.
6017 $supportuser = core_user::get_support_user();
6018 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6019 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6020 } else {
6021 require_once($CFG->libdir.'/filelib.php');
6022 $mimetype = mimeinfo('type', $attachname);
6024 $attachmentpath = $attachment;
6026 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6027 $attachpath = str_replace('\\', '/', $attachmentpath);
6028 // Make sure both variables are normalised before comparing.
6029 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
6031 // If the attachment is a full path to a file in the tempdir, use it as is,
6032 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6033 if (strpos($attachpath, $temppath) !== 0) {
6034 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
6037 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
6041 // Check if the email should be sent in an other charset then the default UTF-8.
6042 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6044 // Use the defined site mail charset or eventually the one preferred by the recipient.
6045 $charset = $CFG->sitemailcharset;
6046 if (!empty($CFG->allowusermailcharset)) {
6047 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6048 $charset = $useremailcharset;
6052 // Convert all the necessary strings if the charset is supported.
6053 $charsets = get_list_of_charsets();
6054 unset($charsets['UTF-8']);
6055 if (in_array($charset, $charsets)) {
6056 $mail->CharSet = $charset;
6057 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6058 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6059 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6060 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6062 foreach ($temprecipients as $key => $values) {
6063 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6065 foreach ($tempreplyto as $key => $values) {
6066 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6071 foreach ($temprecipients as $values) {
6072 $mail->addAddress($values[0], $values[1]);
6074 foreach ($tempreplyto as $values) {
6075 $mail->addReplyTo($values[0], $values[1]);
6078 if ($mail->send()) {
6079 set_send_count($user);
6080 if (!empty($mail->SMTPDebug)) {
6081 echo '</pre>';
6083 return true;
6084 } else {
6085 // Trigger event for failing to send email.
6086 $event = \core\event\email_failed::create(array(
6087 'context' => context_system::instance(),
6088 'userid' => $from->id,
6089 'relateduserid' => $user->id,
6090 'other' => array(
6091 'subject' => $subject,
6092 'message' => $messagetext,
6093 'errorinfo' => $mail->ErrorInfo
6096 $event->trigger();
6097 if (CLI_SCRIPT) {
6098 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6100 if (!empty($mail->SMTPDebug)) {
6101 echo '</pre>';
6103 return false;
6108 * Check to see if a user's real email address should be used for the "From" field.
6110 * @param object $from The user object for the user we are sending the email from.
6111 * @param object $user The user object that we are sending the email to.
6112 * @param array $unused No longer used.
6113 * @return bool Returns true if we can use the from user's email adress in the "From" field.
6115 function can_send_from_real_email_address($from, $user, $unused = null) {
6116 global $CFG;
6117 if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6118 return false;
6120 $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6121 // Email is in the list of allowed domains for sending email,
6122 // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6123 // in a course with the sender.
6124 if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6125 && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6126 || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6127 && enrol_get_shared_courses($user, $from, false, true)))) {
6128 return true;
6130 return false;
6134 * Generate a signoff for emails based on support settings
6136 * @return string
6138 function generate_email_signoff() {
6139 global $CFG;
6141 $signoff = "\n";
6142 if (!empty($CFG->supportname)) {
6143 $signoff .= $CFG->supportname."\n";
6145 if (!empty($CFG->supportemail)) {
6146 $signoff .= $CFG->supportemail."\n";
6148 if (!empty($CFG->supportpage)) {
6149 $signoff .= $CFG->supportpage."\n";
6151 return $signoff;
6155 * Sets specified user's password and send the new password to the user via email.
6157 * @param stdClass $user A {@link $USER} object
6158 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6159 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6161 function setnew_password_and_mail($user, $fasthash = false) {
6162 global $CFG, $DB;
6164 // We try to send the mail in language the user understands,
6165 // unfortunately the filter_string() does not support alternative langs yet
6166 // so multilang will not work properly for site->fullname.
6167 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6169 $site = get_site();
6171 $supportuser = core_user::get_support_user();
6173 $newpassword = generate_password();
6175 update_internal_user_password($user, $newpassword, $fasthash);
6177 $a = new stdClass();
6178 $a->firstname = fullname($user, true);
6179 $a->sitename = format_string($site->fullname);
6180 $a->username = $user->username;
6181 $a->newpassword = $newpassword;
6182 $a->link = $CFG->wwwroot .'/login/?lang='.$lang;
6183 $a->signoff = generate_email_signoff();
6185 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6187 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6189 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6190 return email_to_user($user, $supportuser, $subject, $message);
6195 * Resets specified user's password and send the new password to the user via email.
6197 * @param stdClass $user A {@link $USER} object
6198 * @return bool Returns true if mail was sent OK and false if there was an error.
6200 function reset_password_and_mail($user) {
6201 global $CFG;
6203 $site = get_site();
6204 $supportuser = core_user::get_support_user();
6206 $userauth = get_auth_plugin($user->auth);
6207 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6208 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6209 return false;
6212 $newpassword = generate_password();
6214 if (!$userauth->user_update_password($user, $newpassword)) {
6215 print_error("cannotsetpassword");
6218 $a = new stdClass();
6219 $a->firstname = $user->firstname;
6220 $a->lastname = $user->lastname;
6221 $a->sitename = format_string($site->fullname);
6222 $a->username = $user->username;
6223 $a->newpassword = $newpassword;
6224 $a->link = $CFG->wwwroot .'/login/change_password.php';
6225 $a->signoff = generate_email_signoff();
6227 $message = get_string('newpasswordtext', '', $a);
6229 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6231 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6233 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6234 return email_to_user($user, $supportuser, $subject, $message);
6238 * Send email to specified user with confirmation text and activation link.
6240 * @param stdClass $user A {@link $USER} object
6241 * @param string $confirmationurl user confirmation URL
6242 * @return bool Returns true if mail was sent OK and false if there was an error.
6244 function send_confirmation_email($user, $confirmationurl = null) {
6245 global $CFG;
6247 $site = get_site();
6248 $supportuser = core_user::get_support_user();
6250 $data = new stdClass();
6251 $data->firstname = fullname($user);
6252 $data->sitename = format_string($site->fullname);
6253 $data->admin = generate_email_signoff();
6255 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6257 if (empty($confirmationurl)) {
6258 $confirmationurl = '/login/confirm.php';
6261 $confirmationurl = new moodle_url($confirmationurl);
6262 // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6263 $confirmationurl->remove_params('data');
6264 $confirmationpath = $confirmationurl->out(false);
6266 // We need to custom encode the username to include trailing dots in the link.
6267 // Because of this custom encoding we can't use moodle_url directly.
6268 // Determine if a query string is present in the confirmation url.
6269 $hasquerystring = strpos($confirmationpath, '?') !== false;
6270 // Perform normal url encoding of the username first.
6271 $username = urlencode($user->username);
6272 // Prevent problems with trailing dots not being included as part of link in some mail clients.
6273 $username = str_replace('.', '%2E', $username);
6275 $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6277 $message = get_string('emailconfirmation', '', $data);
6278 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6280 $user->mailformat = 1; // Always send HTML version as well.
6282 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6283 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6287 * Sends a password change confirmation email.
6289 * @param stdClass $user A {@link $USER} object
6290 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6291 * @return bool Returns true if mail was sent OK and false if there was an error.
6293 function send_password_change_confirmation_email($user, $resetrecord) {
6294 global $CFG;
6296 $site = get_site();
6297 $supportuser = core_user::get_support_user();
6298 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6300 $data = new stdClass();
6301 $data->firstname = $user->firstname;
6302 $data->lastname = $user->lastname;
6303 $data->username = $user->username;
6304 $data->sitename = format_string($site->fullname);
6305 $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6306 $data->admin = generate_email_signoff();
6307 $data->resetminutes = $pwresetmins;
6309 $message = get_string('emailresetconfirmation', '', $data);
6310 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6312 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6313 return email_to_user($user, $supportuser, $subject, $message);
6318 * Sends an email containinginformation on how to change your password.
6320 * @param stdClass $user A {@link $USER} object
6321 * @return bool Returns true if mail was sent OK and false if there was an error.
6323 function send_password_change_info($user) {
6324 global $CFG;
6326 $site = get_site();
6327 $supportuser = core_user::get_support_user();
6328 $systemcontext = context_system::instance();
6330 $data = new stdClass();
6331 $data->firstname = $user->firstname;
6332 $data->lastname = $user->lastname;
6333 $data->username = $user->username;
6334 $data->sitename = format_string($site->fullname);
6335 $data->admin = generate_email_signoff();
6337 $userauth = get_auth_plugin($user->auth);
6339 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6340 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6341 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6342 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6343 return email_to_user($user, $supportuser, $subject, $message);
6346 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6347 // We have some external url for password changing.
6348 $data->link .= $userauth->change_password_url();
6350 } else {
6351 // No way to change password, sorry.
6352 $data->link = '';
6355 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6356 $message = get_string('emailpasswordchangeinfo', '', $data);
6357 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6358 } else {
6359 $message = get_string('emailpasswordchangeinfofail', '', $data);
6360 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6363 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6364 return email_to_user($user, $supportuser, $subject, $message);
6369 * Check that an email is allowed. It returns an error message if there was a problem.
6371 * @param string $email Content of email
6372 * @return string|false
6374 function email_is_not_allowed($email) {
6375 global $CFG;
6377 if (!empty($CFG->allowemailaddresses)) {
6378 $allowed = explode(' ', $CFG->allowemailaddresses);
6379 foreach ($allowed as $allowedpattern) {
6380 $allowedpattern = trim($allowedpattern);
6381 if (!$allowedpattern) {
6382 continue;
6384 if (strpos($allowedpattern, '.') === 0) {
6385 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6386 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6387 return false;
6390 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6391 return false;
6394 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6396 } else if (!empty($CFG->denyemailaddresses)) {
6397 $denied = explode(' ', $CFG->denyemailaddresses);
6398 foreach ($denied as $deniedpattern) {
6399 $deniedpattern = trim($deniedpattern);
6400 if (!$deniedpattern) {
6401 continue;
6403 if (strpos($deniedpattern, '.') === 0) {
6404 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6405 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6406 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6409 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6410 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6415 return false;
6418 // FILE HANDLING.
6421 * Returns local file storage instance
6423 * @return file_storage
6425 function get_file_storage($reset = false) {
6426 global $CFG;
6428 static $fs = null;
6430 if ($reset) {
6431 $fs = null;
6432 return;
6435 if ($fs) {
6436 return $fs;
6439 require_once("$CFG->libdir/filelib.php");
6441 $fs = new file_storage();
6443 return $fs;
6447 * Returns local file storage instance
6449 * @return file_browser
6451 function get_file_browser() {
6452 global $CFG;
6454 static $fb = null;
6456 if ($fb) {
6457 return $fb;
6460 require_once("$CFG->libdir/filelib.php");
6462 $fb = new file_browser();
6464 return $fb;
6468 * Returns file packer
6470 * @param string $mimetype default application/zip
6471 * @return file_packer
6473 function get_file_packer($mimetype='application/zip') {
6474 global $CFG;
6476 static $fp = array();
6478 if (isset($fp[$mimetype])) {
6479 return $fp[$mimetype];
6482 switch ($mimetype) {
6483 case 'application/zip':
6484 case 'application/vnd.moodle.profiling':
6485 $classname = 'zip_packer';
6486 break;
6488 case 'application/x-gzip' :
6489 $classname = 'tgz_packer';
6490 break;
6492 case 'application/vnd.moodle.backup':
6493 $classname = 'mbz_packer';
6494 break;
6496 default:
6497 return false;
6500 require_once("$CFG->libdir/filestorage/$classname.php");
6501 $fp[$mimetype] = new $classname();
6503 return $fp[$mimetype];
6507 * Returns current name of file on disk if it exists.
6509 * @param string $newfile File to be verified
6510 * @return string Current name of file on disk if true
6512 function valid_uploaded_file($newfile) {
6513 if (empty($newfile)) {
6514 return '';
6516 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6517 return $newfile['tmp_name'];
6518 } else {
6519 return '';
6524 * Returns the maximum size for uploading files.
6526 * There are seven possible upload limits:
6527 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6528 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6529 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6530 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6531 * 5. by the Moodle admin in $CFG->maxbytes
6532 * 6. by the teacher in the current course $course->maxbytes
6533 * 7. by the teacher for the current module, eg $assignment->maxbytes
6535 * These last two are passed to this function as arguments (in bytes).
6536 * Anything defined as 0 is ignored.
6537 * The smallest of all the non-zero numbers is returned.
6539 * @todo Finish documenting this function
6541 * @param int $sitebytes Set maximum size
6542 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6543 * @param int $modulebytes Current module ->maxbytes (in bytes)
6544 * @param bool $unused This parameter has been deprecated and is not used any more.
6545 * @return int The maximum size for uploading files.
6547 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6549 if (! $filesize = ini_get('upload_max_filesize')) {
6550 $filesize = '5M';
6552 $minimumsize = get_real_size($filesize);
6554 if ($postsize = ini_get('post_max_size')) {
6555 $postsize = get_real_size($postsize);
6556 if ($postsize < $minimumsize) {
6557 $minimumsize = $postsize;
6561 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6562 $minimumsize = $sitebytes;
6565 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6566 $minimumsize = $coursebytes;
6569 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6570 $minimumsize = $modulebytes;
6573 return $minimumsize;
6577 * Returns the maximum size for uploading files for the current user
6579 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6581 * @param context $context The context in which to check user capabilities
6582 * @param int $sitebytes Set maximum size
6583 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6584 * @param int $modulebytes Current module ->maxbytes (in bytes)
6585 * @param stdClass $user The user
6586 * @param bool $unused This parameter has been deprecated and is not used any more.
6587 * @return int The maximum size for uploading files.
6589 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6590 $unused = false) {
6591 global $USER;
6593 if (empty($user)) {
6594 $user = $USER;
6597 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6598 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6601 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6605 * Returns an array of possible sizes in local language
6607 * Related to {@link get_max_upload_file_size()} - this function returns an
6608 * array of possible sizes in an array, translated to the
6609 * local language.
6611 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6613 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6614 * with the value set to 0. This option will be the first in the list.
6616 * @uses SORT_NUMERIC
6617 * @param int $sitebytes Set maximum size
6618 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6619 * @param int $modulebytes Current module ->maxbytes (in bytes)
6620 * @param int|array $custombytes custom upload size/s which will be added to list,
6621 * Only value/s smaller then maxsize will be added to list.
6622 * @return array
6624 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6625 global $CFG;
6627 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6628 return array();
6631 if ($sitebytes == 0) {
6632 // Will get the minimum of upload_max_filesize or post_max_size.
6633 $sitebytes = get_max_upload_file_size();
6636 $filesize = array();
6637 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6638 5242880, 10485760, 20971520, 52428800, 104857600,
6639 262144000, 524288000, 786432000, 1073741824,
6640 2147483648, 4294967296, 8589934592);
6642 // If custombytes is given and is valid then add it to the list.
6643 if (is_number($custombytes) and $custombytes > 0) {
6644 $custombytes = (int)$custombytes;
6645 if (!in_array($custombytes, $sizelist)) {
6646 $sizelist[] = $custombytes;
6648 } else if (is_array($custombytes)) {
6649 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6652 // Allow maxbytes to be selected if it falls outside the above boundaries.
6653 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6654 // Note: get_real_size() is used in order to prevent problems with invalid values.
6655 $sizelist[] = get_real_size($CFG->maxbytes);
6658 foreach ($sizelist as $sizebytes) {
6659 if ($sizebytes < $maxsize && $sizebytes > 0) {
6660 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6664 $limitlevel = '';
6665 $displaysize = '';
6666 if ($modulebytes &&
6667 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6668 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6669 $limitlevel = get_string('activity', 'core');
6670 $displaysize = display_size($modulebytes);
6671 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6673 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6674 $limitlevel = get_string('course', 'core');
6675 $displaysize = display_size($coursebytes);
6676 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6678 } else if ($sitebytes) {
6679 $limitlevel = get_string('site', 'core');
6680 $displaysize = display_size($sitebytes);
6681 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6684 krsort($filesize, SORT_NUMERIC);
6685 if ($limitlevel) {
6686 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6687 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6690 return $filesize;
6694 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6696 * If excludefiles is defined, then that file/directory is ignored
6697 * If getdirs is true, then (sub)directories are included in the output
6698 * If getfiles is true, then files are included in the output
6699 * (at least one of these must be true!)
6701 * @todo Finish documenting this function. Add examples of $excludefile usage.
6703 * @param string $rootdir A given root directory to start from
6704 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6705 * @param bool $descend If true then subdirectories are recursed as well
6706 * @param bool $getdirs If true then (sub)directories are included in the output
6707 * @param bool $getfiles If true then files are included in the output
6708 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6710 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6712 $dirs = array();
6714 if (!$getdirs and !$getfiles) { // Nothing to show.
6715 return $dirs;
6718 if (!is_dir($rootdir)) { // Must be a directory.
6719 return $dirs;
6722 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6723 return $dirs;
6726 if (!is_array($excludefiles)) {
6727 $excludefiles = array($excludefiles);
6730 while (false !== ($file = readdir($dir))) {
6731 $firstchar = substr($file, 0, 1);
6732 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6733 continue;
6735 $fullfile = $rootdir .'/'. $file;
6736 if (filetype($fullfile) == 'dir') {
6737 if ($getdirs) {
6738 $dirs[] = $file;
6740 if ($descend) {
6741 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6742 foreach ($subdirs as $subdir) {
6743 $dirs[] = $file .'/'. $subdir;
6746 } else if ($getfiles) {
6747 $dirs[] = $file;
6750 closedir($dir);
6752 asort($dirs);
6754 return $dirs;
6759 * Adds up all the files in a directory and works out the size.
6761 * @param string $rootdir The directory to start from
6762 * @param string $excludefile A file to exclude when summing directory size
6763 * @return int The summed size of all files and subfiles within the root directory
6765 function get_directory_size($rootdir, $excludefile='') {
6766 global $CFG;
6768 // Do it this way if we can, it's much faster.
6769 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6770 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6771 $output = null;
6772 $return = null;
6773 exec($command, $output, $return);
6774 if (is_array($output)) {
6775 // We told it to return k.
6776 return get_real_size(intval($output[0]).'k');
6780 if (!is_dir($rootdir)) {
6781 // Must be a directory.
6782 return 0;
6785 if (!$dir = @opendir($rootdir)) {
6786 // Can't open it for some reason.
6787 return 0;
6790 $size = 0;
6792 while (false !== ($file = readdir($dir))) {
6793 $firstchar = substr($file, 0, 1);
6794 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6795 continue;
6797 $fullfile = $rootdir .'/'. $file;
6798 if (filetype($fullfile) == 'dir') {
6799 $size += get_directory_size($fullfile, $excludefile);
6800 } else {
6801 $size += filesize($fullfile);
6804 closedir($dir);
6806 return $size;
6810 * Converts bytes into display form
6812 * @static string $gb Localized string for size in gigabytes
6813 * @static string $mb Localized string for size in megabytes
6814 * @static string $kb Localized string for size in kilobytes
6815 * @static string $b Localized string for size in bytes
6816 * @param int $size The size to convert to human readable form
6817 * @return string
6819 function display_size($size) {
6821 static $gb, $mb, $kb, $b;
6823 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6824 return get_string('unlimited');
6827 if (empty($gb)) {
6828 $gb = get_string('sizegb');
6829 $mb = get_string('sizemb');
6830 $kb = get_string('sizekb');
6831 $b = get_string('sizeb');
6834 if ($size >= 1073741824) {
6835 $size = round($size / 1073741824 * 10) / 10 . $gb;
6836 } else if ($size >= 1048576) {
6837 $size = round($size / 1048576 * 10) / 10 . $mb;
6838 } else if ($size >= 1024) {
6839 $size = round($size / 1024 * 10) / 10 . $kb;
6840 } else {
6841 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6843 return $size;
6847 * Cleans a given filename by removing suspicious or troublesome characters
6849 * @see clean_param()
6850 * @param string $string file name
6851 * @return string cleaned file name
6853 function clean_filename($string) {
6854 return clean_param($string, PARAM_FILE);
6857 // STRING TRANSLATION.
6860 * Returns the code for the current language
6862 * @category string
6863 * @return string
6865 function current_language() {
6866 global $CFG, $USER, $SESSION, $COURSE;
6868 if (!empty($SESSION->forcelang)) {
6869 // Allows overriding course-forced language (useful for admins to check
6870 // issues in courses whose language they don't understand).
6871 // Also used by some code to temporarily get language-related information in a
6872 // specific language (see force_current_language()).
6873 $return = $SESSION->forcelang;
6875 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6876 // Course language can override all other settings for this page.
6877 $return = $COURSE->lang;
6879 } else if (!empty($SESSION->lang)) {
6880 // Session language can override other settings.
6881 $return = $SESSION->lang;
6883 } else if (!empty($USER->lang)) {
6884 $return = $USER->lang;
6886 } else if (isset($CFG->lang)) {
6887 $return = $CFG->lang;
6889 } else {
6890 $return = 'en';
6893 // Just in case this slipped in from somewhere by accident.
6894 $return = str_replace('_utf8', '', $return);
6896 return $return;
6900 * Returns parent language of current active language if defined
6902 * @category string
6903 * @param string $lang null means current language
6904 * @return string
6906 function get_parent_language($lang=null) {
6908 // Let's hack around the current language.
6909 if (!empty($lang)) {
6910 $oldforcelang = force_current_language($lang);
6913 $parentlang = get_string('parentlanguage', 'langconfig');
6914 if ($parentlang === 'en') {
6915 $parentlang = '';
6918 // Let's hack around the current language.
6919 if (!empty($lang)) {
6920 force_current_language($oldforcelang);
6923 return $parentlang;
6927 * Force the current language to get strings and dates localised in the given language.
6929 * After calling this function, all strings will be provided in the given language
6930 * until this function is called again, or equivalent code is run.
6932 * @param string $language
6933 * @return string previous $SESSION->forcelang value
6935 function force_current_language($language) {
6936 global $SESSION;
6937 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6938 if ($language !== $sessionforcelang) {
6939 // Seting forcelang to null or an empty string disables it's effect.
6940 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6941 $SESSION->forcelang = $language;
6942 moodle_setlocale();
6945 return $sessionforcelang;
6949 * Returns current string_manager instance.
6951 * The param $forcereload is needed for CLI installer only where the string_manager instance
6952 * must be replaced during the install.php script life time.
6954 * @category string
6955 * @param bool $forcereload shall the singleton be released and new instance created instead?
6956 * @return core_string_manager
6958 function get_string_manager($forcereload=false) {
6959 global $CFG;
6961 static $singleton = null;
6963 if ($forcereload) {
6964 $singleton = null;
6966 if ($singleton === null) {
6967 if (empty($CFG->early_install_lang)) {
6969 if (empty($CFG->langlist)) {
6970 $translist = array();
6971 } else {
6972 $translist = explode(',', $CFG->langlist);
6973 $translist = array_map('trim', $translist);
6976 if (!empty($CFG->config_php_settings['customstringmanager'])) {
6977 $classname = $CFG->config_php_settings['customstringmanager'];
6979 if (class_exists($classname)) {
6980 $implements = class_implements($classname);
6982 if (isset($implements['core_string_manager'])) {
6983 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist);
6984 return $singleton;
6986 } else {
6987 debugging('Unable to instantiate custom string manager: class '.$classname.
6988 ' does not implement the core_string_manager interface.');
6991 } else {
6992 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
6996 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6998 } else {
6999 $singleton = new core_string_manager_install();
7003 return $singleton;
7007 * Returns a localized string.
7009 * Returns the translated string specified by $identifier as
7010 * for $module. Uses the same format files as STphp.
7011 * $a is an object, string or number that can be used
7012 * within translation strings
7014 * eg 'hello {$a->firstname} {$a->lastname}'
7015 * or 'hello {$a}'
7017 * If you would like to directly echo the localized string use
7018 * the function {@link print_string()}
7020 * Example usage of this function involves finding the string you would
7021 * like a local equivalent of and using its identifier and module information
7022 * to retrieve it.<br/>
7023 * If you open moodle/lang/en/moodle.php and look near line 278
7024 * you will find a string to prompt a user for their word for 'course'
7025 * <code>
7026 * $string['course'] = 'Course';
7027 * </code>
7028 * So if you want to display the string 'Course'
7029 * in any language that supports it on your site
7030 * you just need to use the identifier 'course'
7031 * <code>
7032 * $mystring = '<strong>'. get_string('course') .'</strong>';
7033 * or
7034 * </code>
7035 * If the string you want is in another file you'd take a slightly
7036 * different approach. Looking in moodle/lang/en/calendar.php you find
7037 * around line 75:
7038 * <code>
7039 * $string['typecourse'] = 'Course event';
7040 * </code>
7041 * If you want to display the string "Course event" in any language
7042 * supported you would use the identifier 'typecourse' and the module 'calendar'
7043 * (because it is in the file calendar.php):
7044 * <code>
7045 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7046 * </code>
7048 * As a last resort, should the identifier fail to map to a string
7049 * the returned string will be [[ $identifier ]]
7051 * In Moodle 2.3 there is a new argument to this function $lazyload.
7052 * Setting $lazyload to true causes get_string to return a lang_string object
7053 * rather than the string itself. The fetching of the string is then put off until
7054 * the string object is first used. The object can be used by calling it's out
7055 * method or by casting the object to a string, either directly e.g.
7056 * (string)$stringobject
7057 * or indirectly by using the string within another string or echoing it out e.g.
7058 * echo $stringobject
7059 * return "<p>{$stringobject}</p>";
7060 * It is worth noting that using $lazyload and attempting to use the string as an
7061 * array key will cause a fatal error as objects cannot be used as array keys.
7062 * But you should never do that anyway!
7063 * For more information {@link lang_string}
7065 * @category string
7066 * @param string $identifier The key identifier for the localized string
7067 * @param string $component The module where the key identifier is stored,
7068 * usually expressed as the filename in the language pack without the
7069 * .php on the end but can also be written as mod/forum or grade/export/xls.
7070 * If none is specified then moodle.php is used.
7071 * @param string|object|array $a An object, string or number that can be used
7072 * within translation strings
7073 * @param bool $lazyload If set to true a string object is returned instead of
7074 * the string itself. The string then isn't calculated until it is first used.
7075 * @return string The localized string.
7076 * @throws coding_exception
7078 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7079 global $CFG;
7081 // If the lazy load argument has been supplied return a lang_string object
7082 // instead.
7083 // We need to make sure it is true (and a bool) as you will see below there
7084 // used to be a forth argument at one point.
7085 if ($lazyload === true) {
7086 return new lang_string($identifier, $component, $a);
7089 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7090 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7093 // There is now a forth argument again, this time it is a boolean however so
7094 // we can still check for the old extralocations parameter.
7095 if (!is_bool($lazyload) && !empty($lazyload)) {
7096 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7099 if (strpos($component, '/') !== false) {
7100 debugging('The module name you passed to get_string is the deprecated format ' .
7101 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7102 $componentpath = explode('/', $component);
7104 switch ($componentpath[0]) {
7105 case 'mod':
7106 $component = $componentpath[1];
7107 break;
7108 case 'blocks':
7109 case 'block':
7110 $component = 'block_'.$componentpath[1];
7111 break;
7112 case 'enrol':
7113 $component = 'enrol_'.$componentpath[1];
7114 break;
7115 case 'format':
7116 $component = 'format_'.$componentpath[1];
7117 break;
7118 case 'grade':
7119 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7120 break;
7124 $result = get_string_manager()->get_string($identifier, $component, $a);
7126 // Debugging feature lets you display string identifier and component.
7127 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7128 $result .= ' {' . $identifier . '/' . $component . '}';
7130 return $result;
7134 * Converts an array of strings to their localized value.
7136 * @param array $array An array of strings
7137 * @param string $component The language module that these strings can be found in.
7138 * @return stdClass translated strings.
7140 function get_strings($array, $component = '') {
7141 $string = new stdClass;
7142 foreach ($array as $item) {
7143 $string->$item = get_string($item, $component);
7145 return $string;
7149 * Prints out a translated string.
7151 * Prints out a translated string using the return value from the {@link get_string()} function.
7153 * Example usage of this function when the string is in the moodle.php file:<br/>
7154 * <code>
7155 * echo '<strong>';
7156 * print_string('course');
7157 * echo '</strong>';
7158 * </code>
7160 * Example usage of this function when the string is not in the moodle.php file:<br/>
7161 * <code>
7162 * echo '<h1>';
7163 * print_string('typecourse', 'calendar');
7164 * echo '</h1>';
7165 * </code>
7167 * @category string
7168 * @param string $identifier The key identifier for the localized string
7169 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7170 * @param string|object|array $a An object, string or number that can be used within translation strings
7172 function print_string($identifier, $component = '', $a = null) {
7173 echo get_string($identifier, $component, $a);
7177 * Returns a list of charset codes
7179 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7180 * (checking that such charset is supported by the texlib library!)
7182 * @return array And associative array with contents in the form of charset => charset
7184 function get_list_of_charsets() {
7186 $charsets = array(
7187 'EUC-JP' => 'EUC-JP',
7188 'ISO-2022-JP'=> 'ISO-2022-JP',
7189 'ISO-8859-1' => 'ISO-8859-1',
7190 'SHIFT-JIS' => 'SHIFT-JIS',
7191 'GB2312' => 'GB2312',
7192 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7193 'UTF-8' => 'UTF-8');
7195 asort($charsets);
7197 return $charsets;
7201 * Returns a list of valid and compatible themes
7203 * @return array
7205 function get_list_of_themes() {
7206 global $CFG;
7208 $themes = array();
7210 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7211 $themelist = explode(',', $CFG->themelist);
7212 } else {
7213 $themelist = array_keys(core_component::get_plugin_list("theme"));
7216 foreach ($themelist as $key => $themename) {
7217 $theme = theme_config::load($themename);
7218 $themes[$themename] = $theme;
7221 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7223 return $themes;
7227 * Factory function for emoticon_manager
7229 * @return emoticon_manager singleton
7231 function get_emoticon_manager() {
7232 static $singleton = null;
7234 if (is_null($singleton)) {
7235 $singleton = new emoticon_manager();
7238 return $singleton;
7242 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7244 * Whenever this manager mentiones 'emoticon object', the following data
7245 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7246 * altidentifier and altcomponent
7248 * @see admin_setting_emoticons
7250 * @copyright 2010 David Mudrak
7251 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7253 class emoticon_manager {
7256 * Returns the currently enabled emoticons
7258 * @return array of emoticon objects
7260 public function get_emoticons() {
7261 global $CFG;
7263 if (empty($CFG->emoticons)) {
7264 return array();
7267 $emoticons = $this->decode_stored_config($CFG->emoticons);
7269 if (!is_array($emoticons)) {
7270 // Something is wrong with the format of stored setting.
7271 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7272 return array();
7275 return $emoticons;
7279 * Converts emoticon object into renderable pix_emoticon object
7281 * @param stdClass $emoticon emoticon object
7282 * @param array $attributes explicit HTML attributes to set
7283 * @return pix_emoticon
7285 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7286 $stringmanager = get_string_manager();
7287 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7288 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7289 } else {
7290 $alt = s($emoticon->text);
7292 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7296 * Encodes the array of emoticon objects into a string storable in config table
7298 * @see self::decode_stored_config()
7299 * @param array $emoticons array of emtocion objects
7300 * @return string
7302 public function encode_stored_config(array $emoticons) {
7303 return json_encode($emoticons);
7307 * Decodes the string into an array of emoticon objects
7309 * @see self::encode_stored_config()
7310 * @param string $encoded
7311 * @return string|null
7313 public function decode_stored_config($encoded) {
7314 $decoded = json_decode($encoded);
7315 if (!is_array($decoded)) {
7316 return null;
7318 return $decoded;
7322 * Returns default set of emoticons supported by Moodle
7324 * @return array of sdtClasses
7326 public function default_emoticons() {
7327 return array(
7328 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7329 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7330 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7331 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7332 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7333 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7334 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7335 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7336 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7337 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7338 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7339 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7340 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7341 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7342 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7343 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7344 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7345 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7346 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7347 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7348 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7349 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7350 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7351 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7352 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7353 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7354 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7355 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7356 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7357 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7362 * Helper method preparing the stdClass with the emoticon properties
7364 * @param string|array $text or array of strings
7365 * @param string $imagename to be used by {@link pix_emoticon}
7366 * @param string $altidentifier alternative string identifier, null for no alt
7367 * @param string $altcomponent where the alternative string is defined
7368 * @param string $imagecomponent to be used by {@link pix_emoticon}
7369 * @return stdClass
7371 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7372 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7373 return (object)array(
7374 'text' => $text,
7375 'imagename' => $imagename,
7376 'imagecomponent' => $imagecomponent,
7377 'altidentifier' => $altidentifier,
7378 'altcomponent' => $altcomponent,
7383 // ENCRYPTION.
7386 * rc4encrypt
7388 * @param string $data Data to encrypt.
7389 * @return string The now encrypted data.
7391 function rc4encrypt($data) {
7392 return endecrypt(get_site_identifier(), $data, '');
7396 * rc4decrypt
7398 * @param string $data Data to decrypt.
7399 * @return string The now decrypted data.
7401 function rc4decrypt($data) {
7402 return endecrypt(get_site_identifier(), $data, 'de');
7406 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7408 * @todo Finish documenting this function
7410 * @param string $pwd The password to use when encrypting or decrypting
7411 * @param string $data The data to be decrypted/encrypted
7412 * @param string $case Either 'de' for decrypt or '' for encrypt
7413 * @return string
7415 function endecrypt ($pwd, $data, $case) {
7417 if ($case == 'de') {
7418 $data = urldecode($data);
7421 $key[] = '';
7422 $box[] = '';
7423 $pwdlength = strlen($pwd);
7425 for ($i = 0; $i <= 255; $i++) {
7426 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7427 $box[$i] = $i;
7430 $x = 0;
7432 for ($i = 0; $i <= 255; $i++) {
7433 $x = ($x + $box[$i] + $key[$i]) % 256;
7434 $tempswap = $box[$i];
7435 $box[$i] = $box[$x];
7436 $box[$x] = $tempswap;
7439 $cipher = '';
7441 $a = 0;
7442 $j = 0;
7444 for ($i = 0; $i < strlen($data); $i++) {
7445 $a = ($a + 1) % 256;
7446 $j = ($j + $box[$a]) % 256;
7447 $temp = $box[$a];
7448 $box[$a] = $box[$j];
7449 $box[$j] = $temp;
7450 $k = $box[(($box[$a] + $box[$j]) % 256)];
7451 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7452 $cipher .= chr($cipherby);
7455 if ($case == 'de') {
7456 $cipher = urldecode(urlencode($cipher));
7457 } else {
7458 $cipher = urlencode($cipher);
7461 return $cipher;
7464 // ENVIRONMENT CHECKING.
7467 * This method validates a plug name. It is much faster than calling clean_param.
7469 * @param string $name a string that might be a plugin name.
7470 * @return bool if this string is a valid plugin name.
7472 function is_valid_plugin_name($name) {
7473 // This does not work for 'mod', bad luck, use any other type.
7474 return core_component::is_valid_plugin_name('tool', $name);
7478 * Get a list of all the plugins of a given type that define a certain API function
7479 * in a certain file. The plugin component names and function names are returned.
7481 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7482 * @param string $function the part of the name of the function after the
7483 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7484 * names like report_courselist_hook.
7485 * @param string $file the name of file within the plugin that defines the
7486 * function. Defaults to lib.php.
7487 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7488 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7490 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7491 global $CFG;
7493 // We don't include here as all plugin types files would be included.
7494 $plugins = get_plugins_with_function($function, $file, false);
7496 if (empty($plugins[$plugintype])) {
7497 return array();
7500 $allplugins = core_component::get_plugin_list($plugintype);
7502 // Reformat the array and include the files.
7503 $pluginfunctions = array();
7504 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7506 // Check that it has not been removed and the file is still available.
7507 if (!empty($allplugins[$pluginname])) {
7509 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7510 if (file_exists($filepath)) {
7511 include_once($filepath);
7512 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7517 return $pluginfunctions;
7521 * Get a list of all the plugins that define a certain API function in a certain file.
7523 * @param string $function the part of the name of the function after the
7524 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7525 * names like report_courselist_hook.
7526 * @param string $file the name of file within the plugin that defines the
7527 * function. Defaults to lib.php.
7528 * @param bool $include Whether to include the files that contain the functions or not.
7529 * @return array with [plugintype][plugin] = functionname
7531 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7532 global $CFG;
7534 if (during_initial_install() || isset($CFG->upgraderunning)) {
7535 // API functions _must not_ be called during an installation or upgrade.
7536 return [];
7539 $cache = \cache::make('core', 'plugin_functions');
7541 // Including both although I doubt that we will find two functions definitions with the same name.
7542 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7543 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7544 $pluginfunctions = $cache->get($key);
7546 // Use the plugin manager to check that plugins are currently installed.
7547 $pluginmanager = \core_plugin_manager::instance();
7549 if ($pluginfunctions !== false) {
7551 // Checking that the files are still available.
7552 foreach ($pluginfunctions as $plugintype => $plugins) {
7554 $allplugins = \core_component::get_plugin_list($plugintype);
7555 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7556 foreach ($plugins as $plugin => $function) {
7557 if (!isset($installedplugins[$plugin])) {
7558 // Plugin code is still present on disk but it is not installed.
7559 unset($pluginfunctions[$plugintype][$plugin]);
7560 continue;
7563 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7564 if (empty($allplugins[$plugin])) {
7565 unset($pluginfunctions[$plugintype][$plugin]);
7566 continue;
7569 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7570 if ($include && $fileexists) {
7571 // Include the files if it was requested.
7572 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7573 } else if (!$fileexists) {
7574 // If the file is not available any more it should not be returned.
7575 unset($pluginfunctions[$plugintype][$plugin]);
7579 return $pluginfunctions;
7582 $pluginfunctions = array();
7584 // To fill the cached. Also, everything should continue working with cache disabled.
7585 $plugintypes = \core_component::get_plugin_types();
7586 foreach ($plugintypes as $plugintype => $unused) {
7588 // We need to include files here.
7589 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7590 $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7591 foreach ($pluginswithfile as $plugin => $notused) {
7593 if (!isset($installedplugins[$plugin])) {
7594 continue;
7597 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7599 $pluginfunction = false;
7600 if (function_exists($fullfunction)) {
7601 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7602 $pluginfunction = $fullfunction;
7604 } else if ($plugintype === 'mod') {
7605 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7606 $shortfunction = $plugin . '_' . $function;
7607 if (function_exists($shortfunction)) {
7608 $pluginfunction = $shortfunction;
7612 if ($pluginfunction) {
7613 if (empty($pluginfunctions[$plugintype])) {
7614 $pluginfunctions[$plugintype] = array();
7616 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7621 $cache->set($key, $pluginfunctions);
7623 return $pluginfunctions;
7628 * Lists plugin-like directories within specified directory
7630 * This function was originally used for standard Moodle plugins, please use
7631 * new core_component::get_plugin_list() now.
7633 * This function is used for general directory listing and backwards compatility.
7635 * @param string $directory relative directory from root
7636 * @param string $exclude dir name to exclude from the list (defaults to none)
7637 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7638 * @return array Sorted array of directory names found under the requested parameters
7640 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7641 global $CFG;
7643 $plugins = array();
7645 if (empty($basedir)) {
7646 $basedir = $CFG->dirroot .'/'. $directory;
7648 } else {
7649 $basedir = $basedir .'/'. $directory;
7652 if ($CFG->debugdeveloper and empty($exclude)) {
7653 // Make sure devs do not use this to list normal plugins,
7654 // this is intended for general directories that are not plugins!
7656 $subtypes = core_component::get_plugin_types();
7657 if (in_array($basedir, $subtypes)) {
7658 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7660 unset($subtypes);
7663 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7664 if (!$dirhandle = opendir($basedir)) {
7665 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7666 return array();
7668 while (false !== ($dir = readdir($dirhandle))) {
7669 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7670 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7671 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7672 continue;
7674 if (filetype($basedir .'/'. $dir) != 'dir') {
7675 continue;
7677 $plugins[] = $dir;
7679 closedir($dirhandle);
7681 if ($plugins) {
7682 asort($plugins);
7684 return $plugins;
7688 * Invoke plugin's callback functions
7690 * @param string $type plugin type e.g. 'mod'
7691 * @param string $name plugin name
7692 * @param string $feature feature name
7693 * @param string $action feature's action
7694 * @param array $params parameters of callback function, should be an array
7695 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7696 * @return mixed
7698 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7700 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7701 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7705 * Invoke component's callback functions
7707 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7708 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7709 * @param array $params parameters of callback function
7710 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7711 * @return mixed
7713 function component_callback($component, $function, array $params = array(), $default = null) {
7715 $functionname = component_callback_exists($component, $function);
7717 if ($functionname) {
7718 // Function exists, so just return function result.
7719 $ret = call_user_func_array($functionname, $params);
7720 if (is_null($ret)) {
7721 return $default;
7722 } else {
7723 return $ret;
7726 return $default;
7730 * Determine if a component callback exists and return the function name to call. Note that this
7731 * function will include the required library files so that the functioname returned can be
7732 * called directly.
7734 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7735 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7736 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7737 * @throws coding_exception if invalid component specfied
7739 function component_callback_exists($component, $function) {
7740 global $CFG; // This is needed for the inclusions.
7742 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7743 if (empty($cleancomponent)) {
7744 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7746 $component = $cleancomponent;
7748 list($type, $name) = core_component::normalize_component($component);
7749 $component = $type . '_' . $name;
7751 $oldfunction = $name.'_'.$function;
7752 $function = $component.'_'.$function;
7754 $dir = core_component::get_component_directory($component);
7755 if (empty($dir)) {
7756 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7759 // Load library and look for function.
7760 if (file_exists($dir.'/lib.php')) {
7761 require_once($dir.'/lib.php');
7764 if (!function_exists($function) and function_exists($oldfunction)) {
7765 if ($type !== 'mod' and $type !== 'core') {
7766 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7768 $function = $oldfunction;
7771 if (function_exists($function)) {
7772 return $function;
7774 return false;
7778 * Call the specified callback method on the provided class.
7780 * If the callback returns null, then the default value is returned instead.
7781 * If the class does not exist, then the default value is returned.
7783 * @param string $classname The name of the class to call upon.
7784 * @param string $methodname The name of the staticically defined method on the class.
7785 * @param array $params The arguments to pass into the method.
7786 * @param mixed $default The default value.
7787 * @return mixed The return value.
7789 function component_class_callback($classname, $methodname, array $params, $default = null) {
7790 if (!class_exists($classname)) {
7791 return $default;
7794 if (!method_exists($classname, $methodname)) {
7795 return $default;
7798 $fullfunction = $classname . '::' . $methodname;
7799 $result = call_user_func_array($fullfunction, $params);
7801 if (null === $result) {
7802 return $default;
7803 } else {
7804 return $result;
7809 * Checks whether a plugin supports a specified feature.
7811 * @param string $type Plugin type e.g. 'mod'
7812 * @param string $name Plugin name e.g. 'forum'
7813 * @param string $feature Feature code (FEATURE_xx constant)
7814 * @param mixed $default default value if feature support unknown
7815 * @return mixed Feature result (false if not supported, null if feature is unknown,
7816 * otherwise usually true but may have other feature-specific value such as array)
7817 * @throws coding_exception
7819 function plugin_supports($type, $name, $feature, $default = null) {
7820 global $CFG;
7822 if ($type === 'mod' and $name === 'NEWMODULE') {
7823 // Somebody forgot to rename the module template.
7824 return false;
7827 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7828 if (empty($component)) {
7829 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7832 $function = null;
7834 if ($type === 'mod') {
7835 // We need this special case because we support subplugins in modules,
7836 // otherwise it would end up in infinite loop.
7837 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7838 include_once("$CFG->dirroot/mod/$name/lib.php");
7839 $function = $component.'_supports';
7840 if (!function_exists($function)) {
7841 // Legacy non-frankenstyle function name.
7842 $function = $name.'_supports';
7846 } else {
7847 if (!$path = core_component::get_plugin_directory($type, $name)) {
7848 // Non existent plugin type.
7849 return false;
7851 if (file_exists("$path/lib.php")) {
7852 include_once("$path/lib.php");
7853 $function = $component.'_supports';
7857 if ($function and function_exists($function)) {
7858 $supports = $function($feature);
7859 if (is_null($supports)) {
7860 // Plugin does not know - use default.
7861 return $default;
7862 } else {
7863 return $supports;
7867 // Plugin does not care, so use default.
7868 return $default;
7872 * Returns true if the current version of PHP is greater that the specified one.
7874 * @todo Check PHP version being required here is it too low?
7876 * @param string $version The version of php being tested.
7877 * @return bool
7879 function check_php_version($version='5.2.4') {
7880 return (version_compare(phpversion(), $version) >= 0);
7884 * Determine if moodle installation requires update.
7886 * Checks version numbers of main code and all plugins to see
7887 * if there are any mismatches.
7889 * @return bool
7891 function moodle_needs_upgrading() {
7892 global $CFG;
7894 if (empty($CFG->version)) {
7895 return true;
7898 // There is no need to purge plugininfo caches here because
7899 // these caches are not used during upgrade and they are purged after
7900 // every upgrade.
7902 if (empty($CFG->allversionshash)) {
7903 return true;
7906 $hash = core_component::get_all_versions_hash();
7908 return ($hash !== $CFG->allversionshash);
7912 * Returns the major version of this site
7914 * Moodle version numbers consist of three numbers separated by a dot, for
7915 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7916 * called major version. This function extracts the major version from either
7917 * $CFG->release (default) or eventually from the $release variable defined in
7918 * the main version.php.
7920 * @param bool $fromdisk should the version if source code files be used
7921 * @return string|false the major version like '2.3', false if could not be determined
7923 function moodle_major_version($fromdisk = false) {
7924 global $CFG;
7926 if ($fromdisk) {
7927 $release = null;
7928 require($CFG->dirroot.'/version.php');
7929 if (empty($release)) {
7930 return false;
7933 } else {
7934 if (empty($CFG->release)) {
7935 return false;
7937 $release = $CFG->release;
7940 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7941 return $matches[0];
7942 } else {
7943 return false;
7947 // MISCELLANEOUS.
7950 * Sets the system locale
7952 * @category string
7953 * @param string $locale Can be used to force a locale
7955 function moodle_setlocale($locale='') {
7956 global $CFG;
7958 static $currentlocale = ''; // Last locale caching.
7960 $oldlocale = $currentlocale;
7962 // Fetch the correct locale based on ostype.
7963 if ($CFG->ostype == 'WINDOWS') {
7964 $stringtofetch = 'localewin';
7965 } else {
7966 $stringtofetch = 'locale';
7969 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7970 if (!empty($locale)) {
7971 $currentlocale = $locale;
7972 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7973 $currentlocale = $CFG->locale;
7974 } else {
7975 $currentlocale = get_string($stringtofetch, 'langconfig');
7978 // Do nothing if locale already set up.
7979 if ($oldlocale == $currentlocale) {
7980 return;
7983 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7984 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7985 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7987 // Get current values.
7988 $monetary= setlocale (LC_MONETARY, 0);
7989 $numeric = setlocale (LC_NUMERIC, 0);
7990 $ctype = setlocale (LC_CTYPE, 0);
7991 if ($CFG->ostype != 'WINDOWS') {
7992 $messages= setlocale (LC_MESSAGES, 0);
7994 // Set locale to all.
7995 $result = setlocale (LC_ALL, $currentlocale);
7996 // If setting of locale fails try the other utf8 or utf-8 variant,
7997 // some operating systems support both (Debian), others just one (OSX).
7998 if ($result === false) {
7999 if (stripos($currentlocale, '.UTF-8') !== false) {
8000 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8001 setlocale (LC_ALL, $newlocale);
8002 } else if (stripos($currentlocale, '.UTF8') !== false) {
8003 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8004 setlocale (LC_ALL, $newlocale);
8007 // Set old values.
8008 setlocale (LC_MONETARY, $monetary);
8009 setlocale (LC_NUMERIC, $numeric);
8010 if ($CFG->ostype != 'WINDOWS') {
8011 setlocale (LC_MESSAGES, $messages);
8013 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8014 // To workaround a well-known PHP problem with Turkish letter Ii.
8015 setlocale (LC_CTYPE, $ctype);
8020 * Count words in a string.
8022 * Words are defined as things between whitespace.
8024 * @category string
8025 * @param string $string The text to be searched for words.
8026 * @return int The count of words in the specified string
8028 function count_words($string) {
8029 $string = strip_tags($string);
8030 // Decode HTML entities.
8031 $string = html_entity_decode($string);
8032 // Replace underscores (which are classed as word characters) with spaces.
8033 $string = preg_replace('/_/u', ' ', $string);
8034 // Remove any characters that shouldn't be treated as word boundaries.
8035 $string = preg_replace('/[\'"’-]/u', '', $string);
8036 // Remove dots and commas from within numbers only.
8037 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
8039 return count(preg_split('/\w\b/u', $string)) - 1;
8043 * Count letters in a string.
8045 * Letters are defined as chars not in tags and different from whitespace.
8047 * @category string
8048 * @param string $string The text to be searched for letters.
8049 * @return int The count of letters in the specified text.
8051 function count_letters($string) {
8052 $string = strip_tags($string); // Tags are out now.
8053 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8055 return core_text::strlen($string);
8059 * Generate and return a random string of the specified length.
8061 * @param int $length The length of the string to be created.
8062 * @return string
8064 function random_string($length=15) {
8065 $randombytes = random_bytes_emulate($length);
8066 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8067 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8068 $pool .= '0123456789';
8069 $poollen = strlen($pool);
8070 $string = '';
8071 for ($i = 0; $i < $length; $i++) {
8072 $rand = ord($randombytes[$i]);
8073 $string .= substr($pool, ($rand%($poollen)), 1);
8075 return $string;
8079 * Generate a complex random string (useful for md5 salts)
8081 * This function is based on the above {@link random_string()} however it uses a
8082 * larger pool of characters and generates a string between 24 and 32 characters
8084 * @param int $length Optional if set generates a string to exactly this length
8085 * @return string
8087 function complex_random_string($length=null) {
8088 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8089 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8090 $poollen = strlen($pool);
8091 if ($length===null) {
8092 $length = floor(rand(24, 32));
8094 $randombytes = random_bytes_emulate($length);
8095 $string = '';
8096 for ($i = 0; $i < $length; $i++) {
8097 $rand = ord($randombytes[$i]);
8098 $string .= $pool[($rand%$poollen)];
8100 return $string;
8104 * Try to generates cryptographically secure pseudo-random bytes.
8106 * Note this is achieved by fallbacking between:
8107 * - PHP 7 random_bytes().
8108 * - OpenSSL openssl_random_pseudo_bytes().
8109 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8111 * @param int $length requested length in bytes
8112 * @return string binary data
8114 function random_bytes_emulate($length) {
8115 global $CFG;
8116 if ($length <= 0) {
8117 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8118 return '';
8120 if (function_exists('random_bytes')) {
8121 // Use PHP 7 goodness.
8122 $hash = @random_bytes($length);
8123 if ($hash !== false) {
8124 return $hash;
8127 if (function_exists('openssl_random_pseudo_bytes')) {
8128 // If you have the openssl extension enabled.
8129 $hash = openssl_random_pseudo_bytes($length);
8130 if ($hash !== false) {
8131 return $hash;
8135 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8136 $staticdata = serialize($CFG) . serialize($_SERVER);
8137 $hash = '';
8138 do {
8139 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8140 } while (strlen($hash) < $length);
8142 return substr($hash, 0, $length);
8146 * Given some text (which may contain HTML) and an ideal length,
8147 * this function truncates the text neatly on a word boundary if possible
8149 * @category string
8150 * @param string $text text to be shortened
8151 * @param int $ideal ideal string length
8152 * @param boolean $exact if false, $text will not be cut mid-word
8153 * @param string $ending The string to append if the passed string is truncated
8154 * @return string $truncate shortened string
8156 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8157 // If the plain text is shorter than the maximum length, return the whole text.
8158 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8159 return $text;
8162 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8163 // and only tag in its 'line'.
8164 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8166 $totallength = core_text::strlen($ending);
8167 $truncate = '';
8169 // This array stores information about open and close tags and their position
8170 // in the truncated string. Each item in the array is an object with fields
8171 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8172 // (byte position in truncated text).
8173 $tagdetails = array();
8175 foreach ($lines as $linematchings) {
8176 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8177 if (!empty($linematchings[1])) {
8178 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8179 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8180 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8181 // Record closing tag.
8182 $tagdetails[] = (object) array(
8183 'open' => false,
8184 'tag' => core_text::strtolower($tagmatchings[1]),
8185 'pos' => core_text::strlen($truncate),
8188 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8189 // Record opening tag.
8190 $tagdetails[] = (object) array(
8191 'open' => true,
8192 'tag' => core_text::strtolower($tagmatchings[1]),
8193 'pos' => core_text::strlen($truncate),
8195 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8196 $tagdetails[] = (object) array(
8197 'open' => true,
8198 'tag' => core_text::strtolower('if'),
8199 'pos' => core_text::strlen($truncate),
8201 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8202 $tagdetails[] = (object) array(
8203 'open' => false,
8204 'tag' => core_text::strtolower('if'),
8205 'pos' => core_text::strlen($truncate),
8209 // Add html-tag to $truncate'd text.
8210 $truncate .= $linematchings[1];
8213 // Calculate the length of the plain text part of the line; handle entities as one character.
8214 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8215 if ($totallength + $contentlength > $ideal) {
8216 // The number of characters which are left.
8217 $left = $ideal - $totallength;
8218 $entitieslength = 0;
8219 // Search for html entities.
8220 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)) {
8221 // Calculate the real length of all entities in the legal range.
8222 foreach ($entities[0] as $entity) {
8223 if ($entity[1]+1-$entitieslength <= $left) {
8224 $left--;
8225 $entitieslength += core_text::strlen($entity[0]);
8226 } else {
8227 // No more characters left.
8228 break;
8232 $breakpos = $left + $entitieslength;
8234 // If the words shouldn't be cut in the middle...
8235 if (!$exact) {
8236 // Search the last occurence of a space.
8237 for (; $breakpos > 0; $breakpos--) {
8238 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8239 if ($char === '.' or $char === ' ') {
8240 $breakpos += 1;
8241 break;
8242 } else if (strlen($char) > 2) {
8243 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8244 $breakpos += 1;
8245 break;
8250 if ($breakpos == 0) {
8251 // This deals with the test_shorten_text_no_spaces case.
8252 $breakpos = $left + $entitieslength;
8253 } else if ($breakpos > $left + $entitieslength) {
8254 // This deals with the previous for loop breaking on the first char.
8255 $breakpos = $left + $entitieslength;
8258 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8259 // Maximum length is reached, so get off the loop.
8260 break;
8261 } else {
8262 $truncate .= $linematchings[2];
8263 $totallength += $contentlength;
8266 // If the maximum length is reached, get off the loop.
8267 if ($totallength >= $ideal) {
8268 break;
8272 // Add the defined ending to the text.
8273 $truncate .= $ending;
8275 // Now calculate the list of open html tags based on the truncate position.
8276 $opentags = array();
8277 foreach ($tagdetails as $taginfo) {
8278 if ($taginfo->open) {
8279 // Add tag to the beginning of $opentags list.
8280 array_unshift($opentags, $taginfo->tag);
8281 } else {
8282 // Can have multiple exact same open tags, close the last one.
8283 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8284 if ($pos !== false) {
8285 unset($opentags[$pos]);
8290 // Close all unclosed html-tags.
8291 foreach ($opentags as $tag) {
8292 if ($tag === 'if') {
8293 $truncate .= '<!--<![endif]-->';
8294 } else {
8295 $truncate .= '</' . $tag . '>';
8299 return $truncate;
8303 * Shortens a given filename by removing characters positioned after the ideal string length.
8304 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8305 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8307 * @param string $filename file name
8308 * @param int $length ideal string length
8309 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8310 * @return string $shortened shortened file name
8312 function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8313 $shortened = $filename;
8314 // Extract a part of the filename if it's char size exceeds the ideal string length.
8315 if (core_text::strlen($filename) > $length) {
8316 // Exclude extension if present in filename.
8317 $mimetypes = get_mimetypes_array();
8318 $extension = pathinfo($filename, PATHINFO_EXTENSION);
8319 if ($extension && !empty($mimetypes[$extension])) {
8320 $basename = pathinfo($filename, PATHINFO_FILENAME);
8321 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8322 $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8323 $shortened .= '.' . $extension;
8324 } else {
8325 $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8326 $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8329 return $shortened;
8333 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8335 * @param array $path The paths to reduce the length.
8336 * @param int $length Ideal string length
8337 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8338 * @return array $result Shortened paths in array.
8340 function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8341 $result = null;
8343 $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8344 $carry[] = shorten_filename($singlepath, $length, $includehash);
8345 return $carry;
8346 }, []);
8348 return $result;
8352 * Given dates in seconds, how many weeks is the date from startdate
8353 * The first week is 1, the second 2 etc ...
8355 * @param int $startdate Timestamp for the start date
8356 * @param int $thedate Timestamp for the end date
8357 * @return string
8359 function getweek ($startdate, $thedate) {
8360 if ($thedate < $startdate) {
8361 return 0;
8364 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8368 * Returns a randomly generated password of length $maxlen. inspired by
8370 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8371 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8373 * @param int $maxlen The maximum size of the password being generated.
8374 * @return string
8376 function generate_password($maxlen=10) {
8377 global $CFG;
8379 if (empty($CFG->passwordpolicy)) {
8380 $fillers = PASSWORD_DIGITS;
8381 $wordlist = file($CFG->wordlist);
8382 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8383 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8384 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8385 $password = $word1 . $filler1 . $word2;
8386 } else {
8387 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8388 $digits = $CFG->minpassworddigits;
8389 $lower = $CFG->minpasswordlower;
8390 $upper = $CFG->minpasswordupper;
8391 $nonalphanum = $CFG->minpasswordnonalphanum;
8392 $total = $lower + $upper + $digits + $nonalphanum;
8393 // Var minlength should be the greater one of the two ( $minlen and $total ).
8394 $minlen = $minlen < $total ? $total : $minlen;
8395 // Var maxlen can never be smaller than minlen.
8396 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8397 $additional = $maxlen - $total;
8399 // Make sure we have enough characters to fulfill
8400 // complexity requirements.
8401 $passworddigits = PASSWORD_DIGITS;
8402 while ($digits > strlen($passworddigits)) {
8403 $passworddigits .= PASSWORD_DIGITS;
8405 $passwordlower = PASSWORD_LOWER;
8406 while ($lower > strlen($passwordlower)) {
8407 $passwordlower .= PASSWORD_LOWER;
8409 $passwordupper = PASSWORD_UPPER;
8410 while ($upper > strlen($passwordupper)) {
8411 $passwordupper .= PASSWORD_UPPER;
8413 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8414 while ($nonalphanum > strlen($passwordnonalphanum)) {
8415 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8418 // Now mix and shuffle it all.
8419 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8420 substr(str_shuffle ($passwordupper), 0, $upper) .
8421 substr(str_shuffle ($passworddigits), 0, $digits) .
8422 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8423 substr(str_shuffle ($passwordlower .
8424 $passwordupper .
8425 $passworddigits .
8426 $passwordnonalphanum), 0 , $additional));
8429 return substr ($password, 0, $maxlen);
8433 * Given a float, prints it nicely.
8434 * Localized floats must not be used in calculations!
8436 * The stripzeros feature is intended for making numbers look nicer in small
8437 * areas where it is not necessary to indicate the degree of accuracy by showing
8438 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8439 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8441 * @param float $float The float to print
8442 * @param int $decimalpoints The number of decimal places to print.
8443 * @param bool $localized use localized decimal separator
8444 * @param bool $stripzeros If true, removes final zeros after decimal point
8445 * @return string locale float
8447 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8448 if (is_null($float)) {
8449 return '';
8451 if ($localized) {
8452 $separator = get_string('decsep', 'langconfig');
8453 } else {
8454 $separator = '.';
8456 $result = number_format($float, $decimalpoints, $separator, '');
8457 if ($stripzeros) {
8458 // Remove zeros and final dot if not needed.
8459 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8461 return $result;
8465 * Converts locale specific floating point/comma number back to standard PHP float value
8466 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8468 * @param string $localefloat locale aware float representation
8469 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8470 * @return mixed float|bool - false or the parsed float.
8472 function unformat_float($localefloat, $strict = false) {
8473 $localefloat = trim($localefloat);
8475 if ($localefloat == '') {
8476 return null;
8479 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8480 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8482 if ($strict && !is_numeric($localefloat)) {
8483 return false;
8486 return (float)$localefloat;
8490 * Given a simple array, this shuffles it up just like shuffle()
8491 * Unlike PHP's shuffle() this function works on any machine.
8493 * @param array $array The array to be rearranged
8494 * @return array
8496 function swapshuffle($array) {
8498 $last = count($array) - 1;
8499 for ($i = 0; $i <= $last; $i++) {
8500 $from = rand(0, $last);
8501 $curr = $array[$i];
8502 $array[$i] = $array[$from];
8503 $array[$from] = $curr;
8505 return $array;
8509 * Like {@link swapshuffle()}, but works on associative arrays
8511 * @param array $array The associative array to be rearranged
8512 * @return array
8514 function swapshuffle_assoc($array) {
8516 $newarray = array();
8517 $newkeys = swapshuffle(array_keys($array));
8519 foreach ($newkeys as $newkey) {
8520 $newarray[$newkey] = $array[$newkey];
8522 return $newarray;
8526 * Given an arbitrary array, and a number of draws,
8527 * this function returns an array with that amount
8528 * of items. The indexes are retained.
8530 * @todo Finish documenting this function
8532 * @param array $array
8533 * @param int $draws
8534 * @return array
8536 function draw_rand_array($array, $draws) {
8538 $return = array();
8540 $last = count($array);
8542 if ($draws > $last) {
8543 $draws = $last;
8546 while ($draws > 0) {
8547 $last--;
8549 $keys = array_keys($array);
8550 $rand = rand(0, $last);
8552 $return[$keys[$rand]] = $array[$keys[$rand]];
8553 unset($array[$keys[$rand]]);
8555 $draws--;
8558 return $return;
8562 * Calculate the difference between two microtimes
8564 * @param string $a The first Microtime
8565 * @param string $b The second Microtime
8566 * @return string
8568 function microtime_diff($a, $b) {
8569 list($adec, $asec) = explode(' ', $a);
8570 list($bdec, $bsec) = explode(' ', $b);
8571 return $bsec - $asec + $bdec - $adec;
8575 * Given a list (eg a,b,c,d,e) this function returns
8576 * an array of 1->a, 2->b, 3->c etc
8578 * @param string $list The string to explode into array bits
8579 * @param string $separator The separator used within the list string
8580 * @return array The now assembled array
8582 function make_menu_from_list($list, $separator=',') {
8584 $array = array_reverse(explode($separator, $list), true);
8585 foreach ($array as $key => $item) {
8586 $outarray[$key+1] = trim($item);
8588 return $outarray;
8592 * Creates an array that represents all the current grades that
8593 * can be chosen using the given grading type.
8595 * Negative numbers
8596 * are scales, zero is no grade, and positive numbers are maximum
8597 * grades.
8599 * @todo Finish documenting this function or better deprecated this completely!
8601 * @param int $gradingtype
8602 * @return array
8604 function make_grades_menu($gradingtype) {
8605 global $DB;
8607 $grades = array();
8608 if ($gradingtype < 0) {
8609 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8610 return make_menu_from_list($scale->scale);
8612 } else if ($gradingtype > 0) {
8613 for ($i=$gradingtype; $i>=0; $i--) {
8614 $grades[$i] = $i .' / '. $gradingtype;
8616 return $grades;
8618 return $grades;
8622 * make_unique_id_code
8624 * @todo Finish documenting this function
8626 * @uses $_SERVER
8627 * @param string $extra Extra string to append to the end of the code
8628 * @return string
8630 function make_unique_id_code($extra = '') {
8632 $hostname = 'unknownhost';
8633 if (!empty($_SERVER['HTTP_HOST'])) {
8634 $hostname = $_SERVER['HTTP_HOST'];
8635 } else if (!empty($_ENV['HTTP_HOST'])) {
8636 $hostname = $_ENV['HTTP_HOST'];
8637 } else if (!empty($_SERVER['SERVER_NAME'])) {
8638 $hostname = $_SERVER['SERVER_NAME'];
8639 } else if (!empty($_ENV['SERVER_NAME'])) {
8640 $hostname = $_ENV['SERVER_NAME'];
8643 $date = gmdate("ymdHis");
8645 $random = random_string(6);
8647 if ($extra) {
8648 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8649 } else {
8650 return $hostname .'+'. $date .'+'. $random;
8656 * Function to check the passed address is within the passed subnet
8658 * The parameter is a comma separated string of subnet definitions.
8659 * Subnet strings can be in one of three formats:
8660 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8661 * 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)
8662 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8663 * Code for type 1 modified from user posted comments by mediator at
8664 * {@link http://au.php.net/manual/en/function.ip2long.php}
8666 * @param string $addr The address you are checking
8667 * @param string $subnetstr The string of subnet addresses
8668 * @return bool
8670 function address_in_subnet($addr, $subnetstr) {
8672 if ($addr == '0.0.0.0') {
8673 return false;
8675 $subnets = explode(',', $subnetstr);
8676 $found = false;
8677 $addr = trim($addr);
8678 $addr = cleanremoteaddr($addr, false); // Normalise.
8679 if ($addr === null) {
8680 return false;
8682 $addrparts = explode(':', $addr);
8684 $ipv6 = strpos($addr, ':');
8686 foreach ($subnets as $subnet) {
8687 $subnet = trim($subnet);
8688 if ($subnet === '') {
8689 continue;
8692 if (strpos($subnet, '/') !== false) {
8693 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8694 list($ip, $mask) = explode('/', $subnet);
8695 $mask = trim($mask);
8696 if (!is_number($mask)) {
8697 continue; // Incorect mask number, eh?
8699 $ip = cleanremoteaddr($ip, false); // Normalise.
8700 if ($ip === null) {
8701 continue;
8703 if (strpos($ip, ':') !== false) {
8704 // IPv6.
8705 if (!$ipv6) {
8706 continue;
8708 if ($mask > 128 or $mask < 0) {
8709 continue; // Nonsense.
8711 if ($mask == 0) {
8712 return true; // Any address.
8714 if ($mask == 128) {
8715 if ($ip === $addr) {
8716 return true;
8718 continue;
8720 $ipparts = explode(':', $ip);
8721 $modulo = $mask % 16;
8722 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8723 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8724 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8725 if ($modulo == 0) {
8726 return true;
8728 $pos = ($mask-$modulo)/16;
8729 $ipnet = hexdec($ipparts[$pos]);
8730 $addrnet = hexdec($addrparts[$pos]);
8731 $mask = 0xffff << (16 - $modulo);
8732 if (($addrnet & $mask) == ($ipnet & $mask)) {
8733 return true;
8737 } else {
8738 // IPv4.
8739 if ($ipv6) {
8740 continue;
8742 if ($mask > 32 or $mask < 0) {
8743 continue; // Nonsense.
8745 if ($mask == 0) {
8746 return true;
8748 if ($mask == 32) {
8749 if ($ip === $addr) {
8750 return true;
8752 continue;
8754 $mask = 0xffffffff << (32 - $mask);
8755 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8756 return true;
8760 } else if (strpos($subnet, '-') !== false) {
8761 // 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.
8762 $parts = explode('-', $subnet);
8763 if (count($parts) != 2) {
8764 continue;
8767 if (strpos($subnet, ':') !== false) {
8768 // IPv6.
8769 if (!$ipv6) {
8770 continue;
8772 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8773 if ($ipstart === null) {
8774 continue;
8776 $ipparts = explode(':', $ipstart);
8777 $start = hexdec(array_pop($ipparts));
8778 $ipparts[] = trim($parts[1]);
8779 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8780 if ($ipend === null) {
8781 continue;
8783 $ipparts[7] = '';
8784 $ipnet = implode(':', $ipparts);
8785 if (strpos($addr, $ipnet) !== 0) {
8786 continue;
8788 $ipparts = explode(':', $ipend);
8789 $end = hexdec($ipparts[7]);
8791 $addrend = hexdec($addrparts[7]);
8793 if (($addrend >= $start) and ($addrend <= $end)) {
8794 return true;
8797 } else {
8798 // IPv4.
8799 if ($ipv6) {
8800 continue;
8802 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8803 if ($ipstart === null) {
8804 continue;
8806 $ipparts = explode('.', $ipstart);
8807 $ipparts[3] = trim($parts[1]);
8808 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8809 if ($ipend === null) {
8810 continue;
8813 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8814 return true;
8818 } else {
8819 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8820 if (strpos($subnet, ':') !== false) {
8821 // IPv6.
8822 if (!$ipv6) {
8823 continue;
8825 $parts = explode(':', $subnet);
8826 $count = count($parts);
8827 if ($parts[$count-1] === '') {
8828 unset($parts[$count-1]); // Trim trailing :'s.
8829 $count--;
8830 $subnet = implode('.', $parts);
8832 $isip = cleanremoteaddr($subnet, false); // Normalise.
8833 if ($isip !== null) {
8834 if ($isip === $addr) {
8835 return true;
8837 continue;
8838 } else if ($count > 8) {
8839 continue;
8841 $zeros = array_fill(0, 8-$count, '0');
8842 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8843 if (address_in_subnet($addr, $subnet)) {
8844 return true;
8847 } else {
8848 // IPv4.
8849 if ($ipv6) {
8850 continue;
8852 $parts = explode('.', $subnet);
8853 $count = count($parts);
8854 if ($parts[$count-1] === '') {
8855 unset($parts[$count-1]); // Trim trailing .
8856 $count--;
8857 $subnet = implode('.', $parts);
8859 if ($count == 4) {
8860 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8861 if ($subnet === $addr) {
8862 return true;
8864 continue;
8865 } else if ($count > 4) {
8866 continue;
8868 $zeros = array_fill(0, 4-$count, '0');
8869 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8870 if (address_in_subnet($addr, $subnet)) {
8871 return true;
8877 return false;
8881 * For outputting debugging info
8883 * @param string $string The string to write
8884 * @param string $eol The end of line char(s) to use
8885 * @param string $sleep Period to make the application sleep
8886 * This ensures any messages have time to display before redirect
8888 function mtrace($string, $eol="\n", $sleep=0) {
8889 global $CFG;
8891 if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
8892 $fn = $CFG->mtrace_wrapper;
8893 $fn($string, $eol);
8894 return;
8895 } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
8896 fwrite(STDOUT, $string.$eol);
8897 } else {
8898 echo $string . $eol;
8901 flush();
8903 // Delay to keep message on user's screen in case of subsequent redirect.
8904 if ($sleep) {
8905 sleep($sleep);
8910 * Replace 1 or more slashes or backslashes to 1 slash
8912 * @param string $path The path to strip
8913 * @return string the path with double slashes removed
8915 function cleardoubleslashes ($path) {
8916 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8920 * Is the current ip in a given list?
8922 * @param string $list
8923 * @return bool
8925 function remoteip_in_list($list) {
8926 $inlist = false;
8927 $clientip = getremoteaddr(null);
8929 if (!$clientip) {
8930 // Ensure access on cli.
8931 return true;
8934 $list = explode("\n", $list);
8935 foreach ($list as $line) {
8936 $tokens = explode('#', $line);
8937 $subnet = trim($tokens[0]);
8938 if (address_in_subnet($clientip, $subnet)) {
8939 $inlist = true;
8940 break;
8943 return $inlist;
8947 * Returns most reliable client address
8949 * @param string $default If an address can't be determined, then return this
8950 * @return string The remote IP address
8952 function getremoteaddr($default='0.0.0.0') {
8953 global $CFG;
8955 if (empty($CFG->getremoteaddrconf)) {
8956 // This will happen, for example, before just after the upgrade, as the
8957 // user is redirected to the admin screen.
8958 $variablestoskip = 0;
8959 } else {
8960 $variablestoskip = $CFG->getremoteaddrconf;
8962 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8963 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8964 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8965 return $address ? $address : $default;
8968 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8969 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8970 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8971 $address = $forwardedaddresses[0];
8973 if (substr_count($address, ":") > 1) {
8974 // Remove port and brackets from IPv6.
8975 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8976 $address = $matches[1];
8978 } else {
8979 // Remove port from IPv4.
8980 if (substr_count($address, ":") == 1) {
8981 $parts = explode(":", $address);
8982 $address = $parts[0];
8986 $address = cleanremoteaddr($address);
8987 return $address ? $address : $default;
8990 if (!empty($_SERVER['REMOTE_ADDR'])) {
8991 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8992 return $address ? $address : $default;
8993 } else {
8994 return $default;
8999 * Cleans an ip address. Internal addresses are now allowed.
9000 * (Originally local addresses were not allowed.)
9002 * @param string $addr IPv4 or IPv6 address
9003 * @param bool $compress use IPv6 address compression
9004 * @return string normalised ip address string, null if error
9006 function cleanremoteaddr($addr, $compress=false) {
9007 $addr = trim($addr);
9009 if (strpos($addr, ':') !== false) {
9010 // Can be only IPv6.
9011 $parts = explode(':', $addr);
9012 $count = count($parts);
9014 if (strpos($parts[$count-1], '.') !== false) {
9015 // Legacy ipv4 notation.
9016 $last = array_pop($parts);
9017 $ipv4 = cleanremoteaddr($last, true);
9018 if ($ipv4 === null) {
9019 return null;
9021 $bits = explode('.', $ipv4);
9022 $parts[] = dechex($bits[0]).dechex($bits[1]);
9023 $parts[] = dechex($bits[2]).dechex($bits[3]);
9024 $count = count($parts);
9025 $addr = implode(':', $parts);
9028 if ($count < 3 or $count > 8) {
9029 return null; // Severly malformed.
9032 if ($count != 8) {
9033 if (strpos($addr, '::') === false) {
9034 return null; // Malformed.
9036 // Uncompress.
9037 $insertat = array_search('', $parts, true);
9038 $missing = array_fill(0, 1 + 8 - $count, '0');
9039 array_splice($parts, $insertat, 1, $missing);
9040 foreach ($parts as $key => $part) {
9041 if ($part === '') {
9042 $parts[$key] = '0';
9047 $adr = implode(':', $parts);
9048 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9049 return null; // Incorrect format - sorry.
9052 // Normalise 0s and case.
9053 $parts = array_map('hexdec', $parts);
9054 $parts = array_map('dechex', $parts);
9056 $result = implode(':', $parts);
9058 if (!$compress) {
9059 return $result;
9062 if ($result === '0:0:0:0:0:0:0:0') {
9063 return '::'; // All addresses.
9066 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9067 if ($compressed !== $result) {
9068 return $compressed;
9071 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9072 if ($compressed !== $result) {
9073 return $compressed;
9076 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9077 if ($compressed !== $result) {
9078 return $compressed;
9081 return $result;
9084 // First get all things that look like IPv4 addresses.
9085 $parts = array();
9086 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9087 return null;
9089 unset($parts[0]);
9091 foreach ($parts as $key => $match) {
9092 if ($match > 255) {
9093 return null;
9095 $parts[$key] = (int)$match; // Normalise 0s.
9098 return implode('.', $parts);
9103 * Is IP address a public address?
9105 * @param string $ip The ip to check
9106 * @return bool true if the ip is public
9108 function ip_is_public($ip) {
9109 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9113 * This function will make a complete copy of anything it's given,
9114 * regardless of whether it's an object or not.
9116 * @param mixed $thing Something you want cloned
9117 * @return mixed What ever it is you passed it
9119 function fullclone($thing) {
9120 return unserialize(serialize($thing));
9124 * Used to make sure that $min <= $value <= $max
9126 * Make sure that value is between min, and max
9128 * @param int $min The minimum value
9129 * @param int $value The value to check
9130 * @param int $max The maximum value
9131 * @return int
9133 function bounded_number($min, $value, $max) {
9134 if ($value < $min) {
9135 return $min;
9137 if ($value > $max) {
9138 return $max;
9140 return $value;
9144 * Check if there is a nested array within the passed array
9146 * @param array $array
9147 * @return bool true if there is a nested array false otherwise
9149 function array_is_nested($array) {
9150 foreach ($array as $value) {
9151 if (is_array($value)) {
9152 return true;
9155 return false;
9159 * get_performance_info() pairs up with init_performance_info()
9160 * loaded in setup.php. Returns an array with 'html' and 'txt'
9161 * values ready for use, and each of the individual stats provided
9162 * separately as well.
9164 * @return array
9166 function get_performance_info() {
9167 global $CFG, $PERF, $DB, $PAGE;
9169 $info = array();
9170 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9172 $info['html'] = '';
9173 if (!empty($CFG->themedesignermode)) {
9174 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9175 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9177 $info['html'] .= '<ul class="list-unstyled m-l-1 row">'; // Holds userfriendly HTML representation.
9179 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9181 $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9182 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9184 // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9185 $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9187 if (function_exists('memory_get_usage')) {
9188 $info['memory_total'] = memory_get_usage();
9189 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9190 $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9191 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9192 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9195 if (function_exists('memory_get_peak_usage')) {
9196 $info['memory_peak'] = memory_get_peak_usage();
9197 $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9198 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9201 $info['html'] .= '</ul><ul class="list-unstyled m-l-1 row">';
9202 $inc = get_included_files();
9203 $info['includecount'] = count($inc);
9204 $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9205 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9207 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9208 // We can not track more performance before installation or before PAGE init, sorry.
9209 return $info;
9212 $filtermanager = filter_manager::instance();
9213 if (method_exists($filtermanager, 'get_performance_summary')) {
9214 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9215 $info = array_merge($filterinfo, $info);
9216 foreach ($filterinfo as $key => $value) {
9217 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9218 $info['txt'] .= "$key: $value ";
9222 $stringmanager = get_string_manager();
9223 if (method_exists($stringmanager, 'get_performance_summary')) {
9224 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9225 $info = array_merge($filterinfo, $info);
9226 foreach ($filterinfo as $key => $value) {
9227 $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9228 $info['txt'] .= "$key: $value ";
9232 if (!empty($PERF->logwrites)) {
9233 $info['logwrites'] = $PERF->logwrites;
9234 $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9235 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9238 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9239 $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9240 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9242 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9243 $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9244 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9246 if (function_exists('posix_times')) {
9247 $ptimes = posix_times();
9248 if (is_array($ptimes)) {
9249 foreach ($ptimes as $key => $val) {
9250 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9252 $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9253 $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9254 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9258 // Grab the load average for the last minute.
9259 // /proc will only work under some linux configurations
9260 // while uptime is there under MacOSX/Darwin and other unices.
9261 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9262 list($serverload) = explode(' ', $loadavg[0]);
9263 unset($loadavg);
9264 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9265 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9266 $serverload = $matches[1];
9267 } else {
9268 trigger_error('Could not parse uptime output!');
9271 if (!empty($serverload)) {
9272 $info['serverload'] = $serverload;
9273 $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9274 $info['txt'] .= "serverload: {$info['serverload']} ";
9277 // Display size of session if session started.
9278 if ($si = \core\session\manager::get_performance_info()) {
9279 $info['sessionsize'] = $si['size'];
9280 $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9281 $info['txt'] .= $si['txt'];
9284 $info['html'] .= '</ul>';
9285 if ($stats = cache_helper::get_stats()) {
9286 $html = '<ul class="cachesused list-unstyled m-l-1 row">';
9287 $html .= '<li class="cache-stats-heading font-weight-bold">Caches used (hits/misses/sets)</li>';
9288 $html .= '</ul><ul class="cachesused list-unstyled m-l-1">';
9289 $text = 'Caches used (hits/misses/sets): ';
9290 $hits = 0;
9291 $misses = 0;
9292 $sets = 0;
9293 foreach ($stats as $definition => $details) {
9294 switch ($details['mode']) {
9295 case cache_store::MODE_APPLICATION:
9296 $modeclass = 'application';
9297 $mode = ' <span title="application cache">[a]</span>';
9298 break;
9299 case cache_store::MODE_SESSION:
9300 $modeclass = 'session';
9301 $mode = ' <span title="session cache">[s]</span>';
9302 break;
9303 case cache_store::MODE_REQUEST:
9304 $modeclass = 'request';
9305 $mode = ' <span title="request cache">[r]</span>';
9306 break;
9308 $html .= '<ul class="cache-definition-stats list-unstyled m-l-1 m-b-1 cache-mode-'.$modeclass.' card d-inline-block">';
9309 $html .= '<li class="cache-definition-stats-heading p-t-1 card-header bg-dark bg-inverse font-weight-bold">' .
9310 $definition . $mode.'</li>';
9311 $text .= "$definition {";
9312 foreach ($details['stores'] as $store => $data) {
9313 $hits += $data['hits'];
9314 $misses += $data['misses'];
9315 $sets += $data['sets'];
9316 if ($data['hits'] == 0 and $data['misses'] > 0) {
9317 $cachestoreclass = 'nohits text-danger';
9318 } else if ($data['hits'] < $data['misses']) {
9319 $cachestoreclass = 'lowhits text-warning';
9320 } else {
9321 $cachestoreclass = 'hihits text-success';
9323 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9324 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">" .
9325 "$store: $data[hits] / $data[misses] / $data[sets]</li>";
9326 // This makes boxes of same sizes.
9327 if (count($details['stores']) == 1) {
9328 $html .= "<li class=\"cache-store-stats $cachestoreclass p-x-1\">&nbsp;</li>";
9331 $html .= '</ul>';
9332 $text .= '} ';
9334 $html .= '</ul> ';
9335 $html .= "<div class='cache-total-stats row'>Total: $hits / $misses / $sets</div>";
9336 $info['cachesused'] = "$hits / $misses / $sets";
9337 $info['html'] .= $html;
9338 $info['txt'] .= $text.'. ';
9339 } else {
9340 $info['cachesused'] = '0 / 0 / 0';
9341 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9342 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9345 $info['html'] = '<div class="performanceinfo siteinfo container-fluid">'.$info['html'].'</div>';
9346 return $info;
9350 * Delete directory or only its content
9352 * @param string $dir directory path
9353 * @param bool $contentonly
9354 * @return bool success, true also if dir does not exist
9356 function remove_dir($dir, $contentonly=false) {
9357 if (!file_exists($dir)) {
9358 // Nothing to do.
9359 return true;
9361 if (!$handle = opendir($dir)) {
9362 return false;
9364 $result = true;
9365 while (false!==($item = readdir($handle))) {
9366 if ($item != '.' && $item != '..') {
9367 if (is_dir($dir.'/'.$item)) {
9368 $result = remove_dir($dir.'/'.$item) && $result;
9369 } else {
9370 $result = unlink($dir.'/'.$item) && $result;
9374 closedir($handle);
9375 if ($contentonly) {
9376 clearstatcache(); // Make sure file stat cache is properly invalidated.
9377 return $result;
9379 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9380 clearstatcache(); // Make sure file stat cache is properly invalidated.
9381 return $result;
9385 * Detect if an object or a class contains a given property
9386 * will take an actual object or the name of a class
9388 * @param mix $obj Name of class or real object to test
9389 * @param string $property name of property to find
9390 * @return bool true if property exists
9392 function object_property_exists( $obj, $property ) {
9393 if (is_string( $obj )) {
9394 $properties = get_class_vars( $obj );
9395 } else {
9396 $properties = get_object_vars( $obj );
9398 return array_key_exists( $property, $properties );
9402 * Converts an object into an associative array
9404 * This function converts an object into an associative array by iterating
9405 * over its public properties. Because this function uses the foreach
9406 * construct, Iterators are respected. It works recursively on arrays of objects.
9407 * Arrays and simple values are returned as is.
9409 * If class has magic properties, it can implement IteratorAggregate
9410 * and return all available properties in getIterator()
9412 * @param mixed $var
9413 * @return array
9415 function convert_to_array($var) {
9416 $result = array();
9418 // Loop over elements/properties.
9419 foreach ($var as $key => $value) {
9420 // Recursively convert objects.
9421 if (is_object($value) || is_array($value)) {
9422 $result[$key] = convert_to_array($value);
9423 } else {
9424 // Simple values are untouched.
9425 $result[$key] = $value;
9428 return $result;
9432 * Detect a custom script replacement in the data directory that will
9433 * replace an existing moodle script
9435 * @return string|bool full path name if a custom script exists, false if no custom script exists
9437 function custom_script_path() {
9438 global $CFG, $SCRIPT;
9440 if ($SCRIPT === null) {
9441 // Probably some weird external script.
9442 return false;
9445 $scriptpath = $CFG->customscripts . $SCRIPT;
9447 // Check the custom script exists.
9448 if (file_exists($scriptpath) and is_file($scriptpath)) {
9449 return $scriptpath;
9450 } else {
9451 return false;
9456 * Returns whether or not the user object is a remote MNET user. This function
9457 * is in moodlelib because it does not rely on loading any of the MNET code.
9459 * @param object $user A valid user object
9460 * @return bool True if the user is from a remote Moodle.
9462 function is_mnet_remote_user($user) {
9463 global $CFG;
9465 if (!isset($CFG->mnet_localhost_id)) {
9466 include_once($CFG->dirroot . '/mnet/lib.php');
9467 $env = new mnet_environment();
9468 $env->init();
9469 unset($env);
9472 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9476 * This function will search for browser prefereed languages, setting Moodle
9477 * to use the best one available if $SESSION->lang is undefined
9479 function setup_lang_from_browser() {
9480 global $CFG, $SESSION, $USER;
9482 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9483 // Lang is defined in session or user profile, nothing to do.
9484 return;
9487 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9488 return;
9491 // Extract and clean langs from headers.
9492 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9493 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9494 $rawlangs = explode(',', $rawlangs); // Convert to array.
9495 $langs = array();
9497 $order = 1.0;
9498 foreach ($rawlangs as $lang) {
9499 if (strpos($lang, ';') === false) {
9500 $langs[(string)$order] = $lang;
9501 $order = $order-0.01;
9502 } else {
9503 $parts = explode(';', $lang);
9504 $pos = strpos($parts[1], '=');
9505 $langs[substr($parts[1], $pos+1)] = $parts[0];
9508 krsort($langs, SORT_NUMERIC);
9510 // Look for such langs under standard locations.
9511 foreach ($langs as $lang) {
9512 // Clean it properly for include.
9513 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9514 if (get_string_manager()->translation_exists($lang, false)) {
9515 // Lang exists, set it in session.
9516 $SESSION->lang = $lang;
9517 // We have finished. Go out.
9518 break;
9521 return;
9525 * Check if $url matches anything in proxybypass list
9527 * Any errors just result in the proxy being used (least bad)
9529 * @param string $url url to check
9530 * @return boolean true if we should bypass the proxy
9532 function is_proxybypass( $url ) {
9533 global $CFG;
9535 // Sanity check.
9536 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9537 return false;
9540 // Get the host part out of the url.
9541 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9542 return false;
9545 // Get the possible bypass hosts into an array.
9546 $matches = explode( ',', $CFG->proxybypass );
9548 // Check for a match.
9549 // (IPs need to match the left hand side and hosts the right of the url,
9550 // but we can recklessly check both as there can't be a false +ve).
9551 foreach ($matches as $match) {
9552 $match = trim($match);
9554 // Try for IP match (Left side).
9555 $lhs = substr($host, 0, strlen($match));
9556 if (strcasecmp($match, $lhs)==0) {
9557 return true;
9560 // Try for host match (Right side).
9561 $rhs = substr($host, -strlen($match));
9562 if (strcasecmp($match, $rhs)==0) {
9563 return true;
9567 // Nothing matched.
9568 return false;
9572 * Check if the passed navigation is of the new style
9574 * @param mixed $navigation
9575 * @return bool true for yes false for no
9577 function is_newnav($navigation) {
9578 if (is_array($navigation) && !empty($navigation['newnav'])) {
9579 return true;
9580 } else {
9581 return false;
9586 * Checks whether the given variable name is defined as a variable within the given object.
9588 * This will NOT work with stdClass objects, which have no class variables.
9590 * @param string $var The variable name
9591 * @param object $object The object to check
9592 * @return boolean
9594 function in_object_vars($var, $object) {
9595 $classvars = get_class_vars(get_class($object));
9596 $classvars = array_keys($classvars);
9597 return in_array($var, $classvars);
9601 * Returns an array without repeated objects.
9602 * This function is similar to array_unique, but for arrays that have objects as values
9604 * @param array $array
9605 * @param bool $keepkeyassoc
9606 * @return array
9608 function object_array_unique($array, $keepkeyassoc = true) {
9609 $duplicatekeys = array();
9610 $tmp = array();
9612 foreach ($array as $key => $val) {
9613 // Convert objects to arrays, in_array() does not support objects.
9614 if (is_object($val)) {
9615 $val = (array)$val;
9618 if (!in_array($val, $tmp)) {
9619 $tmp[] = $val;
9620 } else {
9621 $duplicatekeys[] = $key;
9625 foreach ($duplicatekeys as $key) {
9626 unset($array[$key]);
9629 return $keepkeyassoc ? $array : array_values($array);
9633 * Is a userid the primary administrator?
9635 * @param int $userid int id of user to check
9636 * @return boolean
9638 function is_primary_admin($userid) {
9639 $primaryadmin = get_admin();
9641 if ($userid == $primaryadmin->id) {
9642 return true;
9643 } else {
9644 return false;
9649 * Returns the site identifier
9651 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9653 function get_site_identifier() {
9654 global $CFG;
9655 // Check to see if it is missing. If so, initialise it.
9656 if (empty($CFG->siteidentifier)) {
9657 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9659 // Return it.
9660 return $CFG->siteidentifier;
9664 * Check whether the given password has no more than the specified
9665 * number of consecutive identical characters.
9667 * @param string $password password to be checked against the password policy
9668 * @param integer $maxchars maximum number of consecutive identical characters
9669 * @return bool
9671 function check_consecutive_identical_characters($password, $maxchars) {
9673 if ($maxchars < 1) {
9674 return true; // Zero 0 is to disable this check.
9676 if (strlen($password) <= $maxchars) {
9677 return true; // Too short to fail this test.
9680 $previouschar = '';
9681 $consecutivecount = 1;
9682 foreach (str_split($password) as $char) {
9683 if ($char != $previouschar) {
9684 $consecutivecount = 1;
9685 } else {
9686 $consecutivecount++;
9687 if ($consecutivecount > $maxchars) {
9688 return false; // Check failed already.
9692 $previouschar = $char;
9695 return true;
9699 * Helper function to do partial function binding.
9700 * so we can use it for preg_replace_callback, for example
9701 * this works with php functions, user functions, static methods and class methods
9702 * it returns you a callback that you can pass on like so:
9704 * $callback = partial('somefunction', $arg1, $arg2);
9705 * or
9706 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9707 * or even
9708 * $obj = new someclass();
9709 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9711 * and then the arguments that are passed through at calltime are appended to the argument list.
9713 * @param mixed $function a php callback
9714 * @param mixed $arg1,... $argv arguments to partially bind with
9715 * @return array Array callback
9717 function partial() {
9718 if (!class_exists('partial')) {
9720 * Used to manage function binding.
9721 * @copyright 2009 Penny Leach
9722 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9724 class partial{
9725 /** @var array */
9726 public $values = array();
9727 /** @var string The function to call as a callback. */
9728 public $func;
9730 * Constructor
9731 * @param string $func
9732 * @param array $args
9734 public function __construct($func, $args) {
9735 $this->values = $args;
9736 $this->func = $func;
9739 * Calls the callback function.
9740 * @return mixed
9742 public function method() {
9743 $args = func_get_args();
9744 return call_user_func_array($this->func, array_merge($this->values, $args));
9748 $args = func_get_args();
9749 $func = array_shift($args);
9750 $p = new partial($func, $args);
9751 return array($p, 'method');
9755 * helper function to load up and initialise the mnet environment
9756 * this must be called before you use mnet functions.
9758 * @return mnet_environment the equivalent of old $MNET global
9760 function get_mnet_environment() {
9761 global $CFG;
9762 require_once($CFG->dirroot . '/mnet/lib.php');
9763 static $instance = null;
9764 if (empty($instance)) {
9765 $instance = new mnet_environment();
9766 $instance->init();
9768 return $instance;
9772 * during xmlrpc server code execution, any code wishing to access
9773 * information about the remote peer must use this to get it.
9775 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9777 function get_mnet_remote_client() {
9778 if (!defined('MNET_SERVER')) {
9779 debugging(get_string('notinxmlrpcserver', 'mnet'));
9780 return false;
9782 global $MNET_REMOTE_CLIENT;
9783 if (isset($MNET_REMOTE_CLIENT)) {
9784 return $MNET_REMOTE_CLIENT;
9786 return false;
9790 * during the xmlrpc server code execution, this will be called
9791 * to setup the object returned by {@link get_mnet_remote_client}
9793 * @param mnet_remote_client $client the client to set up
9794 * @throws moodle_exception
9796 function set_mnet_remote_client($client) {
9797 if (!defined('MNET_SERVER')) {
9798 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9800 global $MNET_REMOTE_CLIENT;
9801 $MNET_REMOTE_CLIENT = $client;
9805 * return the jump url for a given remote user
9806 * this is used for rewriting forum post links in emails, etc
9808 * @param stdclass $user the user to get the idp url for
9810 function mnet_get_idp_jump_url($user) {
9811 global $CFG;
9813 static $mnetjumps = array();
9814 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9815 $idp = mnet_get_peer_host($user->mnethostid);
9816 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9817 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9819 return $mnetjumps[$user->mnethostid];
9823 * Gets the homepage to use for the current user
9825 * @return int One of HOMEPAGE_*
9827 function get_home_page() {
9828 global $CFG;
9830 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9831 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9832 return HOMEPAGE_MY;
9833 } else {
9834 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9837 return HOMEPAGE_SITE;
9841 * Gets the name of a course to be displayed when showing a list of courses.
9842 * By default this is just $course->fullname but user can configure it. The
9843 * result of this function should be passed through print_string.
9844 * @param stdClass|course_in_list $course Moodle course object
9845 * @return string Display name of course (either fullname or short + fullname)
9847 function get_course_display_name_for_list($course) {
9848 global $CFG;
9849 if (!empty($CFG->courselistshortnames)) {
9850 if (!($course instanceof stdClass)) {
9851 $course = (object)convert_to_array($course);
9853 return get_string('courseextendednamedisplay', '', $course);
9854 } else {
9855 return $course->fullname;
9860 * Safe analogue of unserialize() that can only parse arrays
9862 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
9863 * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
9864 * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
9866 * @param string $expression
9867 * @return array|bool either parsed array or false if parsing was impossible.
9869 function unserialize_array($expression) {
9870 $subs = [];
9871 // Find nested arrays, parse them and store in $subs , substitute with special string.
9872 while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
9873 $key = '--SUB' . count($subs) . '--';
9874 $subs[$key] = unserialize_array($matches[2]);
9875 if ($subs[$key] === false) {
9876 return false;
9878 $expression = str_replace($matches[2], $key . ';', $expression);
9881 // Check the expression is an array.
9882 if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
9883 return false;
9885 // Get the size and elements of an array (key;value;key;value;....).
9886 $parts = explode(';', $matches1[2]);
9887 $size = intval($matches1[1]);
9888 if (count($parts) < $size * 2 + 1) {
9889 return false;
9891 // Analyze each part and make sure it is an integer or string or a substitute.
9892 $value = [];
9893 for ($i = 0; $i < $size * 2; $i++) {
9894 if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
9895 $parts[$i] = (int)$matches2[1];
9896 } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
9897 $parts[$i] = $matches3[2];
9898 } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
9899 $parts[$i] = $subs[$parts[$i]];
9900 } else {
9901 return false;
9904 // Combine keys and values.
9905 for ($i = 0; $i < $size * 2; $i += 2) {
9906 $value[$parts[$i]] = $parts[$i+1];
9908 return $value;
9912 * The lang_string class
9914 * This special class is used to create an object representation of a string request.
9915 * It is special because processing doesn't occur until the object is first used.
9916 * The class was created especially to aid performance in areas where strings were
9917 * required to be generated but were not necessarily used.
9918 * As an example the admin tree when generated uses over 1500 strings, of which
9919 * normally only 1/3 are ever actually printed at any time.
9920 * The performance advantage is achieved by not actually processing strings that
9921 * arn't being used, as such reducing the processing required for the page.
9923 * How to use the lang_string class?
9924 * There are two methods of using the lang_string class, first through the
9925 * forth argument of the get_string function, and secondly directly.
9926 * The following are examples of both.
9927 * 1. Through get_string calls e.g.
9928 * $string = get_string($identifier, $component, $a, true);
9929 * $string = get_string('yes', 'moodle', null, true);
9930 * 2. Direct instantiation
9931 * $string = new lang_string($identifier, $component, $a, $lang);
9932 * $string = new lang_string('yes');
9934 * How do I use a lang_string object?
9935 * The lang_string object makes use of a magic __toString method so that you
9936 * are able to use the object exactly as you would use a string in most cases.
9937 * This means you are able to collect it into a variable and then directly
9938 * echo it, or concatenate it into another string, or similar.
9939 * The other thing you can do is manually get the string by calling the
9940 * lang_strings out method e.g.
9941 * $string = new lang_string('yes');
9942 * $string->out();
9943 * Also worth noting is that the out method can take one argument, $lang which
9944 * allows the developer to change the language on the fly.
9946 * When should I use a lang_string object?
9947 * The lang_string object is designed to be used in any situation where a
9948 * string may not be needed, but needs to be generated.
9949 * The admin tree is a good example of where lang_string objects should be
9950 * used.
9951 * A more practical example would be any class that requries strings that may
9952 * not be printed (after all classes get renderer by renderers and who knows
9953 * what they will do ;))
9955 * When should I not use a lang_string object?
9956 * Don't use lang_strings when you are going to use a string immediately.
9957 * There is no need as it will be processed immediately and there will be no
9958 * advantage, and in fact perhaps a negative hit as a class has to be
9959 * instantiated for a lang_string object, however get_string won't require
9960 * that.
9962 * Limitations:
9963 * 1. You cannot use a lang_string object as an array offset. Doing so will
9964 * result in PHP throwing an error. (You can use it as an object property!)
9966 * @package core
9967 * @category string
9968 * @copyright 2011 Sam Hemelryk
9969 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9971 class lang_string {
9973 /** @var string The strings identifier */
9974 protected $identifier;
9975 /** @var string The strings component. Default '' */
9976 protected $component = '';
9977 /** @var array|stdClass Any arguments required for the string. Default null */
9978 protected $a = null;
9979 /** @var string The language to use when processing the string. Default null */
9980 protected $lang = null;
9982 /** @var string The processed string (once processed) */
9983 protected $string = null;
9986 * A special boolean. If set to true then the object has been woken up and
9987 * cannot be regenerated. If this is set then $this->string MUST be used.
9988 * @var bool
9990 protected $forcedstring = false;
9993 * Constructs a lang_string object
9995 * This function should do as little processing as possible to ensure the best
9996 * performance for strings that won't be used.
9998 * @param string $identifier The strings identifier
9999 * @param string $component The strings component
10000 * @param stdClass|array $a Any arguments the string requires
10001 * @param string $lang The language to use when processing the string.
10002 * @throws coding_exception
10004 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10005 if (empty($component)) {
10006 $component = 'moodle';
10009 $this->identifier = $identifier;
10010 $this->component = $component;
10011 $this->lang = $lang;
10013 // We MUST duplicate $a to ensure that it if it changes by reference those
10014 // changes are not carried across.
10015 // To do this we always ensure $a or its properties/values are strings
10016 // and that any properties/values that arn't convertable are forgotten.
10017 if (!empty($a)) {
10018 if (is_scalar($a)) {
10019 $this->a = $a;
10020 } else if ($a instanceof lang_string) {
10021 $this->a = $a->out();
10022 } else if (is_object($a) or is_array($a)) {
10023 $a = (array)$a;
10024 $this->a = array();
10025 foreach ($a as $key => $value) {
10026 // Make sure conversion errors don't get displayed (results in '').
10027 if (is_array($value)) {
10028 $this->a[$key] = '';
10029 } else if (is_object($value)) {
10030 if (method_exists($value, '__toString')) {
10031 $this->a[$key] = $value->__toString();
10032 } else {
10033 $this->a[$key] = '';
10035 } else {
10036 $this->a[$key] = (string)$value;
10042 if (debugging(false, DEBUG_DEVELOPER)) {
10043 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10044 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10046 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10047 throw new coding_exception('Invalid string compontent. Please check your string definition');
10049 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10050 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10056 * Processes the string.
10058 * This function actually processes the string, stores it in the string property
10059 * and then returns it.
10060 * You will notice that this function is VERY similar to the get_string method.
10061 * That is because it is pretty much doing the same thing.
10062 * However as this function is an upgrade it isn't as tolerant to backwards
10063 * compatibility.
10065 * @return string
10066 * @throws coding_exception
10068 protected function get_string() {
10069 global $CFG;
10071 // Check if we need to process the string.
10072 if ($this->string === null) {
10073 // Check the quality of the identifier.
10074 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10075 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);
10078 // Process the string.
10079 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10080 // Debugging feature lets you display string identifier and component.
10081 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10082 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10085 // Return the string.
10086 return $this->string;
10090 * Returns the string
10092 * @param string $lang The langauge to use when processing the string
10093 * @return string
10095 public function out($lang = null) {
10096 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10097 if ($this->forcedstring) {
10098 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10099 return $this->get_string();
10101 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10102 return $translatedstring->out();
10104 return $this->get_string();
10108 * Magic __toString method for printing a string
10110 * @return string
10112 public function __toString() {
10113 return $this->get_string();
10117 * Magic __set_state method used for var_export
10119 * @return string
10121 public function __set_state() {
10122 return $this->get_string();
10126 * Prepares the lang_string for sleep and stores only the forcedstring and
10127 * string properties... the string cannot be regenerated so we need to ensure
10128 * it is generated for this.
10130 * @return string
10132 public function __sleep() {
10133 $this->get_string();
10134 $this->forcedstring = true;
10135 return array('forcedstring', 'string', 'lang');
10139 * Returns the identifier.
10141 * @return string
10143 public function get_identifier() {
10144 return $this->identifier;
10148 * Returns the component.
10150 * @return string
10152 public function get_component() {
10153 return $this->component;